The Open Standard for Generative UI
lang-core: report plain objects in component slots as type-mismatch (#1287)
Aditya-thesys7c8f5e9ae2e9
diff --git a/.changeset/component-slot-plain-data.md b/.changeset/component-slot-plain-data.mdnew file mode 100644index 000000000..709cdeb97--- /dev/null+++ b/.changeset/component-slot-plain-data.md@@ -0,0 +1,5 @@+---+"@openuidev/lang-core": patch+---++Report data (an object, array, string, number or boolean) in a slot that only takes components as a `type-mismatch` and prune it, instead of passing it through to render as a blank component or stray text. Slots whose schema also allows data are unchanged.diff --git a/packages/lang-core/src/parser/__tests__/materialize.validation.test.ts b/packages/lang-core/src/parser/__tests__/materialize.validation.test.tsindex 5309bb0dc..60e6b5ee1 100644--- a/packages/lang-core/src/parser/__tests__/materialize.validation.test.ts+++ b/packages/lang-core/src/parser/__tests__/materialize.validation.test.ts@@ -100,7 +100,7 @@ const schema: LibraryJSONSchema = {properties: { theme: { type: "string", default: "dark" } },required: ["theme"],},- // arg0 → `children`: a component slot (anyOf of $refs) — membership unchecked+ // arg0 → `children`: a component slot (anyOf of $refs)SlotBox: {properties: {children: { type: "array", items: { anyOf: [{ $ref: "#/$defs/CardBox" }] } },@@ -288,7 +288,7 @@ describe("components in data slots", () => {]);});- it("component slots ($ref/anyOf) stay unchecked; a misplaced component's own args still validate", () => {+ it("component slots ($ref/anyOf) accept any component; a misplaced component's own args still validate", () => {const slot = parser.parse('root = SlotBox([CardBox("hi"), EnumBox("active")])');expect(slot.meta.errors).toEqual([]);expect((slot.root?.props.children as unknown[]).length).toBe(2);@@ -298,6 +298,33 @@ describe("components in data slots", () => {expect(errors.find((e) => e.component === "CardBox")).toMatchObject({ path: "/text" });expect(errors.find((e) => e.component === "ObjBox")).toMatchObject({ path: "/info/author" });});+ it("data in a component slot is a type-mismatch and is pruned, also through a reference", () => {+ const inline = parser.parse(+ 'root = SlotBox([CardBox("hi"), { text: "a" }, "b", 3, [CardBox("x")]])',+ );+ expect(inline.root?.props.children).toHaveLength(1);+ expect(inline.meta.errors.map((e) => e.message)).toEqual([+ 'field "/children/1" expects CardBox but got plain object',+ 'field "/children/2" expects CardBox but got string',+ 'field "/children/3" expects CardBox but got number',+ 'field "/children/4" expects CardBox but got array',+ ]);+ const viaRef = parser.parse('root = SlotBox(items)\nitems = [{ text: "a" }]');+ expect(viaRef.root?.props.children).toEqual([]);+ expect(viaRef.meta.errors[0]).toMatchObject({ code: "type-mismatch", path: "/children/0" });+ });+ it("a $ref to a non-component def (e.g. a recursive object) is not a component slot", () => {+ const p = createParser({+ properties: { Tree: {} },+ $defs: {+ Tree: { properties: { node: { $ref: "#/$defs/__schema0" } }, required: ["node"] },+ __schema0: { type: "object", properties: { label: { type: "string" } } },+ },+ });+ const r = p.parse('root = Tree({ label: "a" })');+ expect(r.meta.errors).toEqual([]);+ expect(r.root?.props.node).toEqual({ label: "a" });+ });});describe("conservative skips", () => {diff --git a/packages/lang-core/src/parser/parser.ts b/packages/lang-core/src/parser/parser.tsindex c0482c6e7..9e932a656 100644--- a/packages/lang-core/src/parser/parser.ts+++ b/packages/lang-core/src/parser/parser.ts@@ -638,8 +638,11 @@ export interface Parser {export function compileSchema(schema: LibraryJSONSchema): ParamMap {const map: ParamMap = new Map();const defs = schema.$defs ?? {};+ const components = schema.properties && new Set(Object.keys(schema.properties));for (const [name, def] of Object.entries(defs)) {+ // Skip non-component defs, e.g. zod's hoisted recursive schemas (__schema0).+ if (components && !components.has(name)) continue;const properties = def.properties ?? {};const required = def.required ?? [];const params = Object.keys(properties).map((key) => ({diff --git a/packages/lang-core/src/parser/types.ts b/packages/lang-core/src/parser/types.tsindex 2a378972f..26e689071 100644--- a/packages/lang-core/src/parser/types.ts+++ b/packages/lang-core/src/parser/types.ts@@ -13,6 +13,8 @@ export type JSONSchemaDef = {*/export interface LibraryJSONSchema {$defs?: Record<string, JSONSchemaDef>;+ /** Component names as keys. Other `$defs` are data shapes. */+ properties?: Record<string, unknown>;}/** Scalar JSON Schema types we can reliably check a positional literal against. */diff --git a/packages/lang-core/src/parser/validation.ts b/packages/lang-core/src/parser/validation.tsindex 77458972b..e9a086d7a 100644--- a/packages/lang-core/src/parser/validation.ts+++ b/packages/lang-core/src/parser/validation.ts@@ -21,6 +21,11 @@ function jsType(value: unknown): string {return Array.isArray(value) ? "array" : typeof value;}+/** `{ $ref: "#/$defs/Name" }` → `"Name"`. */+function refName(s: Record<string, unknown>): string | undefined {+ return typeof s["$ref"] === "string" ? s["$ref"].split("/").pop() : undefined;+}+/** Composite shapes can't be reliably matched to a single plain value. */function isCompositeSchema(s: Record<string, unknown>): boolean {return "$ref" in s || "anyOf" in s || "oneOf" in s || "allOf" in s;@@ -66,9 +71,8 @@ export function getTypeFromSchema(property: unknown): string | undefined {}const p = property as Record<string, unknown>;// $refs and compound types aren't validator-checkable but still make useful hints.- if (typeof p.$ref === "string") {- return p.$ref.split("/").pop();- }+ const ref = refName(p);+ if (ref) return ref;// Scalar/enum leaves: share the validator's schema-leaf interpretation so// signatures and type-mismatch messages never disagree.const leaf = getScalarTypeInfo(p);@@ -220,6 +224,17 @@ function validateElementPosition(return false;}+/** The `$ref` names a slot allows: one for `$ref`, several for anyOf/oneOf. */+function slotRefNames(s: Record<string, unknown>): (string | undefined)[] {+ return ((s["anyOf"] ?? s["oneOf"] ?? [s]) as Record<string, unknown>[]).map(refName);+}++/** True when every option of the slot is a `$ref` to a component. */+function isOnlyComponentSlot(s: Record<string, unknown>, ctx: MaterializeCtx): boolean {+ const names = slotRefNames(s);+ return names.length > 0 && names.every((n) => n !== undefined && ctx.cat?.has(n));+}+/*** Validate an object-shaped slot: container type, required keys (absent/null* ones fill silently from their schema default), then each declared property@@ -361,7 +376,20 @@ export function validateSchemaValue(if (isASTNode(value)) return false;// Child components: only their position is checked here.if (isElementNode(value)) return validateElementPosition(value, s, component, path, ctx);- if (isCompositeSchema(s)) return false;+ if (isCompositeSchema(s)) {+ // Data (an object, array, string, number or boolean) in a component-only slot is invalid.+ if (!isOnlyComponentSlot(s, ctx)) return false;+ pushValidationIssue(ctx, component, path, {+ code: "type-mismatch",+ expected: slotRefNames(s).join(" | "),+ actual: Array.isArray(value)+ ? "array"+ : typeof value === "object"+ ? "plain object"+ : typeof value,+ });+ return true;+ }const type = s["type"];if (type === "object") return validateObjectValue(value, s, component, path, ctx);