@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
@@ -0,0 +1,608 @@
1
+ /**
2
+ * Profile v2 surface syntax → the internal transformation model.
3
+ *
4
+ * v2 is the first profile language that authors the internal model DIRECTLY:
5
+ * where v1 accumulated ten directives named after collisions (`subText`,
6
+ * `subButtonText`, `subTable`, …), a v2 plan writes Identity / Route / Collect
7
+ * facts in a closed string syntax. This module parses that syntax, derives the
8
+ * things v1 made authors imply (write order, subtree consumption), and REFUSES
9
+ * everything else — a v2 plan that parses is a plan the engine can emit.
10
+ *
11
+ * The grammar is deliberately closed. Selectors and destinations are fixed
12
+ * string forms with two parameterized holes (a prop name, a sub-component id
13
+ * set); there is no expression language, no JSON paths, no predicates, no
14
+ * computed destination names, and no cross-instance routing. Those absences
15
+ * are the design: a plan you cannot write is a plan nobody has to audit.
16
+ *
17
+ * Capability note: the grammar admits exactly what the engine can emit. T1
18
+ * (transparent identity + constrained control donation) landed as the
19
+ * `transparent` / `donate` spellings below; spellings whose engine support
20
+ * has not landed (`joinOn` pairing — T3, multi-slot children routing — T4,
21
+ * variant identity — T5) are still refused, never reinterpreted.
22
+ */
23
+ import type { ComponentPlan } from "./profiles.js";
24
+ import {
25
+ WriteOrder,
26
+ emptySurfaceModel,
27
+ isCollect,
28
+ type Collect,
29
+ type CollectJoin,
30
+ type Destination,
31
+ type Donation,
32
+ type Route,
33
+ type Selector,
34
+ type SurfaceModel,
35
+ } from "./model.js";
36
+
37
+ /** One pathed finding; parse-v2 refusals reuse the loader's issue shape. */
38
+ export interface ParseIssue {
39
+ path: string;
40
+ message: string;
41
+ }
42
+
43
+ export class ProfileParseError extends Error {
44
+ constructor(readonly issues: ParseIssue[]) {
45
+ super(
46
+ `profile v2 surface syntax is invalid (${issues.length} issue${issues.length === 1 ? "" : "s"}): ` +
47
+ issues
48
+ .slice(0, 3)
49
+ .map((i) => `${i.path || "$"}: ${i.message}`)
50
+ .join("; ") +
51
+ (issues.length > 3 ? "; …" : ""),
52
+ );
53
+ this.name = "ProfileParseError";
54
+ }
55
+ }
56
+
57
+ // ---------------------------------------------------------------------------
58
+ // The authored v2 shapes (what the JSON schema admits)
59
+ // ---------------------------------------------------------------------------
60
+
61
+ export interface SurfaceV2Route {
62
+ /** Ordered fallback chain; the first selector that yields a value wins. */
63
+ from: string[];
64
+ to: string;
65
+ overwrite?: boolean;
66
+ }
67
+
68
+ export interface SurfaceV2Collect {
69
+ /** Sections (table-mode) or the repeated items themselves (item-mode). */
70
+ of: string[];
71
+ /** Array-valued destination (`prop:<name>`). */
72
+ into: string;
73
+ /** table-mode: `flat` concatenates all rows into one list; `records` keeps one record per row. */
74
+ shape?: "flat" | "records";
75
+ /** table-mode: record field carrying each row's cells; required when shape is `records`. */
76
+ field?: string;
77
+ /** table-mode: repetitions inside a section. */
78
+ row?: string[];
79
+ /** table-mode: cells inside a repetition, flattened to their subtree text. */
80
+ cells?: string[];
81
+ /**
82
+ * T2 item-mode: each matching descendant becomes one record; every field
83
+ * resolves against THAT item's own node. Selectors: `self.text`,
84
+ * `self.props.<prop>`, `self.id`.
85
+ */
86
+ item?: Record<string, string>;
87
+ /**
88
+ * T3: a DECLARED key join onto a sibling sub-family. `on.left` extracts the
89
+ * key from each item, `on.right` from each counterpart; `fields` source
90
+ * record fields from the JOINED side (item-local selectors, or the literal
91
+ * `"children"` for the slot-valued field: the counterpart's children emit
92
+ * as instances and the record carries the reference). `optional: true`
93
+ * relaxes exactly-one to 0..1. The profile names the relation; nothing is
94
+ * ever inferred from position or adjacency.
95
+ */
96
+ join?: {
97
+ with: string[];
98
+ on: { left: string; right: string };
99
+ fields: Record<string, string>;
100
+ optional?: boolean;
101
+ };
102
+ }
103
+
104
+ export interface SurfaceV2Donate {
105
+ /** `self.text` or `sub(<id>|…).text` — where the donated value comes from. */
106
+ from: string;
107
+ /** `prop:<name>` on the boundary's single eligible control. */
108
+ to: string;
109
+ }
110
+
111
+ export type SurfaceV2Sub =
112
+ | "transparent"
113
+ | { transparent: true | { donate: SurfaceV2Donate[] } }
114
+ | { asText: string }
115
+ | { drop: string };
116
+
117
+ export interface SurfaceV2 {
118
+ /**
119
+ * T1 transparent identity: this component emits no instance; children rise.
120
+ * `true`, or an object carrying constrained control donations scoped to
121
+ * each dissolved instance's subtree.
122
+ */
123
+ transparent?: true | { donate: SurfaceV2Donate[] };
124
+ routes?: SurfaceV2Route[];
125
+ collects?: SurfaceV2Collect[];
126
+ /** Identity or disposition of named sub-components met in this node's subtree. */
127
+ subs?: Record<string, SurfaceV2Sub>;
128
+ }
129
+
130
+ // ---------------------------------------------------------------------------
131
+ // Selector / destination string grammar
132
+ // ---------------------------------------------------------------------------
133
+
134
+ const ID = "[a-z][a-z0-9-]*";
135
+ const PROP = "[A-Za-z][A-Za-z0-9]*";
136
+ const SELECTOR = new RegExp(
137
+ `^(self\\.text|self\\.id|self\\.props\\.(${PROP})|sub\\((${ID}(?:\\|${ID})*)\\)\\.(text|label|firstText|subtreeText|children)|children|synthesized\\.action)$`,
138
+ );
139
+ const DESTINATION = new RegExp(`^(prop|textChild|slot|slots|action):(${PROP})$`);
140
+
141
+ export function parseSelector(raw: string): Selector | null {
142
+ const m = SELECTOR.exec(raw);
143
+ if (!m) return null;
144
+ if (m[1] === "self.text") return { kind: "self-text" };
145
+ if (m[1] === "self.id") return { kind: "self-id" };
146
+ if (m[1] === "children") return { kind: "children" };
147
+ if (m[1] === "synthesized.action") return { kind: "synthesized-action" };
148
+ if (m[2]) return { kind: "self-prop", prop: m[2] };
149
+ const subs = m[3].split("|");
150
+ switch (m[4]) {
151
+ case "text":
152
+ return { kind: "sub-text", subs };
153
+ case "label":
154
+ return { kind: "sub-label", subs };
155
+ case "firstText":
156
+ return { kind: "sub-text-lift", subs };
157
+ case "children":
158
+ return { kind: "sub-children", subs };
159
+ default:
160
+ return { kind: "subtree-text", subs };
161
+ }
162
+ }
163
+
164
+ export function parseDestination(raw: string): Destination | null {
165
+ const m = DESTINATION.exec(raw);
166
+ if (!m) return null;
167
+ const name = m[2];
168
+ switch (m[1]) {
169
+ case "prop":
170
+ return { kind: "prop", name };
171
+ case "textChild":
172
+ return { kind: "text-child", name };
173
+ case "slot":
174
+ return { kind: "slot", name };
175
+ case "slots":
176
+ return { kind: "slots", name };
177
+ default:
178
+ return { kind: "action", name };
179
+ }
180
+ }
181
+
182
+ // ---------------------------------------------------------------------------
183
+ // Derived write order — v2 authors never write WriteOrder; it is a function
184
+ // of what the route reads and writes, reproducing v1's phase semantics.
185
+ // ---------------------------------------------------------------------------
186
+
187
+ function orderOfSelector(s: Selector, to: Destination): WriteOrder {
188
+ switch (s.kind) {
189
+ case "self-prop":
190
+ return WriteOrder.Verbatim;
191
+ case "sub-text":
192
+ case "sub-label":
193
+ case "sub-text-lift":
194
+ return WriteOrder.Consume;
195
+ case "subtree-text":
196
+ return WriteOrder.CollectLead;
197
+ case "self-text":
198
+ return to.kind === "text-child" ? WriteOrder.SelfTextChild : WriteOrder.SelfText;
199
+ case "self-id":
200
+ return WriteOrder.SelfText; // unreachable in routes: `compatible` refuses it
201
+ case "synthesized-action":
202
+ return WriteOrder.Action;
203
+ case "sub-children":
204
+ return WriteOrder.Slot;
205
+ case "children":
206
+ return WriteOrder.Children;
207
+ }
208
+ }
209
+
210
+ /** Selector-kind → destination-kind compatibility (closed, refused otherwise). */
211
+ function compatible(s: Selector, to: Destination): boolean {
212
+ switch (s.kind) {
213
+ case "children":
214
+ return to.kind === "slot" || to.kind === "slots";
215
+ case "sub-children":
216
+ // T4: instance emission from a named region lands in exactly one slot.
217
+ return to.kind === "slot";
218
+ case "synthesized-action":
219
+ return to.kind === "action";
220
+ case "self-text":
221
+ return to.kind === "prop" || to.kind === "text-child";
222
+ case "self-id":
223
+ return false; // item-field-only: a route may not read self.id
224
+ default:
225
+ return to.kind === "prop";
226
+ }
227
+ }
228
+
229
+ // ---------------------------------------------------------------------------
230
+ // The parser
231
+ // ---------------------------------------------------------------------------
232
+
233
+ /**
234
+ * Parse and statically validate one plan's v2 surface block.
235
+ *
236
+ * `path` roots the pathed findings (e.g. `/components/3/surface`). Validation
237
+ * here needs only the plan itself: destinations against its own declared
238
+ * structural slots and propMap targets, conflict detection under the write
239
+ * discipline, and grammar closure. Contract-facing checks (sub ids exist,
240
+ * self-props are declared, derived coverage is complete) run at transform
241
+ * time, where the contract is in hand — see validate-v2.ts.
242
+ */
243
+ /** Parses one donate entry; donation selectors and destinations are narrower than routes'. */
244
+ function parseDonation(d: SurfaceV2Donate, at: string, issues: ParseIssue[], origin: string): Donation | null {
245
+ const from = parseSelector(d.from);
246
+ if (!from || (from.kind !== "self-text" && from.kind !== "sub-text")) {
247
+ issues.push({ path: `${at}/from`, message: `'${d.from}' is not a donation source (donations harvest text: self.text or sub(<id>|…).text)` });
248
+ return null;
249
+ }
250
+ const to = parseDestination(d.to);
251
+ if (!to || to.kind !== "prop") {
252
+ issues.push({ path: `${at}/to`, message: `'${d.to}' is not a donation destination (donations write prop:<name> on the receiving control)` });
253
+ return null;
254
+ }
255
+ return { from, to, origin };
256
+ }
257
+
258
+ export function parseSurfaceV2(surface: SurfaceV2, plan: ComponentPlan, path: string): SurfaceModel {
259
+ const issues: ParseIssue[] = [];
260
+ const model = emptySurfaceModel();
261
+
262
+ // T1: transparent identity. A transparent plan emits nothing, so nothing it
263
+ // could declare for an instance is meaningful — routes, collects, structural
264
+ // slots, propMap, required all refuse. Only sub dispositions (for its own
265
+ // dissolved subtree) and donations survive.
266
+ if (surface.transparent !== undefined) {
267
+ model.transparent = true;
268
+ if (typeof surface.transparent === "object") {
269
+ surface.transparent.donate.forEach((d, i) => {
270
+ const parsed = parseDonation(d, `${path}/transparent/donate/${i}`, issues, `v2:transparent/donate/${i}`);
271
+ if (parsed) model.transparentDonate.push(parsed);
272
+ });
273
+ }
274
+ if ((surface.routes ?? []).length > 0 || (surface.collects ?? []).length > 0) {
275
+ issues.push({ path, message: "a transparent plan emits no instance; routes and collects have nowhere to land (donations are the only writes it may carry)" });
276
+ }
277
+ for (const [field, label] of [
278
+ [plan.structural ?? {}, "structural"],
279
+ [plan.propMap ?? {}, "propMap"],
280
+ ] as const) {
281
+ if (Object.keys(field).length > 0) {
282
+ issues.push({ path, message: `a transparent plan declares no catalog surface; remove its ${label} block` });
283
+ }
284
+ }
285
+ if ((plan.required ?? []).length > 0) {
286
+ issues.push({ path, message: "a transparent plan declares no catalog surface; remove its required list" });
287
+ }
288
+ }
289
+
290
+ // The plan's own declared destination names: structural slots plus the
291
+ // a2ui-side names its propMap writes. Gate A3 catches an OMITTED property
292
+ // but silently passes an INVENTED one, so this is where invention dies.
293
+ const declared = new Set<string>([
294
+ ...Object.keys(plan.structural ?? {}),
295
+ ...Object.values(plan.propMap ?? {}).map((p) => p.a2ui),
296
+ ]);
297
+
298
+ // Write-conflict detection under the declared discipline. Two writers on one
299
+ // destination are LEGAL when they resolve in distinct write orders — the
300
+ // outcome is then fully determined by order plus the overwrite flag (v1's
301
+ // Table does exactly this: a passthrough prop wins over the collect harvest
302
+ // because Verbatim runs first and later writers are first-wins). What is
303
+ // refused is a SAME-order double-claim, where nothing but declaration order
304
+ // would decide the winner — that is ambiguity, not layering.
305
+ const claimed = new Map<string, Array<{ order: WriteOrder; by: string }>>();
306
+ const claim = (name: string, order: WriteOrder, by: string, at: string): void => {
307
+ const prior = claimed.get(name) ?? [];
308
+ // The children destination is exclusive in BOTH directions (see the
309
+ // children-route check below for the rationale).
310
+ const children = prior.find((c) => c.order === WriteOrder.Children);
311
+ if (children && order !== WriteOrder.Children) {
312
+ issues.push({
313
+ path: at,
314
+ message: `destination '${name}' is claimed by the children route (${children.by}); instance references do not participate in first-wins layering`,
315
+ });
316
+ }
317
+ const clash = prior.find((c) => c.order === order);
318
+ if (clash) {
319
+ issues.push({
320
+ path: at,
321
+ message: `destination '${name}' is already claimed in the same write phase by ${clash.by}; two same-phase writers would be ordered only by declaration position (fallbacks belong inside a single route's 'from' chain)`,
322
+ });
323
+ }
324
+ prior.push({ order, by });
325
+ claimed.set(name, prior);
326
+ };
327
+
328
+ let childrenRoutes = 0;
329
+
330
+ for (const [i, r] of (surface.routes ?? []).entries()) {
331
+ const at = `${path}/routes/${i}`;
332
+ const to = parseDestination(r.to);
333
+ if (!to) {
334
+ issues.push({ path: `${at}/to`, message: `'${r.to}' is not a destination (expected prop:|textChild:|slot:|slots:|action: followed by a name)` });
335
+ continue;
336
+ }
337
+ if (!declared.has(to.name)) {
338
+ issues.push({
339
+ path: `${at}/to`,
340
+ message: `destination '${to.name}' is not declared by this plan (declare it in structural or map a prop onto it; inventing properties is refused because gate A3 cannot catch them)`,
341
+ });
342
+ }
343
+
344
+ const from: Selector[] = [];
345
+ let order: WriteOrder | undefined;
346
+ for (const [j, rawSel] of r.from.entries()) {
347
+ const sel = parseSelector(rawSel);
348
+ if (!sel) {
349
+ issues.push({ path: `${at}/from/${j}`, message: `'${rawSel}' is not a selector (closed forms: self.text, self.props.<prop>, sub(<id>|…).<text|label|firstText|subtreeText>, children, synthesized.action)` });
350
+ continue;
351
+ }
352
+ if (!compatible(sel, to)) {
353
+ issues.push({ path: `${at}/from/${j}`, message: `selector '${rawSel}' cannot feed destination kind '${to.kind}'` });
354
+ continue;
355
+ }
356
+ const selOrder = orderOfSelector(sel, to);
357
+ if (order === undefined) order = selOrder;
358
+ else if (order !== selOrder) {
359
+ issues.push({
360
+ path: `${at}/from/${j}`,
361
+ message: `fallback chain mixes write phases ('${rawSel}' resolves in a different phase than the first selector); a route resolves in exactly one phase`,
362
+ });
363
+ continue;
364
+ }
365
+ from.push(sel);
366
+ }
367
+ if (from.length === 0) {
368
+ issues.push({ path: `${at}/from`, message: "route has no valid selectors" });
369
+ continue;
370
+ }
371
+
372
+ // firstText is a FALLBACK selector: the engine serves it only after a
373
+ // primary label/text selector yielded nothing. As a primary it would
374
+ // parse, derive Consume, and then never resolve — consuming the subtree
375
+ // while writing nothing. Refuse the dead spelling instead of shipping it.
376
+ if (from[0].kind === "sub-text-lift") {
377
+ issues.push({
378
+ path: `${at}/from/0`,
379
+ message:
380
+ "sub(…).firstText is a fallback selector and cannot lead a route; give the route a primary (sub(…).label or sub(…).text) and put firstText after it",
381
+ });
382
+ continue;
383
+ }
384
+
385
+ if (from[0].kind === "children") {
386
+ childrenRoutes++;
387
+ if (from.length > 1) {
388
+ issues.push({ path: `${at}/from`, message: "a children route takes no fallbacks" });
389
+ }
390
+ if (childrenRoutes > 1) {
391
+ issues.push({ path: at, message: "only one children route is supported (multiple named slots arrive with capability class T4)" });
392
+ }
393
+ // A children route produces INSTANCES, not a value: it cannot join
394
+ // first-wins layering, so its destination is exclusively its own. Two
395
+ // writers here would either orphan a synthesized instance in the hashed
396
+ // artifact or silently discard the children — refuse the pair.
397
+ const shared = claimed.get(to.name);
398
+ if (shared && shared.length > 0) {
399
+ issues.push({
400
+ path: `${at}/to`,
401
+ message: `destination '${to.name}' is already claimed by ${shared[0].by}; a children route's destination cannot be layered with value routes (instance references do not participate in first-wins)`,
402
+ });
403
+ }
404
+ }
405
+
406
+ claim(to.name, order!, `routes/${i}`, `${at}/to`);
407
+ const route: Route = { order: order!, from, to, origin: `v2:routes/${i}` };
408
+ if (r.overwrite) route.overwrite = true;
409
+ model.routes.push(route);
410
+ }
411
+
412
+ for (const [i, c] of (surface.collects ?? []).entries()) {
413
+ const at = `${path}/collects/${i}`;
414
+ const into = parseDestination(c.into);
415
+ if (!into || into.kind !== "prop") {
416
+ issues.push({ path: `${at}/into`, message: `'${c.into}' is not an array-valued destination (collects write prop:<name>)` });
417
+ continue;
418
+ }
419
+ if (!declared.has(into.name)) {
420
+ issues.push({ path: `${at}/into`, message: `destination '${into.name}' is not declared by this plan` });
421
+ }
422
+
423
+ // T2 item-mode and table-mode are distinct shapes; mixing them is a
424
+ // contradiction, not a preference.
425
+ const itemMode = c.item !== undefined;
426
+ const tableKeys = [c.shape, c.field, c.row, c.cells].some((v) => v !== undefined);
427
+ if (itemMode && tableKeys) {
428
+ issues.push({ path: at, message: "a collect is either item-mode (item) or table-mode (shape/row/cells/field), never both" });
429
+ continue;
430
+ }
431
+ if (itemMode) {
432
+ const fields: Record<string, Selector> = {};
433
+ let ok = true;
434
+ for (const [fieldName, raw] of Object.entries(c.item!)) {
435
+ const sel = parseSelector(raw);
436
+ const itemLocal = sel && (sel.kind === "self-text" || sel.kind === "self-prop" || sel.kind === "self-id");
437
+ if (!itemLocal) {
438
+ issues.push({
439
+ path: `${at}/item/${fieldName}`,
440
+ message: `'${raw}' is not an item field source (item fields resolve on the item's own node: self.text, self.props.<prop>, self.id — sibling reads and joins are T3)`,
441
+ });
442
+ ok = false;
443
+ continue;
444
+ }
445
+ fields[fieldName] = sel;
446
+ }
447
+ if (!ok || Object.keys(fields).length === 0) {
448
+ if (Object.keys(c.item!).length === 0) issues.push({ path: `${at}/item`, message: "an item-mode collect names at least one field" });
449
+ continue;
450
+ }
451
+ // T3 join, only on item-mode collects.
452
+ let join: CollectJoin | undefined;
453
+ if (c.join) {
454
+ const jAt = `${at}/join`;
455
+ const left = parseSelector(c.join.on.left);
456
+ const right = parseSelector(c.join.on.right);
457
+ const itemLocal = (sel: Selector | null): sel is Selector =>
458
+ sel !== null && (sel.kind === "self-text" || sel.kind === "self-prop" || sel.kind === "self-id");
459
+ let jOk = true;
460
+ if (!itemLocal(left)) {
461
+ issues.push({ path: `${jAt}/on/left`, message: `'${c.join.on.left}' is not a join key source (item-local: self.id, self.props.<prop>, self.text)` });
462
+ jOk = false;
463
+ }
464
+ if (!itemLocal(right)) {
465
+ issues.push({ path: `${jAt}/on/right`, message: `'${c.join.on.right}' is not a join key source (item-local: self.id, self.props.<prop>, self.text)` });
466
+ jOk = false;
467
+ }
468
+ const jFields: CollectJoin["fields"] = {};
469
+ for (const [fieldName, raw] of Object.entries(c.join.fields)) {
470
+ if (raw === "children") {
471
+ jFields[fieldName] = { kind: "joined-children" };
472
+ continue;
473
+ }
474
+ const sel = parseSelector(raw);
475
+ if (!itemLocal(sel)) {
476
+ issues.push({ path: `${jAt}/fields/${fieldName}`, message: `'${raw}' is not a joined-side field source (item-local selectors, or "children" for the slot-valued field)` });
477
+ jOk = false;
478
+ continue;
479
+ }
480
+ jFields[fieldName] = sel;
481
+ }
482
+ for (const fieldName of Object.keys(jFields)) {
483
+ if (fieldName in fields) {
484
+ issues.push({ path: `${jAt}/fields/${fieldName}`, message: `field '${fieldName}' is already sourced from the left item; one record field, one source` });
485
+ jOk = false;
486
+ }
487
+ }
488
+ if (Object.keys(jFields).length === 0) {
489
+ issues.push({ path: `${jAt}/fields`, message: "a join names at least one joined-side field — a join that contributes nothing is not a relation" });
490
+ jOk = false;
491
+ }
492
+ if (jOk) {
493
+ join = { with: c.join.with, leftKey: left as Selector, rightKey: right as Selector, fields: jFields, optional: c.join.optional === true, origin: `v2:collects/${i}/join` };
494
+ } else {
495
+ continue;
496
+ }
497
+ }
498
+ claim(into.name, WriteOrder.Collect, `collects/${i}`, `${at}/into`);
499
+ model.collects.push({
500
+ order: WriteOrder.Collect,
501
+ flatten: false,
502
+ of: c.of,
503
+ as: into,
504
+ fields,
505
+ ...(join ? { join } : {}),
506
+ origin: `v2:collects/${i}`,
507
+ });
508
+ continue;
509
+ }
510
+ if (c.shape === undefined || c.row === undefined || c.cells === undefined) {
511
+ issues.push({ path: at, message: "a table-mode collect declares shape, row, and cells (or use item-mode with `item`)" });
512
+ continue;
513
+ }
514
+ if (c.shape === "records" && !c.field) {
515
+ issues.push({ path: `${at}/field`, message: "a records collect names the field its rows' cells land in" });
516
+ continue;
517
+ }
518
+ claim(into.name, WriteOrder.Collect, `collects/${i}`, `${at}/into`);
519
+
520
+ const origin = `v2:collects/${i}`;
521
+ const inner: Collect = {
522
+ order: WriteOrder.Collect,
523
+ flatten: false,
524
+ of: c.row,
525
+ as: { kind: "inline" },
526
+ scalar: {
527
+ order: WriteOrder.Collect,
528
+ from: [{ kind: "subtree-text", subs: c.cells }],
529
+ to: { kind: "prop", name: c.field ?? "cells" },
530
+ origin,
531
+ },
532
+ origin,
533
+ };
534
+ model.collects.push({
535
+ order: WriteOrder.Collect,
536
+ flatten: c.shape === "flat",
537
+ of: c.of,
538
+ as: into,
539
+ item: { [c.field ?? "cells"]: inner },
540
+ origin,
541
+ });
542
+ }
543
+
544
+ for (const [sub, disposition] of Object.entries(surface.subs ?? {})) {
545
+ const at = `${path}/subs/${sub}`;
546
+ if (disposition === "transparent") {
547
+ model.subIdentity[sub] = { kind: "transparent" };
548
+ } else if (typeof disposition === "object" && "transparent" in disposition) {
549
+ const donate: Donation[] = [];
550
+ if (typeof disposition.transparent === "object") {
551
+ disposition.transparent.donate.forEach((d, i) => {
552
+ const parsed = parseDonation(d, `${at}/transparent/donate/${i}`, issues, `v2:subs/${sub}/donate/${i}`);
553
+ if (parsed) donate.push(parsed);
554
+ });
555
+ }
556
+ model.subIdentity[sub] = donate.length > 0 ? { kind: "transparent", donate } : { kind: "transparent" };
557
+ } else if ("asText" in disposition) {
558
+ model.subIdentity[sub] = { kind: "as-text", variant: disposition.asText };
559
+ } else {
560
+ model.drops[sub] = disposition.drop;
561
+ }
562
+ // A sub with an identity/drop must not also be a route or collect source —
563
+ // two dispositions for one sub is a contradiction, not a preference.
564
+ const alsoRouted = model.routes.some((r) => r.from.some((s) => "subs" in s && (s.subs as string[]).includes(sub)));
565
+ const inCollect = (col: Collect): boolean =>
566
+ col.of.includes(sub) ||
567
+ Boolean(col.scalar?.from.some((s) => "subs" in s && (s.subs as string[]).includes(sub))) ||
568
+ Object.values(col.item ?? {}).some((f) => (isCollect(f) ? inCollect(f) : f.from.some((s) => "subs" in s && (s.subs as string[]).includes(sub))));
569
+ const alsoCollected = model.collects.some(inCollect);
570
+ if (alsoRouted || alsoCollected) {
571
+ issues.push({ path: at, message: `sub-component '${sub}' has a disposition here and is also consumed by a ${alsoRouted ? "route" : "collect"}; one sub, one disposition` });
572
+ }
573
+ }
574
+
575
+ // Derived, never authored: a plan that reads its subtree into props does not
576
+ // also emit that subtree as children.
577
+ model.consumesSubtree =
578
+ model.collects.length > 0 ||
579
+ model.routes.some((r) => r.order === WriteOrder.Consume || r.order === WriteOrder.CollectLead || r.order === WriteOrder.Slot);
580
+
581
+ // T4: one region, one slot — a sub named by several sub-children routes
582
+ // (or the same route naming several subs) would make one child list land
583
+ // twice; and a mixed from-list has no fallback semantics for regions.
584
+ const slotRoutes = model.routes.filter((r) => r.from.some((sel) => sel.kind === "sub-children"));
585
+ for (const r of slotRoutes) {
586
+ if (r.from.length !== 1 || r.from[0].kind !== "sub-children") {
587
+ issues.push({ path, message: `a sub(x).children route takes exactly one selector — regions have no fallback chain` });
588
+ } else if (r.from[0].subs.length !== 1) {
589
+ issues.push({ path, message: `sub(${r.from[0].subs.join("|")}).children names ${r.from[0].subs.length} subs; a slot route names exactly one region` });
590
+ }
591
+ }
592
+ const slotSources = slotRoutes.flatMap((r) => (r.from[0].kind === "sub-children" ? r.from[0].subs : []));
593
+ for (const dup of slotSources.filter((id, i) => slotSources.indexOf(id) !== i)) {
594
+ issues.push({ path, message: `sub-component '${dup}' is the source of more than one slot route; one region, one slot` });
595
+ }
596
+
597
+ const childrenRoute = model.routes.find((r) => r.from[0].kind === "children");
598
+ if (model.consumesSubtree && childrenRoute) {
599
+ issues.push({
600
+ path,
601
+ message:
602
+ "this plan both consumes its subtree into props and routes children as instances; the two are contradictory (the consumed subtree has no children left to emit)",
603
+ });
604
+ }
605
+
606
+ if (issues.length > 0) throw new ProfileParseError(issues);
607
+ return model;
608
+ }