@aestheticfunction/dspack-emit 0.3.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 (62) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +285 -0
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +186 -0
  5. package/dist/index.d.ts +16 -0
  6. package/dist/index.js +15 -0
  7. package/dist/targets/a2ui/surface.d.ts +43 -0
  8. package/dist/targets/a2ui/surface.js +219 -0
  9. package/dist/targets/csr.d.ts +15 -0
  10. package/dist/targets/csr.js +9 -0
  11. package/dist/targets/json-render/codegen.d.ts +35 -0
  12. package/dist/targets/json-render/codegen.js +91 -0
  13. package/dist/targets/json-render/emit.d.ts +66 -0
  14. package/dist/targets/json-render/emit.js +142 -0
  15. package/dist/targets/json-render/model.d.ts +57 -0
  16. package/dist/targets/json-render/model.js +99 -0
  17. package/dist/targets/json-render/profile.d.ts +23 -0
  18. package/dist/targets/json-render/profile.js +3 -0
  19. package/dist/transform/color.d.ts +11 -0
  20. package/dist/transform/color.js +53 -0
  21. package/dist/transform/emit.d.ts +15 -0
  22. package/dist/transform/emit.js +100 -0
  23. package/dist/transform/index.d.ts +26 -0
  24. package/dist/transform/index.js +26 -0
  25. package/dist/transform/inline-defs.d.ts +22 -0
  26. package/dist/transform/inline-defs.js +172 -0
  27. package/dist/transform/mapping.d.ts +24 -0
  28. package/dist/transform/mapping.js +322 -0
  29. package/dist/transform/profiles.d.ts +120 -0
  30. package/dist/transform/profiles.js +282 -0
  31. package/dist/transform/report.d.ts +13 -0
  32. package/dist/transform/report.js +76 -0
  33. package/dist/types.d.ts +103 -0
  34. package/dist/types.js +6 -0
  35. package/dist/validate/ajv.d.ts +15 -0
  36. package/dist/validate/ajv.js +132 -0
  37. package/dist/validate/meta/a2ui-catalog.meta.0_9_1.json +39 -0
  38. package/dist/validate/meta/a2ui-catalog.meta.1_0.json +34 -0
  39. package/package.json +41 -0
  40. package/src/cli.ts +197 -0
  41. package/src/index.ts +39 -0
  42. package/src/ingestion.test.ts +156 -0
  43. package/src/json-render-emit.test.ts +196 -0
  44. package/src/surface-emit.test.ts +184 -0
  45. package/src/targets/a2ui/surface.ts +287 -0
  46. package/src/targets/csr.ts +23 -0
  47. package/src/targets/json-render/codegen.ts +135 -0
  48. package/src/targets/json-render/emit.ts +227 -0
  49. package/src/targets/json-render/model.ts +170 -0
  50. package/src/targets/json-render/profile.ts +26 -0
  51. package/src/transform/color.ts +52 -0
  52. package/src/transform/emit.ts +128 -0
  53. package/src/transform/index.ts +54 -0
  54. package/src/transform/inline-defs.ts +209 -0
  55. package/src/transform/mapping.ts +391 -0
  56. package/src/transform/profiles.ts +425 -0
  57. package/src/transform/report.ts +105 -0
  58. package/src/transform.test.ts +112 -0
  59. package/src/types.ts +145 -0
  60. package/src/validate/ajv.ts +151 -0
  61. package/src/validate/meta/a2ui-catalog.meta.0_9_1.json +39 -0
  62. package/src/validate/meta/a2ui-catalog.meta.1_0.json +34 -0
package/dist/cli.js ADDED
@@ -0,0 +1,186 @@
1
+ #!/usr/bin/env -S npx tsx
2
+ /**
3
+ * dspack-emit CLI.
4
+ *
5
+ * tsx src/cli.ts --in <dspack.json> --a2ui-version <0.9.1|1.0> --out <dir> [--surface <surface.json>]
6
+ * [--emit-surface <surface.dsurface.json>]
7
+ * tsx src/cli.ts --target json-render --in <dspack.json> --out <dir>
8
+ * [--emit-surface <surface.dsurface.json>]
9
+ *
10
+ * Default target (a2ui): emits a versioned A2UI catalog + a
11
+ * validation/fidelity report. Exits non-zero if the hard gate (catalog schema
12
+ * validation) fails, so it is CI-friendly. With --emit-surface, additionally
13
+ * compiles a dspack surface document (CSR) into A2UI surface messages
14
+ * (out/<name>.surface.json), instance-validated against the freshly generated
15
+ * catalog (gate A3). A malformed or out-of-vocabulary surface exits 4.
16
+ *
17
+ * json-render target: generates catalog.ts + registry.tsx (Zod component
18
+ * defs + typed stub registry) from the contract. With --emit-surface,
19
+ * additionally compiles the CSR into a json-render spec
20
+ * (out/<name>.spec.json), validated against the catalog model — failure
21
+ * exits 4, mirroring the a2ui path. The framework-level gates J1–J3 (tsc +
22
+ * real Zod parse) run in gates/json-render, not here.
23
+ */
24
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
25
+ import { basename, join, resolve } from "node:path";
26
+ import { transform } from "./transform/index.js";
27
+ import { emitSurface, EmitSurfaceError } from "./targets/a2ui/surface.js";
28
+ import { generateJsonRenderModules } from "./targets/json-render/codegen.js";
29
+ import { emitJsonRenderSpec, EmitJsonRenderError, validateSpecAgainstModel } from "./targets/json-render/emit.js";
30
+ /** Flags that take no value; their presence means `true`. */
31
+ const BOOLEAN_FLAGS = new Set(["strict-coverage"]);
32
+ function parseArgs(argv) {
33
+ // Supports `--key value`, `--key=value`, and valueless boolean flags; fails fast
34
+ // on a malformed flag or a value-taking `--key` missing its value.
35
+ const m = new Map();
36
+ for (let i = 0; i < argv.length; i++) {
37
+ const tok = argv[i];
38
+ if (!tok.startsWith("--"))
39
+ fail(`unexpected argument '${tok}' (flags must start with --)`);
40
+ const eq = tok.indexOf("=");
41
+ if (eq !== -1) {
42
+ m.set(tok.slice(2, eq), tok.slice(eq + 1));
43
+ }
44
+ else if (BOOLEAN_FLAGS.has(tok.slice(2))) {
45
+ m.set(tok.slice(2), "true");
46
+ }
47
+ else {
48
+ const value = argv[++i];
49
+ if (value === undefined)
50
+ fail(`flag '${tok}' is missing a value`);
51
+ m.set(tok.slice(2), value);
52
+ }
53
+ }
54
+ const target = m.get("target") ?? "a2ui";
55
+ if (target !== "a2ui" && target !== "json-render") {
56
+ fail("--target must be 'a2ui' or 'json-render'");
57
+ }
58
+ const version = m.get("a2ui-version");
59
+ if (target === "a2ui" && version !== "0.9.1" && version !== "1.0") {
60
+ fail("--a2ui-version must be '0.9.1' or '1.0'");
61
+ }
62
+ if (target === "json-render" && version !== undefined) {
63
+ fail("--a2ui-version does not apply to --target json-render");
64
+ }
65
+ const input = m.get("in");
66
+ if (!input)
67
+ fail("--in <dspack.json> is required");
68
+ return {
69
+ target,
70
+ in: input,
71
+ version: (version ?? "0.9.1"),
72
+ out: m.get("out") ?? "out",
73
+ surface: m.get("surface") ?? "surface/settings-card.surface.json",
74
+ emitSurface: m.get("emit-surface"),
75
+ strictCoverage: m.get("strict-coverage") === "true",
76
+ };
77
+ }
78
+ function fail(msg) {
79
+ console.error(`error: ${msg}`);
80
+ process.exit(2);
81
+ }
82
+ function jsonRenderMain(args, doc) {
83
+ const tag = "[json-render]";
84
+ const { catalogTs, registryTsx, model } = generateJsonRenderModules(doc);
85
+ mkdirSync(resolve(args.out), { recursive: true });
86
+ const base = resolve(args.out);
87
+ writeFileSync(join(base, "catalog.ts"), catalogTs);
88
+ writeFileSync(join(base, "registry.tsx"), registryTsx);
89
+ console.log(`${tag} catalog -> ${join(args.out, "catalog.ts")} (${model.components.length} components)`);
90
+ console.log(`${tag} registry -> ${join(args.out, "registry.tsx")} (stub implementations)`);
91
+ for (const component of model.components) {
92
+ for (const excluded of component.excludedProps) {
93
+ console.log(`${tag} note prop-excluded: ${component.dspackId}.${excluded.name} — ${excluded.reason}`);
94
+ }
95
+ }
96
+ if (args.emitSurface) {
97
+ const csr = JSON.parse(readFileSync(resolve(args.emitSurface), "utf8"));
98
+ let emitted;
99
+ try {
100
+ emitted = emitJsonRenderSpec(csr, doc);
101
+ }
102
+ catch (e) {
103
+ if (e instanceof EmitJsonRenderError) {
104
+ console.error(`${tag} EMIT-SPEC FAILED: ${e.message}`);
105
+ process.exit(4);
106
+ }
107
+ throw e;
108
+ }
109
+ const name = basename(args.emitSurface).replace(/\.dsurface\.json$|\.json$/, "");
110
+ const outPath = join(base, `${name}.spec.json`);
111
+ writeFileSync(outPath, JSON.stringify(emitted.spec, null, 2) + "\n");
112
+ for (const w of emitted.warnings)
113
+ console.log(`${tag} note ${w.code}: ${w.message}`);
114
+ // Offline mirror of gates J2/J3 over the emitted spec; the framework-level
115
+ // gates (tsc + real Zod parse) run in gates/json-render.
116
+ const findings = validateSpecAgainstModel(emitted.spec, model);
117
+ console.log(`${tag} emitted spec -> ${outPath}`);
118
+ console.log(`${tag} ${findings.length === 0 ? "PASS" : "FAIL"} model-vocabulary (emitted spec vs generated catalog model)`);
119
+ if (findings.length > 0) {
120
+ for (const f of findings)
121
+ console.error(`${tag} ${f.path}: ${f.message}`);
122
+ process.exit(4);
123
+ }
124
+ }
125
+ }
126
+ function main() {
127
+ const args = parseArgs(process.argv.slice(2));
128
+ const seg = args.version === "0.9.1" ? "v0_9_1" : "v1_0";
129
+ const doc = JSON.parse(readFileSync(resolve(args.in), "utf8"));
130
+ if (args.target === "json-render") {
131
+ jsonRenderMain(args, doc);
132
+ return;
133
+ }
134
+ const surface = JSON.parse(readFileSync(resolve(args.surface), "utf8"));
135
+ const { catalog, mapping, validation, report } = transform(doc, args.version, surface);
136
+ mkdirSync(resolve(args.out), { recursive: true });
137
+ const base = resolve(args.out);
138
+ writeFileSync(join(base, `catalog.${seg}.json`), JSON.stringify(catalog, null, 2) + "\n");
139
+ writeFileSync(join(base, `validation-report.${seg}.md`), report.md);
140
+ writeFileSync(join(base, `validation-report.${seg}.json`), JSON.stringify(report.json, null, 2) + "\n");
141
+ const tag = `[a2ui ${args.version}]`;
142
+ console.log(`${tag} catalog -> ${join(args.out, `catalog.${seg}.json`)}`);
143
+ console.log(`${tag} report -> ${join(args.out, `validation-report.${seg}.md`)}`);
144
+ for (const g of validation.gates)
145
+ console.log(`${tag} ${g.pass ? "PASS" : "FAIL"} ${g.name}`);
146
+ console.log(`${tag} ${validation.pass ? "VALIDATION PASSED" : "VALIDATION FAILED"}`);
147
+ const unclassified = mapping.coverage.filter((c) => c.disposition === "unclassified");
148
+ if (unclassified.length) {
149
+ console.log(`${tag} COVERAGE: ${unclassified.length} unclassified component(s): ${unclassified.map((c) => c.id).join(", ")}`);
150
+ }
151
+ if (!validation.pass)
152
+ process.exit(1);
153
+ if (args.strictCoverage && unclassified.length)
154
+ process.exit(3);
155
+ if (args.emitSurface) {
156
+ const csr = JSON.parse(readFileSync(resolve(args.emitSurface), "utf8"));
157
+ let emitted;
158
+ try {
159
+ emitted = emitSurface(csr, doc);
160
+ }
161
+ catch (e) {
162
+ if (e instanceof EmitSurfaceError) {
163
+ console.error(`${tag} EMIT-SURFACE FAILED: ${e.message}`);
164
+ process.exit(4);
165
+ }
166
+ throw e;
167
+ }
168
+ const name = basename(args.emitSurface).replace(/\.dsurface\.json$|\.json$/, "");
169
+ const outPath = join(base, `${name}.surface.json`);
170
+ writeFileSync(outPath, JSON.stringify({ messages: emitted.messages }, null, 2) + "\n");
171
+ for (const w of emitted.warnings)
172
+ console.log(`${tag} note ${w.code}: ${w.message}`);
173
+ // Gate A3 over the emitted surface: its instances must validate against the
174
+ // catalog generated in this same run.
175
+ const check = transform(doc, args.version, { messages: emitted.messages });
176
+ const instanceGate = check.validation.gates.find((g) => g.name === "instance");
177
+ console.log(`${tag} emitted surface -> ${outPath}`);
178
+ console.log(`${tag} ${instanceGate?.pass ? "PASS" : "FAIL"} instance (emitted surface vs generated catalog)`);
179
+ if (!instanceGate?.pass) {
180
+ for (const err of instanceGate?.errors ?? [])
181
+ console.error(`${tag} ${err}`);
182
+ process.exit(4);
183
+ }
184
+ }
185
+ }
186
+ main();
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Public library surface of dspack-emit (the multi-target dspack emitter).
3
+ *
4
+ * Consumers (dspack-gen) depend on exactly this module; everything not
5
+ * re-exported here is internal. The CLI (src/cli.ts) is a thin wrapper over
6
+ * the same functions.
7
+ */
8
+ export { transform, transformFromJson, type TransformOutput } from "./transform/index.js";
9
+ export { shadcnProfile, type Profile, type ComponentPlan, type SurfacePlanDirectives } from "./transform/profiles.js";
10
+ export { validateCatalog, extractInstances, type ValidationReport, type GateResult } from "./validate/ajv.js";
11
+ export { emitSurface, slug, EmitSurfaceError, type EmitSurfaceResult, type EmitSurfaceOptions, } from "./targets/a2ui/surface.js";
12
+ export { emitJsonRenderSpec, validateSpecAgainstModel, EmitJsonRenderError, type EmitJsonRenderResult, type EmitJsonRenderOptions, type JsonRenderSpec, type JsonRenderElement, type SpecFinding, } from "./targets/json-render/emit.js";
13
+ export { generateJsonRenderModules, type JsonRenderModules } from "./targets/json-render/codegen.js";
14
+ export { buildCatalogModel, type CatalogModel, type CatalogComponent, type CatalogProp } from "./targets/json-render/model.js";
15
+ export { shadcnJsonRenderProfile, type JsonRenderProfile } from "./targets/json-render/profile.js";
16
+ export type { A2uiCatalog, A2uiVersion, DspackDoc, DspackSurface, SurfaceNode, Json, Warning, } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Public library surface of dspack-emit (the multi-target dspack emitter).
3
+ *
4
+ * Consumers (dspack-gen) depend on exactly this module; everything not
5
+ * re-exported here is internal. The CLI (src/cli.ts) is a thin wrapper over
6
+ * the same functions.
7
+ */
8
+ export { transform, transformFromJson } from "./transform/index.js";
9
+ export { shadcnProfile } from "./transform/profiles.js";
10
+ export { validateCatalog, extractInstances } from "./validate/ajv.js";
11
+ export { emitSurface, slug, EmitSurfaceError, } from "./targets/a2ui/surface.js";
12
+ export { emitJsonRenderSpec, validateSpecAgainstModel, EmitJsonRenderError, } from "./targets/json-render/emit.js";
13
+ export { generateJsonRenderModules } from "./targets/json-render/codegen.js";
14
+ export { buildCatalogModel } from "./targets/json-render/model.js";
15
+ export { shadcnJsonRenderProfile } from "./targets/json-render/profile.js";
@@ -0,0 +1,43 @@
1
+ /**
2
+ * dspack surface → A2UI v0.9 surface emitter.
3
+ *
4
+ * Compiles a dspack surface document (the protocol-neutral component tree
5
+ * defined by dspack.surface.v0_1.schema.json) into the A2UI message array
6
+ * shape used by surface/*.surface.json: one `createSurface` (catalogId +
7
+ * dspack-token theme) followed by one `updateComponents` with a flat,
8
+ * id-referenced component list.
9
+ *
10
+ * Deterministic by construction: same surface + contract + profile => same
11
+ * messages. All projection knowledge is data in the profile's `surfacePlan`
12
+ * directives; this engine contains no component-name-specific code.
13
+ *
14
+ * Honest scope (mirrors MAPPING.md):
15
+ * - Compound composition flattens per the documented casualty mapping
16
+ * (`subText` / `subButtonText` consume the node's whole subtree).
17
+ * - A2UI requires declarative actions the surface format does not express;
18
+ * they are synthesized (deterministic event-name slug) and recorded as
19
+ * warnings, not silently invented.
20
+ * - The message envelope is A2UI v0.9 (`version: "v0.9"`), the version the
21
+ * maintained renderers speak. The emitted component instances themselves
22
+ * are version-independent and instance-validate (gate A3) against both
23
+ * generated catalogs.
24
+ */
25
+ import type { DspackDoc, DspackSurface, Json, Warning } from "../../types.js";
26
+ import { type Profile } from "../../transform/profiles.js";
27
+ export declare class EmitSurfaceError extends Error {
28
+ readonly path: string;
29
+ constructor(message: string, path: string);
30
+ }
31
+ export interface EmitSurfaceResult {
32
+ /** The A2UI v0.9 message array (createSurface + updateComponents). */
33
+ messages: Json[];
34
+ /** Every synthesis/drop performed — nothing is silent. */
35
+ warnings: Warning[];
36
+ }
37
+ export interface EmitSurfaceOptions {
38
+ profile?: Profile;
39
+ /** Defaults to a slug of the surface intent. */
40
+ surfaceId?: string;
41
+ }
42
+ export declare function emitSurface(surface: DspackSurface, doc: DspackDoc, options?: EmitSurfaceOptions): EmitSurfaceResult;
43
+ export declare function slug(value: string): string;
@@ -0,0 +1,219 @@
1
+ import { shadcnProfile } from "../../transform/profiles.js";
2
+ import { toHex6 } from "../../transform/color.js";
3
+ import { collectChildren } from "../csr.js";
4
+ export class EmitSurfaceError extends Error {
5
+ path;
6
+ constructor(message, path) {
7
+ super(`${message} (at ${path})`);
8
+ this.path = path;
9
+ this.name = "EmitSurfaceError";
10
+ }
11
+ }
12
+ export function emitSurface(surface, doc, options = {}) {
13
+ const profile = options.profile ?? shadcnProfile;
14
+ if (surface.dspackSurface !== "0.1") {
15
+ throw new EmitSurfaceError(`unsupported dspackSurface version '${surface.dspackSurface}' (this emitter targets 0.1)`, "$");
16
+ }
17
+ if (surface.system !== doc.name) {
18
+ throw new EmitSurfaceError(`surface.system '${surface.system}' does not match contract name '${doc.name}'`, "$.system");
19
+ }
20
+ const byDspackId = new Map();
21
+ for (const plan of profile.components) {
22
+ if (plan.dspackId)
23
+ byDspackId.set(plan.dspackId, plan);
24
+ }
25
+ const emitter = new SurfaceEmitter(profile, byDspackId);
26
+ const rootId = emitter.emitNode(surface.root, "$.root");
27
+ const surfaceId = options.surfaceId ?? slug(surface.intent);
28
+ const theme = { agentDisplayName: `${doc.name} via dspack` };
29
+ const primaryHex = primaryColor(doc, profile);
30
+ if (primaryHex)
31
+ theme.primaryColor = primaryHex;
32
+ const messages = [
33
+ {
34
+ version: "v0.9",
35
+ createSurface: {
36
+ surfaceId,
37
+ catalogId: `${profile.catalogIdBase}/v0_9_1/catalog.json`,
38
+ theme,
39
+ },
40
+ },
41
+ {
42
+ version: "v0.9",
43
+ updateComponents: { surfaceId, components: emitter.components },
44
+ },
45
+ ];
46
+ void rootId; // root is components[0] by construction (pre-order emission)
47
+ return { messages, warnings: emitter.warnings };
48
+ }
49
+ function primaryColor(doc, profile) {
50
+ const { category, name } = profile.primaryColorToken;
51
+ const raw = doc.tokens?.[category]?.values?.[name]?.value;
52
+ return typeof raw === "string" ? toHex6(raw) : null;
53
+ }
54
+ export function slug(value) {
55
+ const s = value
56
+ .toLowerCase()
57
+ .replace(/[^a-z0-9]+/g, "_")
58
+ .replace(/^_+|_+$/g, "");
59
+ return s || "surface";
60
+ }
61
+ class SurfaceEmitter {
62
+ profile;
63
+ byDspackId;
64
+ components = [];
65
+ warnings = [];
66
+ usedIds = new Set();
67
+ constructor(profile, byDspackId) {
68
+ this.profile = profile;
69
+ this.byDspackId = byDspackId;
70
+ }
71
+ /** Emits the component for `node` (and its subtree) and returns its instance id. */
72
+ emitNode(node, path) {
73
+ const plan = this.byDspackId.get(node.component);
74
+ if (!plan) {
75
+ throw new EmitSurfaceError(`unknown component '${node.component}': not a mapped component of the '${this.profile.catalogTitle}' profile ` +
76
+ `(sub-components are consumed by their compound parent and cannot be emitted standalone)`, path);
77
+ }
78
+ // A2UI renderers begin at the component with id "root" (see the
79
+ // hand-authored surfaces); the surface root always emits under that id.
80
+ const id = path === "$.root" ? this.allocateId("root", path) : this.allocateId(node.id ?? plan.a2ui.toLowerCase(), path);
81
+ // Reserve the slot so parent components precede children in the flat list.
82
+ const index = this.components.length;
83
+ this.components.push({});
84
+ const instance = { id, component: plan.a2ui };
85
+ this.applyPropMap(node, plan, instance, path);
86
+ const sp = plan.surfacePlan ?? {};
87
+ const consumesSubtree = Boolean(sp.subText || sp.subButtonText);
88
+ if (sp.structuralPassthrough) {
89
+ for (const key of sp.structuralPassthrough) {
90
+ const value = node.props?.[key];
91
+ if (value !== undefined)
92
+ instance[key] = value;
93
+ }
94
+ }
95
+ if (sp.subText || sp.subButtonText)
96
+ this.applySubContent(node, sp.subText ?? {}, sp.subButtonText ?? {}, instance, path);
97
+ if (sp.textProp && node.text !== undefined)
98
+ instance[sp.textProp] = node.text;
99
+ if (sp.textChildProp && node.text !== undefined) {
100
+ instance[sp.textChildProp] = this.emitTextPrimitive(node.text, `${id}_label`, path);
101
+ }
102
+ if (sp.actionProp) {
103
+ const eventName = slug(node.id ?? instance.confirmLabel ?? node.text ?? node.component);
104
+ instance[sp.actionProp] = { event: { name: eventName, context: {} } };
105
+ this.warnings.push({
106
+ code: "surface-synthesized-action",
107
+ message: `${path}: A2UI requires a declarative action on ${plan.a2ui}; synthesized event '${eventName}'.`,
108
+ });
109
+ }
110
+ if (!consumesSubtree) {
111
+ const childNodes = collectChildren(node);
112
+ if (childNodes.length > 0) {
113
+ const childIds = childNodes.map((child, i) => this.emitNode(child.node, `${path}${child.suffix}[${i}]`));
114
+ if (sp.childrenProp) {
115
+ instance[sp.childrenProp] = childIds;
116
+ }
117
+ else if (sp.childProp) {
118
+ instance[sp.childProp] = childIds.length === 1 ? childIds[0] : this.wrapInColumn(childIds, id, path);
119
+ }
120
+ else {
121
+ throw new EmitSurfaceError(`component '${node.component}' has children but its surface plan declares no child slot`, path);
122
+ }
123
+ }
124
+ }
125
+ this.components[index] = instance;
126
+ return id;
127
+ }
128
+ /** CSR props -> A2UI props via the profile's existing PropPlan projections. */
129
+ applyPropMap(node, plan, instance, path) {
130
+ for (const [prop, raw] of Object.entries(node.props ?? {})) {
131
+ if (plan.surfacePlan?.structuralPassthrough?.includes(prop))
132
+ continue;
133
+ const pp = plan.propMap?.[prop];
134
+ if (!pp) {
135
+ this.warnings.push({
136
+ code: "surface-prop-dropped",
137
+ message: `${path}: prop '${prop}' on '${node.component}' has no A2UI projection; dropped.`,
138
+ });
139
+ continue;
140
+ }
141
+ const value = pp.valueMap ? (pp.valueMap[String(raw)] ?? pp.default) : raw;
142
+ if (value === undefined) {
143
+ this.warnings.push({
144
+ code: "surface-prop-value-dropped",
145
+ message: `${path}: value '${String(raw)}' of prop '${prop}' has no projection and no default; dropped.`,
146
+ });
147
+ continue;
148
+ }
149
+ instance[pp.a2ui] = value;
150
+ }
151
+ }
152
+ /**
153
+ * Compound flattening: pull text out of named sub-components anywhere in the
154
+ * subtree. The subtree is consumed — the documented composition casualty.
155
+ */
156
+ applySubContent(node, subText, subButtonText, instance, path) {
157
+ const visit = (n, insideSub) => {
158
+ const textProp = subText[n.component];
159
+ if (textProp !== undefined && n.text !== undefined && instance[textProp] === undefined) {
160
+ instance[textProp] = n.text;
161
+ }
162
+ const buttonProp = insideSub ? subButtonText[insideSub] : undefined;
163
+ if (buttonProp !== undefined && n.text !== undefined && instance[buttonProp] === undefined && n !== node) {
164
+ // Only a label-bearing component qualifies (one whose surface plan
165
+ // projects its text as a child label, e.g. the trigger's button) —
166
+ // never incidental text on other descendants.
167
+ const plan = this.byDspackId.get(n.component);
168
+ if (plan?.surfacePlan?.textChildProp)
169
+ instance[buttonProp] = n.text;
170
+ }
171
+ const nextInside = subButtonText[n.component] !== undefined ? n.component : insideSub;
172
+ for (const child of collectChildren(n))
173
+ visit(child.node, nextInside);
174
+ };
175
+ visit(node, null);
176
+ this.warnings.push({
177
+ code: "surface-composition-flattened",
178
+ message: `${path}: compound '${node.component}' subtree flattened onto emitted props (documented casualty; nested props beyond text are not carried).`,
179
+ });
180
+ }
181
+ emitTextPrimitive(text, preferredId, path) {
182
+ const { textComponent, textProp } = this.profile.surfaceSynthesis;
183
+ const id = this.allocateId(preferredId, path);
184
+ this.components.push({ id, component: textComponent, [textProp]: text });
185
+ this.warnings.push({
186
+ code: "surface-synthesized-text",
187
+ message: `${path}: node text projected as a synthesized ${textComponent} child ('${id}') — the surface format has no text primitive.`,
188
+ });
189
+ return id;
190
+ }
191
+ wrapInColumn(childIds, parentId, path) {
192
+ const { wrapComponent, wrapChildrenProp } = this.profile.surfaceSynthesis;
193
+ const id = this.allocateId(`${parentId}_col`, path);
194
+ this.components.push({
195
+ id,
196
+ component: wrapComponent,
197
+ [wrapChildrenProp]: childIds,
198
+ });
199
+ this.warnings.push({
200
+ code: "surface-synthesized-wrap",
201
+ message: `${path}: ${childIds.length} children wrapped in a synthesized ${wrapComponent} ('${id}') — the target slot takes a single child.`,
202
+ });
203
+ return id;
204
+ }
205
+ allocateId(preferred, path) {
206
+ let id = slug(preferred);
207
+ let n = 2;
208
+ while (this.usedIds.has(id))
209
+ id = `${slug(preferred)}_${n++}`;
210
+ if (id !== slug(preferred)) {
211
+ this.warnings.push({
212
+ code: "surface-id-deduplicated",
213
+ message: `${path}: node id '${preferred}' already used; emitted as '${id}'.`,
214
+ });
215
+ }
216
+ this.usedIds.add(id);
217
+ return id;
218
+ }
219
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Shared CSR (dspack surface) traversal semantics used by every emitter target.
3
+ *
4
+ * The child-ordering rule is part of the CSR's meaning, not of any one
5
+ * protocol projection: `children` first, then slot groups in sorted-key
6
+ * order. Both targets (a2ui, json-render) must walk a surface identically or
7
+ * the same governed CSR would emit differently-ordered artifacts per target.
8
+ */
9
+ import type { SurfaceNode } from "../types.js";
10
+ export interface ChildRef {
11
+ node: SurfaceNode;
12
+ suffix: string;
13
+ }
14
+ /** Ordered children: `children` first, then slots in sorted-key order (deterministic). */
15
+ export declare function collectChildren(node: SurfaceNode): ChildRef[];
@@ -0,0 +1,9 @@
1
+ /** Ordered children: `children` first, then slots in sorted-key order (deterministic). */
2
+ export function collectChildren(node) {
3
+ const refs = (node.children ?? []).map((n) => ({ node: n, suffix: ".children" }));
4
+ for (const key of Object.keys(node.slots ?? {}).sort()) {
5
+ for (const n of node.slots[key])
6
+ refs.push({ node: n, suffix: `.slots.${key}` });
7
+ }
8
+ return refs;
9
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * dspack contract → generated json-render modules (TypeScript source text).
3
+ *
4
+ * catalog.ts — defineCatalog(schema, …) with Zod prop schemas compiled
5
+ * from the contract's prop vocabulary (enums verbatim).
6
+ * registry.tsx — defineRegistry(catalog, …) with typed stub renderers, one
7
+ * per catalog component. Stubs exist so the registry's
8
+ * catalog-inferred prop typing is *compiled*, not assumed
9
+ * (gate J1); consumers replace them with real components.
10
+ *
11
+ * The generators emit source text only — this module has no runtime
12
+ * dependency on @json-render/* or zod. The generated modules are compiled
13
+ * and executed in gates/json-render, which pins those packages (the a2ui
14
+ * side of the repo is pinned to zod v3 via @a2ui/web_core, so the zod v4
15
+ * packages json-render requires cannot live in the root dependency tree).
16
+ *
17
+ * All props are `.nullable()`: CSR props are optional, and json-render's
18
+ * catalog idiom prefers nullable over optional for structured-output
19
+ * compatibility.
20
+ */
21
+ import type { DspackDoc } from "../../types.js";
22
+ import { type CatalogComponent, type CatalogModel } from "./model.js";
23
+ import { type JsonRenderProfile } from "./profile.js";
24
+ export interface JsonRenderModules {
25
+ /** Source text of the generated catalog module (catalog.ts). */
26
+ catalogTs: string;
27
+ /** Source text of the generated registry module (registry.tsx). */
28
+ registryTsx: string;
29
+ /** The model both modules were rendered from. */
30
+ model: CatalogModel;
31
+ }
32
+ export declare function generateJsonRenderModules(doc: DspackDoc, profile?: JsonRenderProfile): JsonRenderModules;
33
+ export declare function renderCatalogModule(model: CatalogModel, doc: DspackDoc): string;
34
+ export declare function renderRegistryModule(model: CatalogModel, doc: DspackDoc): string;
35
+ export type { CatalogComponent };
@@ -0,0 +1,91 @@
1
+ import { buildCatalogModel } from "./model.js";
2
+ import { shadcnJsonRenderProfile } from "./profile.js";
3
+ export function generateJsonRenderModules(doc, profile = shadcnJsonRenderProfile) {
4
+ const model = buildCatalogModel(doc, profile);
5
+ return {
6
+ catalogTs: renderCatalogModule(model, doc),
7
+ registryTsx: renderRegistryModule(model, doc),
8
+ model,
9
+ };
10
+ }
11
+ function header(what, doc) {
12
+ return (`/**\n` +
13
+ ` * GENERATED ${what} — do not edit.\n` +
14
+ ` * Generated by dspack-emit (--target json-render) from the dspack contract\n` +
15
+ ` * ${JSON.stringify(doc.name)} (dspack ${JSON.stringify(doc.dspack)}).\n` +
16
+ ` */\n`);
17
+ }
18
+ export function renderCatalogModule(model, doc) {
19
+ const lines = [];
20
+ lines.push(header("json-render catalog", doc).trimEnd());
21
+ lines.push(`import { defineCatalog } from "@json-render/core";`);
22
+ lines.push(`import { schema } from "@json-render/react/schema";`);
23
+ lines.push(`import { z } from "zod";`);
24
+ lines.push(``);
25
+ lines.push(`export const catalog = defineCatalog(schema, {`);
26
+ lines.push(` components: {`);
27
+ for (const component of model.components) {
28
+ for (const excluded of component.excludedProps) {
29
+ lines.push(` // ${component.dspackId}.${excluded.name} excluded: ${excluded.reason}`);
30
+ }
31
+ lines.push(` ${component.name}: {`);
32
+ lines.push(` props: z.object({`);
33
+ for (const prop of component.props) {
34
+ lines.push(` ${propKey(prop.name)}: ${zodExpr(prop)},`);
35
+ }
36
+ lines.push(` }),`);
37
+ // Every component accepts children: the CSR node schema allows children
38
+ // on any node (composition correctness is gate S3's job, pre-emission).
39
+ lines.push(` slots: ["default"],`);
40
+ lines.push(` description: ${JSON.stringify(component.description)},`);
41
+ lines.push(` },`);
42
+ }
43
+ lines.push(` },`);
44
+ lines.push(` actions: {},`);
45
+ lines.push(`});`);
46
+ lines.push(``);
47
+ return lines.join("\n");
48
+ }
49
+ export function renderRegistryModule(model, doc) {
50
+ const lines = [];
51
+ lines.push(header("json-render registry (stub implementations)", doc).trimEnd());
52
+ lines.push(`import { defineRegistry } from "@json-render/react";`);
53
+ lines.push(`import { catalog } from "./catalog.js";`);
54
+ lines.push(``);
55
+ lines.push(`export const { registry } = defineRegistry(catalog, {`);
56
+ lines.push(` components: {`);
57
+ for (const component of model.components) {
58
+ lines.push(` ${component.name}: ({ props, children }) => (`);
59
+ lines.push(` <div data-dspack=${JSON.stringify(component.dspackId)}>`);
60
+ lines.push(` {props.text}`);
61
+ lines.push(` {children}`);
62
+ lines.push(` </div>`);
63
+ lines.push(` ),`);
64
+ }
65
+ lines.push(` },`);
66
+ lines.push(`});`);
67
+ lines.push(``);
68
+ return lines.join("\n");
69
+ }
70
+ function propKey(name) {
71
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);
72
+ }
73
+ function zodExpr(prop) {
74
+ let base;
75
+ switch (prop.kind) {
76
+ case "enum":
77
+ base = `z.enum([${prop.values.map((v) => JSON.stringify(v)).join(", ")}])`;
78
+ break;
79
+ case "string":
80
+ base = `z.string()`;
81
+ break;
82
+ case "boolean":
83
+ base = `z.boolean()`;
84
+ break;
85
+ case "number":
86
+ base = `z.number()`;
87
+ break;
88
+ }
89
+ const described = prop.description ? `${base}.describe(${JSON.stringify(prop.description)})` : base;
90
+ return `${described}.nullable()`;
91
+ }