* Derive how a wire payload selects one variant of a union, so every binding runs * the same dispatch instead of re-deriving it (and silently depending on emit * order). Two shapes: * { by, variants: [{ value, ref }], default? } — a discriminated union: look up * payload[by] among `variant
(name, types)
| 470 | * Order is the CDDL choice order (the spec's priority), made explicit here. |
| 471 | */ |
| 472 | function unionSelector(name, types) { |
| 473 | const variants = types[name].variants |
| 474 | const constKeys = new Set() |
| 475 | for (const leaf of variants.flatMap((v) => unionLeaves(v, types))) |
| 476 | for (const f of types[leaf].fields) |
| 477 | if (discriminatorValue(types[leaf], f.name)?.value !== undefined) constKeys.add(f.name) |
| 478 | |
| 479 | for (const key of constKeys) { |
| 480 | const contributions = variants.map((v) => tagContribution(v, key, types)) |
| 481 | if (contributions.some((c) => c === null)) continue // some member can't be placed on this key |
| 482 | const tagged = contributions.flatMap((c) => c.tagged ?? []) |
| 483 | const defaults = contributions.filter((c) => c.default).map((c) => c.default) |
| 484 | if (defaults.length > 1 || tagged.length === 0) continue // ambiguous catch-all, or nothing to tag |
| 485 | const values = tagged.map((e) => JSON.stringify(e.value)) |
| 486 | if (new Set(values).size !== values.length) continue // values collide — not a clean tag |
| 487 | const selector = { by: key, variants: tagged } |
| 488 | if (defaults.length === 1) selector.default = defaults[0] |
| 489 | return selector |
| 490 | } |
| 491 | |
| 492 | // No shared discriminator: dispatch by required-field presence, in spec order. |
| 493 | // Resolve each variant through aliases/sub-unions to its leaf records (as the |
| 494 | // discriminator path does) and require the fields required in every leaf, so an |
| 495 | // alias-to-record variant is not left with an empty (always-matching) predicate. |
| 496 | const requiresOf = (ref) => { |
| 497 | const leaves = unionLeaves(ref, types).map( |
| 498 | (l) => new Set(types[l].fields.filter((f) => f.required).map((f) => f.name)), |
| 499 | ) |
| 500 | return leaves.length ? [...leaves[0]].filter((k) => leaves.every((s) => s.has(k))) : [] |
| 501 | } |
| 502 | return { ordered: variants.map((ref) => ({ ref, requires: requiresOf(ref) })) } |
| 503 | } |
| 504 | |
| 505 | // A structural selector can dispatch a payload only when every arm has a required |
| 506 | // field to test AND no arm's `requires` is a subset of a later arm's (which would |
no test coverage detected