From 3991cab129b1e11e556de952934f52199ca75fce Mon Sep 17 00:00:00 2001 From: Abhinav Deval Date: Wed, 2 Dec 2026 15:45:45 +0530 Subject: [PATCH 1/2] feat(form): support recursive object, array, and $ref schemas Follows up on #23 by recursively extracting nested object properties, array item shapes, map values (additionalProperties), union variants, and local $ref definitions with cycle protection. Chained extensions (spec.dependencies / env-configuration) are intentionally deferred to a separate follow-up PR to keep this change focused. Signed-off-by: Abhinav Deval --- src/form/catalog.ts | 423 +++++++++++++++++++++++++++++++++--------- src/form/form.test.ts | 313 ++++++++++++++++++++++++++++++- src/form/types.ts | 16 +- 3 files changed, 661 insertions(+), 91 deletions(-) diff --git a/src/form/catalog.ts b/src/form/catalog.ts index 31d62e0..068f5bb 100644 --- a/src/form/catalog.ts +++ b/src/form/catalog.ts @@ -1,5 +1,6 @@ import { ConditionalRule, + ExtensionSchemaItem, ExtractedConditionForm, FormEnumOption, FormFieldDescriptor, @@ -8,6 +9,12 @@ import { RuntimeConditionsExtensionDefinition, } from './types'; +interface ExtractionContext { + ext: RuntimeConditionsExtensionDefinition; + schemaItem: ExtensionSchemaItem; + rootSchema: JsonSchemaProperty; +} + /** * Returns property names as field labels as-is, preserving raw field * names for developer familiarity. @@ -59,21 +66,11 @@ export function parseExtensionDefinition( */ function collectStaticRequiredFields( schema: JsonSchemaProperty, - targetScope: 'interface' | 'condition', ): Set { const reqs = new Set(); - - if (targetScope === 'condition') { - if (Array.isArray(schema.required)) { - schema.required.forEach(r => reqs.add(r)); - } - } else { - const iface = schema.properties?.interface as JsonSchemaProperty | undefined; - if (iface && Array.isArray(iface.required)) { - iface.required.forEach(r => reqs.add(r)); - } + if (Array.isArray(schema.required)) { + schema.required.forEach(r => reqs.add(r)); } - return reqs; } @@ -113,10 +110,298 @@ function extractConditionalRules(schema: JsonSchemaProperty): ConditionalRule[] return rules; } +/** + * Resolves a local JSON Pointer (#/$defs/... or #/definitions/...) within the root schema. + */ +function lookupLocalRef( + ref: string, + rootSchema: JsonSchemaProperty, +): JsonSchemaProperty | undefined { + if (!ref.startsWith('#/')) { + return undefined; + } + + const segments = ref + .slice(2) + .split('/') + .map(seg => seg.replace(/~1/g, '/').replace(/~0/g, '~')); + + let current: unknown = rootSchema; + for (const segment of segments) { + if (!current || typeof current !== 'object') { + return undefined; + } + current = (current as Record)[segment]; + } + + return current && typeof current === 'object' + ? (current as JsonSchemaProperty) + : undefined; +} + +function resolveSchema( + rawSchema: JsonSchemaProperty, + rootSchema: JsonSchemaProperty, + activeRefs: Set, +): { schema: JsonSchemaProperty; refs: Set; isRecursiveRef: boolean; recursiveRef?: string } { + let current = rawSchema; + const refs = new Set(activeRefs); + + while (current.$ref) { + const ref = current.$ref; + if (refs.has(ref)) { + const target = lookupLocalRef(ref, rootSchema); + return { + schema: target ? { ...target, ...current } : current, + refs, + isRecursiveRef: true, + recursiveRef: ref, + }; + } + + const target = lookupLocalRef(ref, rootSchema); + if (!target) { + return { schema: current, refs, isRecursiveRef: false }; + } + + refs.add(ref); + const { $ref: _ignoredRef, ...siblings } = current; + current = { ...target, ...siblings }; + } + + return { schema: current, refs, isRecursiveRef: false }; +} + +function inferFieldType(schema: JsonSchemaProperty): FormFieldType { + if (Array.isArray(schema.enum)) { + return 'enum'; + } + + if (Array.isArray(schema.type)) { + const first = schema.type.find(t => t !== 'null'); + if (first) { + return first as FormFieldType; + } + } else if (schema.type) { + return schema.type as FormFieldType; + } + + if ('const' in schema) { + if (typeof schema.const === 'number') { + return Number.isInteger(schema.const) ? 'integer' : 'number'; + } + if (typeof schema.const === 'boolean') { + return 'boolean'; + } + if (Array.isArray(schema.const)) { + return 'array'; + } + if (schema.const && typeof schema.const === 'object') { + return 'object'; + } + return 'string'; + } + + if (schema.properties && typeof schema.properties === 'object') { + return 'object'; + } + + if (schema.items && !Array.isArray(schema.items)) { + return 'array'; + } + + const unionBranches = schema.oneOf ?? schema.anyOf; + if (Array.isArray(unionBranches)) { + const branchTypes = new Set( + unionBranches + .map(b => { + if (Array.isArray(b.type)) { + return b.type.find(t => t !== 'null'); + } + return b.type ?? (b.properties ? 'object' : undefined); + }) + .filter((t): t is string => Boolean(t)), + ); + if (branchTypes.size === 1) { + return Array.from(branchTypes)[0] as FormFieldType; + } + } + + return 'string'; +} + +function hasValueShape(branch: JsonSchemaProperty): boolean { + return Boolean( + branch.$ref || + branch.type || + branch.properties || + branch.items || + branch.enum || + 'const' in branch, + ); +} + +function buildEnumOptions( + pSchema: JsonSchemaProperty, + ctx: ExtractionContext, + path: string, + name: string, +): FormEnumOption[] | undefined { + if (!Array.isArray(pSchema.enum)) { + return undefined; + } + + const fieldValueMatch = ctx.ext.spec.fieldValues?.find( + fv => + fv.targetKind === ctx.schemaItem.appliesToKind && + fv.targetType === ctx.schemaItem.appliesToInterfaceType && + (fv.field === path || ((path === `interface.${name}` || path === name) && fv.field === name)), + ); + + return pSchema.enum.map(val => { + const sVal = String(val); + return { + value: sVal, + label: sVal.charAt(0).toUpperCase() + sVal.slice(1), + description: fieldValueMatch?.valueDescriptions?.[sVal], + }; + }); +} + +function extractFieldDescriptor( + name: string, + path: string, + location: 'interface' | 'condition', + rawSchema: JsonSchemaProperty, + required: boolean, + ctx: ExtractionContext, + activeRefs: Set, + overrideDescription?: string, + // Canonical data path used for children and fieldValues lookups. Differs from `path` + // only for union variants, whose display path carries a unique `#idx` suffix. + pathBase: string = path, +): FormFieldDescriptor { + const { schema: pSchema, refs, isRecursiveRef, recursiveRef } = resolveSchema( + rawSchema, + ctx.rootSchema, + activeRefs, + ); + + const description = + overrideDescription || + pSchema.description || + rawSchema.description || + (location === 'interface' ? `Specifies ${name}` : `Condition property ${name}`); + + if (isRecursiveRef) { + return { + name, + path, + location, + label: formatFieldLabel(name), + description, + type: inferFieldType(pSchema), + required, + isRecursiveRef: true, + recursiveRef, + }; + } + + const fieldType = inferFieldType(pSchema); + const descriptor: FormFieldDescriptor = { + name, + path, + location, + label: formatFieldLabel(name), + description, + type: fieldType, + required, + minimum: pSchema.minimum, + maximum: pSchema.maximum, + pattern: typeof pSchema.pattern === 'string' ? pSchema.pattern : undefined, + enumOptions: buildEnumOptions(pSchema, ctx, pathBase, name), + }; + + if ('const' in pSchema) { + descriptor.constValue = pSchema.const; + } + + if (fieldType === 'object' && pSchema.properties) { + const childRequired = new Set(pSchema.required ?? []); + const children = Object.entries(pSchema.properties).map( + ([childName, childProp]) => + extractFieldDescriptor( + childName, + `${pathBase}.${childName}`, + location, + (childProp || {}) as JsonSchemaProperty, + childRequired.has(childName), + ctx, + refs, + ), + ); + if (children.length > 0) { + descriptor.children = children; + } + } else if (fieldType === 'array' && pSchema.items && !Array.isArray(pSchema.items)) { + descriptor.itemDescriptor = extractFieldDescriptor( + `${name}[]`, + `${pathBase}[]`, + location, + pSchema.items, + false, + ctx, + refs, + ); + } + + if ( + fieldType === 'object' && + pSchema.additionalProperties && + typeof pSchema.additionalProperties === 'object' + ) { + descriptor.mapValueDescriptor = extractFieldDescriptor( + `${name}{}`, + `${pathBase}{}`, + location, + pSchema.additionalProperties, + false, + ctx, + refs, + ); + } + + const unionBranches = pSchema.oneOf ?? pSchema.anyOf; + if ( + Array.isArray(unionBranches) && + !descriptor.children && + !descriptor.itemDescriptor && + !descriptor.mapValueDescriptor + ) { + const shapedBranches = unionBranches.filter(hasValueShape); + if (shapedBranches.length > 0) { + descriptor.variants = shapedBranches.map((branch, idx) => + extractFieldDescriptor( + `${name}#${idx}`, + `${path}#${idx}`, + location, + branch, + false, + ctx, + refs, + undefined, + pathBase, + ), + ); + } + } + + return descriptor; +} + /** * Extracts form field descriptors from an extension definition. - * Covers interface fields, condition-level fields (e.g. env, configuration), - * enums with descriptions, and dynamic validation metadata. + * Recursively extracts nested objects, arrays, $ref/$defs, and union variants. */ export function extractConditionForms( ext: RuntimeConditionsExtensionDefinition, @@ -136,45 +421,26 @@ export function extractConditionForms( const fields: FormFieldDescriptor[] = []; const schemaObj = schemaItem.schema ?? {}; const conditionalRules = extractConditionalRules(schemaObj); + const ctx: ExtractionContext = { + ext, + schemaItem, + rootSchema: schemaObj, + }; // 1. Extract Interface fields (if interface property exists) - const ifaceSchema = schemaObj.properties?.interface as JsonSchemaProperty | undefined; + const rawIfaceSchema = schemaObj.properties?.interface as JsonSchemaProperty | undefined; + const resolvedIface = rawIfaceSchema + ? resolveSchema(rawIfaceSchema, schemaObj, new Set()) + : undefined; + const ifaceSchema = resolvedIface?.schema; const ifaceProps = ifaceSchema?.properties ?? {}; - const ifaceRequiredSet = collectStaticRequiredFields(schemaObj, 'interface'); + const ifaceRequiredSet = new Set(ifaceSchema?.required ?? []); for (const [propName, propVal] of Object.entries(ifaceProps)) { if (propVal && typeof propVal === 'object' && 'const' in propVal) { continue; } - const pSchema = (propVal || {}) as JsonSchemaProperty; - const isRequired = ifaceRequiredSet.has(propName); - - let fieldType: FormFieldType = 'string'; - let enumOptions: FormEnumOption[] | undefined; - - if (Array.isArray(pSchema.enum)) { - fieldType = 'enum'; - const fieldValueMatch = ext.spec.fieldValues?.find( - fv => - fv.targetKind === schemaItem.appliesToKind && - fv.targetType === schemaItem.appliesToInterfaceType && - (fv.field === `interface.${propName}` || fv.field === propName), - ); - - enumOptions = pSchema.enum.map(val => { - const sVal = String(val); - const desc = fieldValueMatch?.valueDescriptions?.[sVal]; - return { - value: sVal, - label: sVal.charAt(0).toUpperCase() + sVal.slice(1), - description: desc, - }; - }); - } else if (pSchema.type) { - fieldType = pSchema.type as FormFieldType; - } - const fieldDoc = ext.spec.interfaceFields?.find( f => f.targetKind === schemaItem.appliesToKind && @@ -182,43 +448,29 @@ export function extractConditionForms( f.name === propName, ); - const description = - fieldDoc?.description || - pSchema.description || - `Specifies ${propName}`; - - fields.push({ - name: propName, - path: `interface.${propName}`, - location: 'interface', - label: formatFieldLabel(propName), - description, - type: fieldType, - required: isRequired, - minimum: pSchema.minimum, - maximum: pSchema.maximum, - pattern: typeof pSchema.pattern === 'string' ? pSchema.pattern : undefined, - enumOptions, - }); + fields.push( + extractFieldDescriptor( + propName, + `interface.${propName}`, + 'interface', + (propVal || {}) as JsonSchemaProperty, + ifaceRequiredSet.has(propName), + ctx, + resolvedIface?.refs ?? new Set(), + fieldDoc?.description, + ), + ); } // 2. Extract Condition-level fields (e.g. env, configuration) const rootProps = schemaObj.properties ?? {}; - const conditionRequiredSet = collectStaticRequiredFields(schemaObj, 'condition'); + const conditionRequiredSet = collectStaticRequiredFields(schemaObj); for (const [propName, propVal] of Object.entries(rootProps)) { if (['kind', 'interface', 'name', 'optional'].includes(propName)) { continue; } - const pSchema = (propVal || {}) as JsonSchemaProperty; - const isRequired = conditionRequiredSet.has(propName); - - let fieldType: FormFieldType = 'string'; - if (pSchema.type) { - fieldType = pSchema.type as FormFieldType; - } - // Look up the extension's documentation for this condition-level field. A conditionFields // entry documents this property when its name matches AND it targets this schema's kind and // interface type. An entry that omits appliesToKinds / appliesToInterfaceTypes is untargeted @@ -230,23 +482,18 @@ export function extractConditionForms( (!cf.appliesToInterfaceTypes || cf.appliesToInterfaceTypes.includes(schemaItem.appliesToInterfaceType)), ); - const description = - condDoc?.description || - pSchema.description || - `Condition property ${propName}`; - - fields.push({ - name: propName, - path: propName, - location: 'condition', - label: formatFieldLabel(propName), - description, - type: fieldType, - required: isRequired, - minimum: pSchema.minimum, - maximum: pSchema.maximum, - pattern: typeof pSchema.pattern === 'string' ? pSchema.pattern : undefined, - }); + fields.push( + extractFieldDescriptor( + propName, + propName, + 'condition', + (propVal || {}) as JsonSchemaProperty, + conditionRequiredSet.has(propName), + ctx, + new Set(), + condDoc?.description, + ), + ); } result.push({ diff --git a/src/form/form.test.ts b/src/form/form.test.ts index d8d64e4..1d26a1c 100644 --- a/src/form/form.test.ts +++ b/src/form/form.test.ts @@ -2,7 +2,10 @@ import { extractConditionForms, formatFieldLabel, } from './catalog'; -import { RuntimeConditionsExtensionDefinition } from './types'; +import { + JsonSchemaProperty, + RuntimeConditionsExtensionDefinition, +} from './types'; const sampleGpuExtension: RuntimeConditionsExtensionDefinition = { apiVersion: 'runtimeconditions.io/v1alpha1', @@ -267,3 +270,311 @@ describe('Catalog & Form Extraction', () => { expect(form.fields[0].location).toBe('condition'); }); }); +const sampleApiHttpExtension: RuntimeConditionsExtensionDefinition = { + apiVersion: 'runtimeconditions.io/v1alpha1', + kind: 'RuntimeConditionsExtensionDefinition', + metadata: { + id: 'https://runtimeconditions.io/extensions/rc/common-integrations/v1alpha4/runtimeconditions.extension.yaml', + version: 'v1alpha4', + description: 'Common integrations', + }, + spec: { + kinds: [{ name: 'api' }], + interfaceTypes: [{ name: 'http', targetKind: 'api' }], + schemas: [ + { + id: 'api-http-interface', + appliesToKind: 'api', + appliesToInterfaceType: 'http', + schema: { + type: 'object', + required: ['kind', 'interface'], + properties: { + kind: { const: 'api' }, + interface: { + type: 'object', + required: ['type'], + properties: { + type: { const: 'http' }, + spec: { + type: 'object', + required: ['format', 'uri'], + properties: { + format: { + const: 'openapi', + description: 'Format of the API document.', + }, + uri: { + type: 'string', + description: 'Where the API document can be found.', + }, + version: { + type: 'string', + pattern: '^[0-9]+\\.[0-9]+\\.[0-9]+$', + }, + }, + }, + operations: { + type: 'array', + items: { + type: 'object', + required: ['method', 'path'], + properties: { + method: { enum: ['GET', 'POST', 'DELETE'] }, + path: { type: 'string' }, + requestBodySchema: { + $ref: '#/$defs/simpleSchema', + description: 'Shape of the request body.', + }, + }, + }, + }, + }, + }, + }, + $defs: { + simpleSchema: { + oneOf: [ + { + type: 'string', + enum: ['string', 'number', 'integer', 'boolean', 'null'], + }, + { + type: 'object', + additionalProperties: { $ref: '#/$defs/simpleSchema' }, + }, + { + type: 'array', + items: { $ref: '#/$defs/simpleSchema' }, + }, + ], + }, + }, + }, + }, + ], + }, +}; + +const sampleS3BucketExtension: RuntimeConditionsExtensionDefinition = { + apiVersion: 'runtimeconditions.io/v1alpha1', + kind: 'RuntimeConditionsExtensionDefinition', + metadata: { + id: 'https://runtimeconditions.io/extensions/aws/s3/0.2.0/runtimeconditions.extension.yaml', + version: '0.2.0', + }, + spec: { + kinds: [{ name: 'aws.s3' }], + interfaceTypes: [{ name: 'bucket', targetKind: 'aws.s3' }], + schemas: [ + { + id: 'aws-s3-bucket-interface', + appliesToKind: 'aws.s3', + appliesToInterfaceType: 'bucket', + schema: { + type: 'object', + required: ['kind', 'interface'], + properties: { + kind: { const: 'aws.s3' }, + interface: { + type: 'object', + required: ['type', 'operations'], + properties: { + type: { const: 'bucket' }, + operations: { + type: 'array', + items: { + oneOf: [ + { + type: 'object', + required: ['name'], + properties: { name: { const: 'AbortMultipartUpload' } }, + }, + { + type: 'object', + required: ['name', 'role'], + properties: { + name: { const: 'CopyObject' }, + role: { enum: ['destination', 'source'] }, + }, + }, + ], + }, + }, + }, + }, + }, + }, + }, + ], + }, +}; + +describe('Recursive Object, Array, and $ref Extraction', () => { + it('recursively extracts nested object properties and const fields', () => { + const [form] = extractConditionForms(sampleApiHttpExtension); + const specField = form.fields.find(f => f.name === 'spec'); + + expect(specField?.type).toBe('object'); + expect(specField?.children).toHaveLength(3); + + const formatField = specField?.children?.find(c => c.name === 'format'); + expect(formatField?.constValue).toBe('openapi'); + expect(formatField?.path).toBe('interface.spec.format'); + expect(formatField?.required).toBe(true); + + const uriField = specField?.children?.find(c => c.name === 'uri'); + expect(uriField?.type).toBe('string'); + expect(uriField?.required).toBe(true); + + const versionField = specField?.children?.find(c => c.name === 'version'); + expect(versionField?.required).toBe(false); + expect(versionField?.pattern).toBe('^[0-9]+\\.[0-9]+\\.[0-9]+$'); + }); + + it('recursively extracts array item descriptors and guards self-recursive $ref cycles', () => { + const [form] = extractConditionForms(sampleApiHttpExtension); + const opsField = form.fields.find(f => f.name === 'operations'); + + expect(opsField?.type).toBe('array'); + expect(opsField?.itemDescriptor?.type).toBe('object'); + + const opChildren = opsField?.itemDescriptor?.children ?? []; + const methodField = opChildren.find(c => c.name === 'method'); + expect(methodField?.type).toBe('enum'); + expect(methodField?.required).toBe(true); + expect(methodField?.enumOptions?.map(o => o.value)).toEqual(['GET', 'POST', 'DELETE']); + + const bodySchemaField = opChildren.find(c => c.name === 'requestBodySchema'); + expect(bodySchemaField?.description).toBe('Shape of the request body.'); + expect(bodySchemaField?.variants).toHaveLength(3); + + const arrayVariant = bodySchemaField?.variants?.[2]; + expect(arrayVariant?.type).toBe('array'); + expect(arrayVariant?.itemDescriptor?.isRecursiveRef).toBe(true); + }); + + it('extracts oneOf variants inside array items', () => { + const [form] = extractConditionForms(sampleS3BucketExtension); + const opsField = form.fields.find(f => f.name === 'operations'); + + expect(opsField?.type).toBe('array'); + const itemVariants = opsField?.itemDescriptor?.variants ?? []; + expect(itemVariants).toHaveLength(2); + + const copyVariant = itemVariants[1]; + expect(copyVariant.type).toBe('object'); + expect(copyVariant.children?.find(c => c.name === 'name')?.constValue).toBe('CopyObject'); + expect(copyVariant.children?.find(c => c.name === 'role')?.enumOptions?.map(o => o.value)).toEqual([ + 'destination', + 'source', + ]); + }); +}); + +const mkExt = ( + schema: JsonSchemaProperty, + extra: Partial = {}, +): RuntimeConditionsExtensionDefinition => ({ + apiVersion: 'runtimeconditions.io/v1alpha1', + kind: 'RuntimeConditionsExtensionDefinition', + metadata: { id: 'test' }, + spec: { + kinds: [{ name: 'k' }], + interfaceTypes: [{ name: 't', targetKind: 'k' }], + schemas: [{ id: 's', appliesToKind: 'k', appliesToInterfaceType: 't', schema }], + ...extra, + }, +}); + +describe('Map values, nullable types, $ref interface, variant paths', () => { + it('extracts additionalProperties as mapValueDescriptor (aws/sqs tags shape)', () => { + const [form] = extractConditionForms( + mkExt({ + type: 'object', + properties: { + kind: { const: 'k' }, + interface: { + type: 'object', + properties: { + tags: { + type: 'object', + additionalProperties: { type: 'string', description: 'A tag value' }, + }, + }, + }, + }, + }), + ); + const tags = form.fields.find(f => f.name === 'tags'); + expect(tags?.type).toBe('object'); + expect(tags?.mapValueDescriptor?.type).toBe('string'); + expect(tags?.mapValueDescriptor?.path).toBe('interface.tags{}'); + }); + + it('picks the first non-null type for nullable array types', () => { + const [form] = extractConditionForms( + mkExt({ + type: 'object', + properties: { + kind: { const: 'k' }, + interface: { type: 'object', properties: { a: { type: ['null', 'integer'] } } }, + }, + }), + ); + expect(form.fields[0].type).toBe('integer'); + }); + + it('keeps required fields when interface is a $ref', () => { + const [form] = extractConditionForms( + mkExt({ + type: 'object', + properties: { kind: { const: 'k' }, interface: { $ref: '#/$defs/I' } }, + $defs: { I: { type: 'object', required: ['a'], properties: { a: { type: 'string' } } } }, + }), + ); + expect(form.fields.find(f => f.name === 'a')?.required).toBe(true); + }); + + it('gives variants unique paths while children keep the canonical data path', () => { + const [form] = extractConditionForms(sampleS3BucketExtension); + const variants = form.fields.find(f => f.name === 'operations')?.itemDescriptor?.variants ?? []; + expect(variants.map(v => v.path)).toEqual(['interface.operations[]#0', 'interface.operations[]#1']); + expect(variants[1].children?.find(c => c.name === 'role')?.path).toBe('interface.operations[].role'); + }); + + it('matches fieldValues descriptions for variant children by canonical path', () => { + const ext = mkExt(sampleS3BucketExtension.spec.schemas[0].schema, { + kinds: [{ name: 'aws.s3' }], + interfaceTypes: [{ name: 'bucket', targetKind: 'aws.s3' }], + fieldValues: [ + { + field: 'interface.operations[].role', + targetKind: 'aws.s3', + targetType: 'bucket', + values: ['destination', 'source'], + valueDescriptions: { source: 'Where the object is read from.' }, + }, + ], + }); + ext.spec.schemas[0].appliesToKind = 'aws.s3'; + ext.spec.schemas[0].appliesToInterfaceType = 'bucket'; + + const [form] = extractConditionForms(ext); + const variants = form.fields.find(f => f.name === 'operations')?.itemDescriptor?.variants ?? []; + const role = variants[1].children?.find(c => c.name === 'role'); + expect(role?.enumOptions?.find(o => o.value === 'source')?.description).toBe( + 'Where the object is read from.', + ); + }); + + it('records which $ref a recursive stub points back to', () => { + const [form] = extractConditionForms(sampleApiHttpExtension); + const body = form.fields + .find(f => f.name === 'operations') + ?.itemDescriptor?.children?.find(c => c.name === 'requestBodySchema'); + expect(body?.variants?.[2].itemDescriptor?.recursiveRef).toBe('#/$defs/simpleSchema'); + expect(body?.variants?.[1].mapValueDescriptor?.isRecursiveRef).toBe(true); + expect(body?.variants?.[1].mapValueDescriptor?.recursiveRef).toBe('#/$defs/simpleSchema'); + }); +}); diff --git a/src/form/types.ts b/src/form/types.ts index 50da374..2db299e 100644 --- a/src/form/types.ts +++ b/src/form/types.ts @@ -43,7 +43,7 @@ export interface ExtensionFieldValue { } export interface JsonSchemaProperty { - type?: string; + type?: string | string[]; enum?: (string | number | boolean)[]; const?: unknown; description?: string; @@ -53,6 +53,7 @@ export interface JsonSchemaProperty { default?: unknown; required?: string[]; properties?: Record; + additionalProperties?: boolean | JsonSchemaProperty; items?: JsonSchemaProperty | JsonSchemaProperty[]; oneOf?: JsonSchemaProperty[]; anyOf?: JsonSchemaProperty[]; @@ -62,6 +63,8 @@ export interface JsonSchemaProperty { else?: JsonSchemaProperty; not?: JsonSchemaProperty; $ref?: string; + $defs?: Record; + definitions?: Record; [key: string]: unknown; } @@ -97,16 +100,25 @@ export interface FormEnumOption { export interface FormFieldDescriptor { name: string; - path: string; // e.g. 'interface.count' or 'env' or 'configuration' + path: string; // e.g. 'interface.count', 'interface.spec.uri', or 'configuration' location: 'interface' | 'condition'; label: string; description?: string; type: FormFieldType; required: boolean; + constValue?: unknown; minimum?: number; maximum?: number; pattern?: string; enumOptions?: FormEnumOption[]; + children?: FormFieldDescriptor[]; + itemDescriptor?: FormFieldDescriptor; + variants?: FormFieldDescriptor[]; + /** Descriptor for the values of a map-like object (additionalProperties). */ + mapValueDescriptor?: FormFieldDescriptor; + isRecursiveRef?: boolean; + /** The $ref this node points back to, when isRecursiveRef is true. */ + recursiveRef?: string; } export interface ConditionalRule { From 2e6843419903be1b3bf7adf7d63be6701f684a42 Mon Sep 17 00:00:00 2001 From: Abhinav Deval Date: Wed, 2 Dec 2026 16:22:55 +0530 Subject: [PATCH 2/2] docs(form): explain branch logic and rename schema vars Signed-off-by: Abhinav Deval --- src/form/catalog.ts | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/src/form/catalog.ts b/src/form/catalog.ts index 068f5bb..4e1f129 100644 --- a/src/form/catalog.ts +++ b/src/form/catalog.ts @@ -139,6 +139,12 @@ function lookupLocalRef( : undefined; } +/** + * Follows chained local `$ref` pointers while guarding against ancestor cycles. + * Clones `activeRefs` per traversal branch so sibling properties reusing the same + * definition do not falsely trip recursion detection, and merges sibling keywords + * over the resolved target (e.g. a field-level `description` alongside `$ref`). + */ function resolveSchema( rawSchema: JsonSchemaProperty, rootSchema: JsonSchemaProperty, @@ -177,6 +183,7 @@ function inferFieldType(schema: JsonSchemaProperty): FormFieldType { return 'enum'; } + // Nullable type arrays (e.g. `['null', 'integer']`) resolve to the first concrete type. if (Array.isArray(schema.type)) { const first = schema.type.find(t => t !== 'null'); if (first) { @@ -210,6 +217,8 @@ function inferFieldType(schema: JsonSchemaProperty): FormFieldType { return 'array'; } + // If every branch of a oneOf/anyOf shares the same underlying type (e.g. every branch is 'string'), + // surface that common type on the parent descriptor instead of falling through. const unionBranches = schema.oneOf ?? schema.anyOf; if (Array.isArray(unionBranches)) { const branchTypes = new Set( @@ -230,6 +239,8 @@ function inferFieldType(schema: JsonSchemaProperty): FormFieldType { return 'string'; } +// Distinguish selectable input shapes from pure validation constraints (e.g. `{ required: [...] }`) +// so constraint-only oneOf/anyOf entries are not rendered as form variants. function hasValueShape(branch: JsonSchemaProperty): boolean { return Boolean( branch.$ref || @@ -242,15 +253,18 @@ function hasValueShape(branch: JsonSchemaProperty): boolean { } function buildEnumOptions( - pSchema: JsonSchemaProperty, + schemaProp: JsonSchemaProperty, ctx: ExtractionContext, path: string, name: string, ): FormEnumOption[] | undefined { - if (!Array.isArray(pSchema.enum)) { + if (!Array.isArray(schemaProp.enum)) { return undefined; } + // Match on the canonical dotted path first; keep the bare-name check for top-level paths + // (`interface.` or ``) for backward compatibility with the original flat lookup, + // while preventing nested leaves from inheriting a top-level entry with the same property name. const fieldValueMatch = ctx.ext.spec.fieldValues?.find( fv => fv.targetKind === ctx.schemaItem.appliesToKind && @@ -258,12 +272,12 @@ function buildEnumOptions( (fv.field === path || ((path === `interface.${name}` || path === name) && fv.field === name)), ); - return pSchema.enum.map(val => { - const sVal = String(val); + return schemaProp.enum.map(val => { + const strVal = String(val); return { - value: sVal, - label: sVal.charAt(0).toUpperCase() + sVal.slice(1), - description: fieldValueMatch?.valueDescriptions?.[sVal], + value: strVal, + label: strVal.charAt(0).toUpperCase() + strVal.slice(1), + description: fieldValueMatch?.valueDescriptions?.[strVal], }; }); } @@ -371,6 +385,9 @@ function extractFieldDescriptor( ); } + // Only extract oneOf/anyOf as separate form variants when the node does not already + // define concrete object properties, array items, or map values; otherwise the union + // usually encodes validation constraints (e.g., required-field combos) rather than distinct inputs. const unionBranches = pSchema.oneOf ?? pSchema.anyOf; if ( Array.isArray(unionBranches) && @@ -427,7 +444,8 @@ export function extractConditionForms( rootSchema: schemaObj, }; - // 1. Extract Interface fields (if interface property exists) + // 1. Extract Interface fields (resolve `interface` itself in case it uses `$ref`, + // which is required to uncover its nested `properties` and `required` list). const rawIfaceSchema = schemaObj.properties?.interface as JsonSchemaProperty | undefined; const resolvedIface = rawIfaceSchema ? resolveSchema(rawIfaceSchema, schemaObj, new Set())