From 40e632536fd7d73347e904e75ed0871df477aeff Mon Sep 17 00:00:00 2001 From: Carsten Kirschner Date: Fri, 20 Nov 2026 17:51:09 +0100 Subject: [PATCH] Add Openapi 3.1 if then else constructs to the constraint rendering. --- src/components/api-request.js | 4 +- src/components/conditions.js | 12 +++ src/components/request-form-table.js | 4 +- src/components/schema-table.js | 5 +- src/components/schema-tree.js | 7 +- src/utils/schema-utils.js | 143 ++++++++++++++++++++++++++- tests/schema-utils.test.js | 19 ++++ 7 files changed, 188 insertions(+), 6 deletions(-) create mode 100644 src/components/conditions.js diff --git a/src/components/api-request.js b/src/components/api-request.js index f7d99d69..42228368 100644 --- a/src/components/api-request.js +++ b/src/components/api-request.js @@ -1,4 +1,5 @@ import { LitElement, html } from 'lit'; +import { renderConditions } from './conditions.js'; import { unsafeHTML } from 'lit/directives/unsafe-html.js'; import { keyed } from 'lit/directives/keyed.js'; @@ -245,10 +246,11 @@ export default class ApiRequest extends LitElement { ` : '' } - ${generatedParamSchema.constraints.length || displayAllowedValuesHints || generatedParamSchema.pattern + ${generatedParamSchema.constraints.length || generatedParamSchema.conditions?.length || displayAllowedValuesHints || generatedParamSchema.pattern ? html`
${generatedParamSchema.constraints.length ? html`Constraints: ${generatedParamSchema.constraints.join(', ')}
` : ''} + ${renderConditions(generatedParamSchema.conditions)} ${generatedParamSchema.pattern ? html`
Pattern:
diff --git a/src/components/conditions.js b/src/components/conditions.js new file mode 100644 index 00000000..a944676e --- /dev/null +++ b/src/components/conditions.js @@ -0,0 +1,12 @@ +import { html } from 'lit'; + +/* Renders conditional (if/then/else) constraints as indented blocks below the regular constraints */ +export function renderConditions(conditions) { + if (!Array.isArray(conditions) || !conditions.length) { + return ''; + } + return html`${conditions.map((condition) => html` +
+ ${condition.when}: ${condition.rules.map((rule, i) => html`${i > 0 ? ', ' : ''}${rule.label}${rule.value !== '' ? ': ' : ''}${rule.value}`)} +
`)}`; +} diff --git a/src/components/request-form-table.js b/src/components/request-form-table.js index 0148e129..3502c0b7 100644 --- a/src/components/request-form-table.js +++ b/src/components/request-form-table.js @@ -1,3 +1,4 @@ +import { renderConditions } from './conditions.js'; /* eslint-disable indent */ import { html } from 'lit'; import { toMarkdown } from '../utils/common-utils.js'; @@ -76,7 +77,7 @@ function generateFormRows(data, options, dataType = 'object', key = '', descript } function generatePrimitiveRow(rowData, parentRecursionOptions) { - const { type, format, readOrWriteOnly, constraints, defaultValue, example, allowedValues, pattern, schemaDescription, schemaTitle, deprecated } = rowData; + const { type, format, readOrWriteOnly, constraints, conditions, defaultValue, example, allowedValues, pattern, schemaDescription, schemaTitle, deprecated } = rowData; const { key, keyLabel, keyDescr, description, dataType, isRequired, options } = parentRecursionOptions; if (readOrWriteOnly === '🆁') { return undefined; @@ -115,6 +116,7 @@ function generatePrimitiveRow(rowData, parentRecursionOptions) {
${pattern ? html`Pattern: ${pattern}
` : ''} ${constraints.length ? html`Constraints: ${constraints.join(', ')}
` : ''} + ${renderConditions(conditions)} ${allowedValues?.filter(v => v !== '').map((v, i) => html` ${i > 0 ? '|' : html`Allowed: `} ${html` diff --git a/src/components/schema-table.js b/src/components/schema-table.js index 4ea72a23..4d3f688b 100644 --- a/src/components/schema-table.js +++ b/src/components/schema-table.js @@ -1,4 +1,5 @@ import { LitElement, html, css } from 'lit'; +import { renderConditions } from './conditions.js'; import { toMarkdown } from '../utils/common-utils.js'; import { unsafeHTML } from 'lit/directives/unsafe-html.js'; import FontStyles from '../styles/font-styles.js'; @@ -271,6 +272,7 @@ export default class SchemaTable extends LitElement { ${unsafeHTML(toMarkdown(displayLine))} ${data['::metadata']?.constraints?.length ? html`
Constraints: ${data['::metadata'].constraints.join(', ')}

` : ''} + ${renderConditions(data['::metadata']?.conditions)}
` : html` @@ -292,7 +294,7 @@ export default class SchemaTable extends LitElement { } // For Primitive Data types - const { type, cssType, format, readOrWriteOnly, constraints, defaultValue, example, allowedValues, pattern, schemaDescription, schemaTitle, deprecated } = JSON.parse(data); + const { type, cssType, format, readOrWriteOnly, constraints, conditions, defaultValue, example, allowedValues, pattern, schemaDescription, schemaTitle, deprecated } = JSON.parse(data); if (readOrWriteOnly === '🆁' && this.schemaHideReadOnly === 'true') { return { result: undefined, keyLabelMaxCharacterLength: newIndentLevel }; } @@ -319,6 +321,7 @@ export default class SchemaTable extends LitElement { ${unsafeHTML(toMarkdown(`${`${(schemaTitle || title) ? `**${schemaTitle || title}${schemaDescription || description ? ':' : ''}**` : ''} ${schemaDescription || description}` || ''}`))} ${constraints.length ? html`
Constraints: ${constraints.join(', ')}

` : ''} + ${renderConditions(conditions)} ${defaultValue !== '' ? html`
Default: ${defaultValue}

` : ''} ${allowedValues ? html`
Allowed: ${allowedValues.filter(v => v !== null && v !== undefined).join(' ┃ ')}

` : ''} ${pattern ? html`
Pattern: ${pattern}

` : ''} diff --git a/src/components/schema-tree.js b/src/components/schema-tree.js index 97cca90c..43ca6238 100644 --- a/src/components/schema-tree.js +++ b/src/components/schema-tree.js @@ -1,4 +1,5 @@ import { LitElement, html, css } from 'lit'; +import { renderConditions } from './conditions.js'; import { toMarkdown } from '../utils/common-utils.js'; import { unsafeHTML } from 'lit/directives/unsafe-html.js'; import { getI18nText } from '../languages/index.js'; @@ -260,7 +261,8 @@ export default class SchemaTree extends LitElement { ${unsafeHTML(toMarkdown(displayLine))} ${this.schemaDescriptionExpanded ? html` - ${data['::metadata']?.constraints?.length ? html`
Constraints: ${data['::metadata'].constraints.join(', ')}

` : ''}` : ''} + ${data['::metadata']?.constraints?.length ? html`
Constraints: ${data['::metadata'].constraints.join(', ')}

` : ''} + ${renderConditions(data['::metadata']?.conditions)}` : ''}
@@ -282,7 +284,7 @@ export default class SchemaTree extends LitElement { } // For Primitive Data types - const { type, cssType, format, readOrWriteOnly, constraints, defaultValue, example, allowedValues, pattern, schemaDescription, schemaTitle, deprecated } = JSON.parse(data); + const { type, cssType, format, readOrWriteOnly, constraints, conditions, defaultValue, example, allowedValues, pattern, schemaDescription, schemaTitle, deprecated } = JSON.parse(data); if (readOrWriteOnly === '🆁' && this.schemaHideReadOnly === 'true') { return undefined; } @@ -312,6 +314,7 @@ export default class SchemaTree extends LitElement { ${this.schemaDescriptionExpanded ? html` ${constraints.length ? html`
Constraints: ${constraints.join(', ')}

` : ''} + ${renderConditions(conditions)} ${defaultValue !== '' ? html`
Default: ${defaultValue}

` : ''} ${allowedValues ? html`
Allowed: ${allowedValues.filter(v => v !== null && v !== undefined).join(' ┃ ')}

` : ''} ${pattern ? html`
Pattern: ${pattern}

` : ''} diff --git a/src/utils/schema-utils.js b/src/utils/schema-utils.js index b98e264a..0d67f303 100644 --- a/src/utils/schema-utils.js +++ b/src/utils/schema-utils.js @@ -87,12 +87,15 @@ export function getTypeInfo(parameter, options = { includeNulls: false, enableEx } } + info.conditions = Array.isArray(schema['x-conditions']) ? schema['x-conditions'] : []; + info.html = JSON.stringify({ type: info.type, format: info.format, cssType: info.cssType, readOrWriteOnly: info.readOrWriteOnly, constraints: info.constraints, + conditions: info.conditions, defaultValue: info.default, example: info.example, allowedValues: info.allowedValues, @@ -316,14 +319,152 @@ export function isPatternProperty(label) { * @param {number} level - recursion level * @param {string} suffix - used for suffixing property names to avoid duplicate props during object composition */ +function formatConditionValue(value) { + return typeof value === 'string' ? value : JSON.stringify(value); +} + +/* Describes the `if` part of a conditional (if/then/else) schema in a human readable way */ +function describeCondition(ifSchema) { + if (!ifSchema || typeof ifSchema !== 'object') { + return JSON.stringify(ifSchema); + } + const parts = []; + const properties = ifSchema.properties || {}; + Object.keys(properties).forEach((key) => { + const prop = properties[key] || {}; + if (typeof prop.const !== 'undefined') { + parts.push(`${key} = ${formatConditionValue(prop.const)}`); + } else if (Array.isArray(prop.enum)) { + parts.push(`${key} is one of ${prop.enum.map(formatConditionValue).join(' | ')}`); + } else if (prop.pattern) { + parts.push(`${key} matches ${prop.pattern}`); + } else { + parts.push(`${key} matches ${JSON.stringify(prop)}`); + } + }); + (ifSchema.required || []).filter((key) => !properties[key]).forEach((key) => parts.push(`${key} is set`)); + const rest = omitKeys(ifSchema, ['properties', 'required', 'type']); + if (Object.keys(rest).length) { + parts.push(JSON.stringify(rest)); + } + return parts.join(' and ') || JSON.stringify(ifSchema); +} + +/* Describes the constraints a `then`/`else` branch adds to a single property */ +function describeConditionalPropertyConstraints(propSchema) { + if (!propSchema || typeof propSchema !== 'object') { + return [{ label: 'Schema', value: JSON.stringify(propSchema) }]; + } + const rules = []; + const add = (label, value) => rules.push({ label, value: String(value) }); + if (typeof propSchema.const !== 'undefined') { add('Must be', formatConditionValue(propSchema.const)); } + if (Array.isArray(propSchema.enum)) { add('Allowed', propSchema.enum.map(formatConditionValue).join(' ┃ ')); } + if (propSchema.pattern) { add('Pattern', propSchema.pattern); } + if (propSchema.format) { add('Format', propSchema.format); } + if (propSchema.type) { add('Type', [].concat(propSchema.type).join(' ┃ ')); } + if (propSchema.minLength !== undefined) { add('Min length', propSchema.minLength); } + if (propSchema.maxLength !== undefined) { add('Max length', propSchema.maxLength); } + if (propSchema.minimum !== undefined) { add('Minimum', propSchema.minimum); } + if (propSchema.maximum !== undefined) { add('Maximum', propSchema.maximum); } + if (propSchema.exclusiveMinimum !== undefined) { add('Exclusive minimum', propSchema.exclusiveMinimum); } + if (propSchema.exclusiveMaximum !== undefined) { add('Exclusive maximum', propSchema.exclusiveMaximum); } + if (propSchema.minItems !== undefined) { add('Min items', propSchema.minItems); } + if (propSchema.maxItems !== undefined) { add('Max items', propSchema.maxItems); } + if (propSchema.not) { add('Not', JSON.stringify(propSchema.not)); } + return rules.length ? rules : [{ label: 'Schema', value: JSON.stringify(propSchema) }]; +} + +function omitKeys(obj, keys) { + return Object.keys(obj).filter((key) => !keys.includes(key)).reduce((acc, key) => Object.assign(acc, { [key]: obj[key] }), {}); +} + +function isPureConditional(subSchema) { + return subSchema && typeof subSchema === 'object' && Object.prototype.hasOwnProperty.call(subSchema, 'if') + && Object.keys(subSchema).every((key) => ['if', 'then', 'else', 'description', 'title', '$comment'].includes(key)); +} + +/* Moves if/then/else rules of an object schema (directly or as allOf entries) onto the affected properties as human readable constraints */ +function applyConditionals(rawSchema) { + if (!rawSchema || typeof rawSchema !== 'object') { + return rawSchema; + } + const conditionals = []; + if (Object.prototype.hasOwnProperty.call(rawSchema, 'if')) { + conditionals.push(rawSchema); + } + const allOfConditionals = Array.isArray(rawSchema.allOf) ? rawSchema.allOf.filter(isPureConditional) : []; + conditionals.push(...allOfConditionals); + if (!conditionals.length) { + return rawSchema; + } + + const schema = omitKeys(rawSchema, ['if', 'then', 'else']); + if (allOfConditionals.length) { + const remainingAllOf = rawSchema.allOf.filter((s) => !isPureConditional(s)); + if (remainingAllOf.length) { + schema.allOf = remainingAllOf; + } else { + delete schema.allOf; + } + } + const properties = Object.assign({}, schema.properties); + const objectConditions = []; + // A condition is { when, rules: [{ label, value }] }, rules with the same `when` are grouped + const addCondition = (target, when, rules) => { + const existing = target.find((c) => c.when === when); + if (existing) { + existing.rules.push(...rules); + } else { + target.push({ when, rules: [...rules] }); + } + }; + const addPropertyCondition = (key, when, rules) => { + if (!properties[key]) { + addCondition(objectConditions, when, rules.map((r) => ({ label: `${key} ${r.label.toLowerCase()}`, value: r.value }))); + return; + } + properties[key] = Object.assign({}, properties[key]); + properties[key]['x-conditions'] = (properties[key]['x-conditions'] || []).map((c) => ({ when: c.when, rules: [...c.rules] })); + addCondition(properties[key]['x-conditions'], when, rules); + }; + const applyBranch = (branch, conditionText) => { + if (!branch || typeof branch !== 'object') { + return; + } + const branchProperties = branch.properties || {}; + Object.keys(branchProperties).forEach((key) => { + addPropertyCondition(key, `If ${conditionText}`, describeConditionalPropertyConstraints(branchProperties[key])); + }); + (branch.required || []).forEach((key) => addPropertyCondition(key, `If ${conditionText}`, [{ label: 'Required', value: '' }])); + const rest = omitKeys(branch, ['properties', 'required']); + if (Object.keys(rest).length) { + addCondition(objectConditions, `If ${conditionText}`, [{ label: 'Schema', value: JSON.stringify(rest) }]); + } + }; + conditionals.forEach((conditional) => { + const conditionText = describeCondition(conditional.if); + applyBranch(conditional.then, conditionText); + applyBranch(conditional.else, `not (${conditionText})`); + }); + + if (schema.properties) { + schema.properties = properties; + } + if (objectConditions.length) { + schema['x-conditions'] = [].concat(schema['x-conditions'] || [], objectConditions); + } + return schema; +} + export function schemaInObjectNotation(rawSchema, options, level = 0, suffix = '') { - const { allOf, oneOf, anyOf, items: arrayItemsSchema, properties: schemaProperties, patternProperties: schemaPatternProperties, ...schema } = (rawSchema || {}); + const { allOf, oneOf, anyOf, items: arrayItemsSchema, properties: schemaProperties, patternProperties: schemaPatternProperties, ...schema } = (applyConditionals(rawSchema) || {}); const propertyType = schema.type; const metadata = { constraints: [] }; if (schema.uniqueItems) { metadata.constraints.push('Requires unique items'); } if (typeof schema.minItems === 'number' || typeof schema.maxItems === 'number') { metadata.constraints.push(`Length: [${schema.minItems || 0}${schema.maxItems ? ', ' : '+'}${schema.maxItems || ''}]`); } + if (Array.isArray(schema['x-conditions'])) { metadata.conditions = schema['x-conditions']; } if (allOf) { // If allOf is an array of multiple elements, then all the keys makes a single object diff --git a/tests/schema-utils.test.js b/tests/schema-utils.test.js index d1fa5a71..55b6511e 100644 --- a/tests/schema-utils.test.js +++ b/tests/schema-utils.test.js @@ -157,3 +157,22 @@ test('schema-utils.js getTypeInfo shows the unique items constraint only for arr expect(getTypeInfo({ type: 'string[]┃null', uniqueItems: true }).constraints).to.eql(['Requires unique items']); t.pass(); }); + +test('schema-utils.js schemaInObjectNotation shows if/then rules from allOf as constraints on the affected property', (t) => { + const schema = { + type: 'object', + properties: { id: { type: 'string', pattern: '[a-z_]+' }, type: { type: 'string', enum: ['HALL', 'STAND'] } }, + allOf: [ + { if: { properties: { type: { const: 'HALL' } }, required: ['type'] }, then: { properties: { id: { pattern: '^hall_' } } } }, + { if: { properties: { type: { const: 'STAND' } } }, then: { required: ['id'] }, else: { properties: { id: { maxLength: 5 } } } } + ] + }; + const result = schemaInObjectNotation(schema, {}); + t.deepEqual(Object.keys(result).filter((k) => !k.startsWith('::')), ['id', 'type']); + t.deepEqual(JSON.parse(result.id).constraints, []); + t.deepEqual(JSON.parse(result.id).conditions, [ + { when: 'If type = HALL', rules: [{ label: 'Pattern', value: '^hall_' }] }, + { when: 'If type = STAND', rules: [{ label: 'Required', value: '' }] }, + { when: 'If not (type = STAND)', rules: [{ label: 'Max length', value: '5' }] } + ]); +});