UNPKG

@kubb/plugin-oas

Version:

OpenAPI Specification (OAS) plugin for Kubb, providing core functionality for parsing and processing OpenAPI/Swagger schemas for code generation.

1,038 lines (1,033 loc) • 36.2 kB
const require_chunk = require('./chunk-CbDLau6x.cjs'); const require_SchemaMapper = require('./SchemaMapper-BUV8vhg0.cjs'); const require_getSchemas = require('./getSchemas-BTCpbjet.cjs'); let __kubb_core = require("@kubb/core"); let __kubb_core_transformers = require("@kubb/core/transformers"); __kubb_core_transformers = require_chunk.__toESM(__kubb_core_transformers); let __kubb_react_fabric = require("@kubb/react-fabric"); let __kubb_react_fabric_jsx_runtime = require("@kubb/react-fabric/jsx-runtime"); let __kubb_oas = require("@kubb/oas"); let remeda = require("remeda"); let __kubb_core_utils = require("@kubb/core/utils"); //#region ../../node_modules/.pnpm/yocto-queue@1.2.2/node_modules/yocto-queue/index.js var Node = class { value; next; constructor(value) { this.value = value; } }; var Queue = class { #head; #tail; #size; constructor() { this.clear(); } enqueue(value) { const node = new Node(value); if (this.#head) { this.#tail.next = node; this.#tail = node; } else { this.#head = node; this.#tail = node; } this.#size++; } dequeue() { const current = this.#head; if (!current) return; this.#head = this.#head.next; this.#size--; if (!this.#head) this.#tail = void 0; return current.value; } peek() { if (!this.#head) return; return this.#head.value; } clear() { this.#head = void 0; this.#tail = void 0; this.#size = 0; } get size() { return this.#size; } *[Symbol.iterator]() { let current = this.#head; while (current) { yield current.value; current = current.next; } } *drain() { while (this.#head) yield this.dequeue(); } }; //#endregion //#region ../../node_modules/.pnpm/p-limit@7.2.0/node_modules/p-limit/index.js function pLimit(concurrency) { validateConcurrency(concurrency); const queue = new Queue(); let activeCount = 0; const resumeNext = () => { if (activeCount < concurrency && queue.size > 0) { activeCount++; queue.dequeue()(); } }; const next = () => { activeCount--; resumeNext(); }; const run = async (function_, resolve, arguments_) => { const result = (async () => function_(...arguments_))(); resolve(result); try { await result; } catch {} next(); }; const enqueue = (function_, resolve, arguments_) => { new Promise((internalResolve) => { queue.enqueue(internalResolve); }).then(run.bind(void 0, function_, resolve, arguments_)); if (activeCount < concurrency) resumeNext(); }; const generator = (function_, ...arguments_) => new Promise((resolve) => { enqueue(function_, resolve, arguments_); }); Object.defineProperties(generator, { activeCount: { get: () => activeCount }, pendingCount: { get: () => queue.size }, clearQueue: { value() { queue.clear(); } }, concurrency: { get: () => concurrency, set(newConcurrency) { validateConcurrency(newConcurrency); concurrency = newConcurrency; queueMicrotask(() => { while (activeCount < concurrency && queue.size > 0) resumeNext(); }); } }, map: { async value(iterable, function_) { const promises = Array.from(iterable, (value, index) => this(function_, value, index)); return Promise.all(promises); } } }); return generator; } function validateConcurrency(concurrency) { if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) throw new TypeError("Expected `concurrency` to be a number from 1 and up"); } //#endregion //#region src/utils.tsx async function buildOperations(operations, { config, fabric, plugin, generator, Component }) { if (!Component) return; const { pluginManager, oas, mode } = generator.context; const fabricChild = (0, __kubb_react_fabric.createReactFabric)(); await fabricChild.render(() => { return /* @__PURE__ */ (0, __kubb_react_fabric_jsx_runtime.jsx)(__kubb_react_fabric.App, { meta: { pluginManager, plugin, mode, oas }, children: /* @__PURE__ */ (0, __kubb_react_fabric_jsx_runtime.jsx)(Component, { config, operations, generator, plugin }) }); }); await fabric.context.fileManager.upsert(...fabricChild.files); } async function buildOperation(operation, { config, fabric, plugin, generator, Component }) { if (!Component) return; const { pluginManager, oas, mode } = generator.context; const fabricChild = (0, __kubb_react_fabric.createReactFabric)(); await fabricChild.render(() => { return /* @__PURE__ */ (0, __kubb_react_fabric_jsx_runtime.jsx)(__kubb_react_fabric.App, { meta: { pluginManager, plugin, mode, oas }, children: /* @__PURE__ */ (0, __kubb_react_fabric_jsx_runtime.jsx)(Component, { config, operation, plugin, generator }) }); }); await fabric.context.fileManager.upsert(...fabricChild.files); } async function buildSchema(schema, { config, fabric, plugin, Component, generator }) { if (!Component) return; const { pluginManager, oas, mode } = generator.context; const fabricChild = (0, __kubb_react_fabric.createReactFabric)(); await fabricChild.render(() => { return /* @__PURE__ */ (0, __kubb_react_fabric_jsx_runtime.jsx)(__kubb_react_fabric.App, { meta: { pluginManager, plugin, mode, oas }, children: /* @__PURE__ */ (0, __kubb_react_fabric_jsx_runtime.jsx)(Component, { config, schema, plugin, generator }) }); }); await fabric.context.fileManager.upsert(...fabricChild.files); } //#endregion //#region src/SchemaGenerator.ts var SchemaGenerator = class SchemaGenerator extends __kubb_core.BaseGenerator { refs = {}; #usedAliasNames = {}; /** * Creates a type node from a given schema. * Delegates to getBaseTypeFromSchema internally and * optionally adds a union with null. */ parse(props) { const options = this.#getOptions(props); const defaultSchemas = this.#parseSchemaObject(props); return (0, remeda.uniqueWith)(options.transformers?.schema?.(props, defaultSchemas) || defaultSchemas || [], remeda.isDeepEqual); } static deepSearch(tree, keyword) { const foundItems = []; tree?.forEach((schema) => { if (schema.keyword === keyword) foundItems.push(schema); if (require_SchemaMapper.isKeyword(schema, require_SchemaMapper.schemaKeywords.object)) { Object.values(schema.args?.properties || {}).forEach((entrySchema) => { foundItems.push(...SchemaGenerator.deepSearch(entrySchema, keyword)); }); Object.values(schema.args?.additionalProperties || {}).forEach((entrySchema) => { foundItems.push(...SchemaGenerator.deepSearch([entrySchema], keyword)); }); } if (require_SchemaMapper.isKeyword(schema, require_SchemaMapper.schemaKeywords.array)) schema.args.items.forEach((entrySchema) => { foundItems.push(...SchemaGenerator.deepSearch([entrySchema], keyword)); }); if (require_SchemaMapper.isKeyword(schema, require_SchemaMapper.schemaKeywords.and)) schema.args.forEach((entrySchema) => { foundItems.push(...SchemaGenerator.deepSearch([entrySchema], keyword)); }); if (require_SchemaMapper.isKeyword(schema, require_SchemaMapper.schemaKeywords.tuple)) schema.args.items.forEach((entrySchema) => { foundItems.push(...SchemaGenerator.deepSearch([entrySchema], keyword)); }); if (require_SchemaMapper.isKeyword(schema, require_SchemaMapper.schemaKeywords.union)) schema.args.forEach((entrySchema) => { foundItems.push(...SchemaGenerator.deepSearch([entrySchema], keyword)); }); }); return foundItems; } static find(tree, keyword) { let foundItem; tree?.forEach((schema) => { if (!foundItem && schema.keyword === keyword) foundItem = schema; if (require_SchemaMapper.isKeyword(schema, require_SchemaMapper.schemaKeywords.array)) schema.args.items.forEach((entrySchema) => { if (!foundItem) foundItem = SchemaGenerator.find([entrySchema], keyword); }); if (require_SchemaMapper.isKeyword(schema, require_SchemaMapper.schemaKeywords.and)) schema.args.forEach((entrySchema) => { if (!foundItem) foundItem = SchemaGenerator.find([entrySchema], keyword); }); if (require_SchemaMapper.isKeyword(schema, require_SchemaMapper.schemaKeywords.tuple)) schema.args.items.forEach((entrySchema) => { if (!foundItem) foundItem = SchemaGenerator.find([entrySchema], keyword); }); if (require_SchemaMapper.isKeyword(schema, require_SchemaMapper.schemaKeywords.union)) schema.args.forEach((entrySchema) => { if (!foundItem) foundItem = SchemaGenerator.find([entrySchema], keyword); }); }); return foundItem; } static combineObjects(tree) { if (!tree) return []; return tree.map((schema) => { if (!require_SchemaMapper.isKeyword(schema, require_SchemaMapper.schemaKeywords.and)) return schema; let mergedProperties = null; let mergedAdditionalProps = []; const newArgs = []; for (const subSchema of schema.args) if (require_SchemaMapper.isKeyword(subSchema, require_SchemaMapper.schemaKeywords.object)) { const { properties = {}, additionalProperties = [] } = subSchema.args ?? {}; if (!mergedProperties) mergedProperties = {}; for (const [key, value] of Object.entries(properties)) mergedProperties[key] = value; if (additionalProperties.length > 0) mergedAdditionalProps = additionalProperties; } else newArgs.push(subSchema); if (mergedProperties) newArgs.push({ keyword: require_SchemaMapper.schemaKeywords.object, args: { properties: mergedProperties, additionalProperties: mergedAdditionalProps } }); return { keyword: require_SchemaMapper.schemaKeywords.and, args: newArgs }; }); } #getOptions({ name }) { const { override = [] } = this.context; return { ...this.options, ...override.find(({ pattern, type }) => { if (name && type === "schemaName") return !!name.match(pattern); return false; })?.options || {} }; } #getUnknownType(props) { const options = this.#getOptions(props); if (options.unknownType === "any") return require_SchemaMapper.schemaKeywords.any; if (options.unknownType === "void") return require_SchemaMapper.schemaKeywords.void; return require_SchemaMapper.schemaKeywords.unknown; } #getEmptyType(props) { const options = this.#getOptions(props); if (options.emptySchemaType === "any") return require_SchemaMapper.schemaKeywords.any; if (options.emptySchemaType === "void") return require_SchemaMapper.schemaKeywords.void; return require_SchemaMapper.schemaKeywords.unknown; } /** * Recursively creates a type literal with the given props. */ #parseProperties({ schemaObject, name }) { const properties = schemaObject?.properties || {}; const additionalProperties = schemaObject?.additionalProperties; const required = schemaObject?.required; const propertiesSchemas = Object.keys(properties).map((propertyName) => { const validationFunctions = []; const propertySchema = properties[propertyName]; const isRequired = Array.isArray(required) ? required?.includes(propertyName) : !!required; const nullable = propertySchema.nullable ?? propertySchema["x-nullable"] ?? false; validationFunctions.push(...this.parse({ schemaObject: propertySchema, name: propertyName, parentName: name })); validationFunctions.push({ keyword: require_SchemaMapper.schemaKeywords.name, args: propertyName }); if (!isRequired && nullable) validationFunctions.push({ keyword: require_SchemaMapper.schemaKeywords.nullish }); else if (!isRequired) validationFunctions.push({ keyword: require_SchemaMapper.schemaKeywords.optional }); return { [propertyName]: validationFunctions }; }).reduce((acc, curr) => ({ ...acc, ...curr }), {}); let additionalPropertiesSchemas = []; if (additionalProperties) additionalPropertiesSchemas = additionalProperties === true || !Object.keys(additionalProperties).length ? [{ keyword: this.#getUnknownType({ schemaObject, name }) }] : this.parse({ schemaObject: additionalProperties, parentName: name }); return [{ keyword: require_SchemaMapper.schemaKeywords.object, args: { properties: propertiesSchemas, additionalProperties: additionalPropertiesSchemas } }]; } /** * Create a type alias for the schema referenced by the given ReferenceObject */ #getRefAlias(schemaObject, name) { const { $ref } = schemaObject; const ref = this.refs[$ref]; if (ref) { const dereferencedSchema = this.context.oas.dereferenceWithRef(schemaObject); if (dereferencedSchema && (0, __kubb_oas.isDiscriminator)(dereferencedSchema)) { const [key] = Object.entries(dereferencedSchema.discriminator.mapping || {}).find(([_key, value]) => value.replace(/.+\//, "") === name) || []; if (key) return [{ keyword: require_SchemaMapper.schemaKeywords.and, args: [{ keyword: require_SchemaMapper.schemaKeywords.ref, args: { name: ref.propertyName, $ref, path: ref.path, isImportable: !!this.context.oas.get($ref) } }, { keyword: require_SchemaMapper.schemaKeywords.object, args: { properties: { [dereferencedSchema.discriminator.propertyName]: [{ keyword: require_SchemaMapper.schemaKeywords.const, args: { name: key, format: "string", value: key } }] } } }] }]; } return [{ keyword: require_SchemaMapper.schemaKeywords.ref, args: { name: ref.propertyName, $ref, path: ref.path, isImportable: !!this.context.oas.get($ref) } }]; } const originalName = (0, __kubb_core_utils.getUniqueName)($ref.replace(/.+\//, ""), this.#usedAliasNames); const propertyName = this.context.pluginManager.resolveName({ name: originalName, pluginKey: this.context.plugin.key, type: "function" }); const fileName = this.context.pluginManager.resolveName({ name: originalName, pluginKey: this.context.plugin.key, type: "file" }); const file = this.context.pluginManager.getFile({ name: fileName, pluginKey: this.context.plugin.key, extname: ".ts" }); this.refs[$ref] = { propertyName, originalName, path: file.path }; return this.#getRefAlias(schemaObject, name); } #getParsedSchemaObject(schema) { return require_getSchemas.getSchemaFactory(this.context.oas)(schema); } #addDiscriminatorToSchema({ schema, schemaObject, discriminator }) { if (!require_SchemaMapper.isKeyword(schema, require_SchemaMapper.schemaKeywords.union)) return schema; const objectPropertySchema = SchemaGenerator.find(this.parse({ schemaObject }), require_SchemaMapper.schemaKeywords.object); return { ...schema, args: Object.entries(discriminator.mapping || {}).map(([key, value]) => { const arg = schema.args.find((item) => require_SchemaMapper.isKeyword(item, require_SchemaMapper.schemaKeywords.ref) && item.args.$ref === value); return { keyword: require_SchemaMapper.schemaKeywords.and, args: [arg, { keyword: require_SchemaMapper.schemaKeywords.object, args: { properties: { ...objectPropertySchema?.args?.properties || {}, [discriminator.propertyName]: [{ keyword: require_SchemaMapper.schemaKeywords.const, args: { name: key, format: "string", value: key } }, ...objectPropertySchema?.args?.properties[discriminator.propertyName] || []].filter((item) => !require_SchemaMapper.isKeyword(item, require_SchemaMapper.schemaKeywords.enum)) } } }] }; }) }; } /** * This is the very core of the OpenAPI to TS conversion - it takes a * schema and returns the appropriate type. */ #parseSchemaObject({ schemaObject: _schemaObject, name, parentName }) { const { schemaObject, version } = this.#getParsedSchemaObject(_schemaObject); const options = this.#getOptions({ schemaObject, name }); const emptyType = this.#getEmptyType({ schemaObject, name }); if (!schemaObject) return [{ keyword: emptyType }]; const baseItems = [{ keyword: require_SchemaMapper.schemaKeywords.schema, args: { type: schemaObject.type, format: schemaObject.format } }]; const min = schemaObject.minimum ?? schemaObject.minLength ?? schemaObject.minItems ?? void 0; const max = schemaObject.maximum ?? schemaObject.maxLength ?? schemaObject.maxItems ?? void 0; const exclusiveMinimum = schemaObject.exclusiveMinimum; const exclusiveMaximum = schemaObject.exclusiveMaximum; const nullable = (0, __kubb_oas.isNullable)(schemaObject); const defaultNullAndNullable = schemaObject.default === null && nullable; if (schemaObject.default !== void 0 && !defaultNullAndNullable && !Array.isArray(schemaObject.default)) if (typeof schemaObject.default === "string") baseItems.push({ keyword: require_SchemaMapper.schemaKeywords.default, args: __kubb_core_transformers.default.stringify(schemaObject.default) }); else if (typeof schemaObject.default === "boolean") baseItems.push({ keyword: require_SchemaMapper.schemaKeywords.default, args: schemaObject.default ?? false }); else baseItems.push({ keyword: require_SchemaMapper.schemaKeywords.default, args: schemaObject.default }); if (schemaObject.deprecated) baseItems.push({ keyword: require_SchemaMapper.schemaKeywords.deprecated }); if (schemaObject.description) baseItems.push({ keyword: require_SchemaMapper.schemaKeywords.describe, args: schemaObject.description }); if (max !== void 0) if (exclusiveMaximum) baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.exclusiveMaximum, args: max }); else baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.max, args: max }); if (min !== void 0) if (exclusiveMinimum) baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.exclusiveMinimum, args: min }); else baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.min, args: min }); if (typeof exclusiveMaximum === "number") baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.exclusiveMaximum, args: exclusiveMaximum }); if (typeof exclusiveMinimum === "number") baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.exclusiveMinimum, args: exclusiveMinimum }); if (nullable) baseItems.push({ keyword: require_SchemaMapper.schemaKeywords.nullable }); if (schemaObject.type && Array.isArray(schemaObject.type)) { const items = schemaObject.type.filter((value) => value !== "null"); if (schemaObject.type.includes("null") && !nullable) baseItems.push({ keyword: require_SchemaMapper.schemaKeywords.nullable }); if (items.length > 1) return [...[{ keyword: require_SchemaMapper.schemaKeywords.union, args: items.map((item) => this.parse({ schemaObject: { ...schemaObject, type: item }, name, parentName })[0]).filter(Boolean).filter((item) => !require_SchemaMapper.isKeyword(item, require_SchemaMapper.schemaKeywords.unknown)).map((item) => require_SchemaMapper.isKeyword(item, require_SchemaMapper.schemaKeywords.object) ? { ...item, args: { ...item.args, strict: true } } : item) }], ...baseItems].filter(Boolean); } if (schemaObject.readOnly) baseItems.push({ keyword: require_SchemaMapper.schemaKeywords.readOnly }); if (schemaObject.writeOnly) baseItems.push({ keyword: require_SchemaMapper.schemaKeywords.writeOnly }); if ((0, __kubb_oas.isReference)(schemaObject)) return [ ...this.#getRefAlias(schemaObject, name), schemaObject.description && { keyword: require_SchemaMapper.schemaKeywords.describe, args: schemaObject.description }, schemaObject.pattern && schemaObject.type === "string" && { keyword: require_SchemaMapper.schemaKeywords.matches, args: schemaObject.pattern }, nullable && { keyword: require_SchemaMapper.schemaKeywords.nullable }, schemaObject.readOnly && { keyword: require_SchemaMapper.schemaKeywords.readOnly }, schemaObject.writeOnly && { keyword: require_SchemaMapper.schemaKeywords.writeOnly }, { keyword: require_SchemaMapper.schemaKeywords.schema, args: { type: schemaObject.type, format: schemaObject.format } } ].filter(Boolean); if (schemaObject.oneOf || schemaObject.anyOf) { const schemaWithoutOneOf = { ...schemaObject, oneOf: void 0, anyOf: void 0 }; const discriminator = this.context.oas.getDiscriminator(schemaObject); const union = { keyword: require_SchemaMapper.schemaKeywords.union, args: (schemaObject.oneOf || schemaObject.anyOf).map((item) => { return item && this.parse({ schemaObject: item, name, parentName })[0]; }).filter(Boolean).filter((item) => !require_SchemaMapper.isKeyword(item, require_SchemaMapper.schemaKeywords.unknown)) }; if (discriminator) { if (this.context && this.context.oas.options.discriminator !== "inherit") return [this.#addDiscriminatorToSchema({ schemaObject: schemaWithoutOneOf, schema: union, discriminator }), ...baseItems]; } if (schemaWithoutOneOf.properties) { const propertySchemas = this.parse({ schemaObject: schemaWithoutOneOf, name, parentName }); union.args = [...union.args.map((arg) => { return { keyword: require_SchemaMapper.schemaKeywords.and, args: [arg, ...propertySchemas] }; })]; return [union, ...baseItems]; } return [union, ...baseItems]; } if (schemaObject.allOf) { const schemaWithoutAllOf = { ...schemaObject, allOf: void 0 }; const and = { keyword: require_SchemaMapper.schemaKeywords.and, args: schemaObject.allOf.map((item) => { return item && this.parse({ schemaObject: item, name, parentName })[0]; }).filter(Boolean).filter((item) => !require_SchemaMapper.isKeyword(item, require_SchemaMapper.schemaKeywords.unknown)) }; if (schemaWithoutAllOf.required?.length) { const allOfItems = schemaObject.allOf; const resolvedSchemas = []; for (const item of allOfItems) { const resolved = (0, __kubb_oas.isReference)(item) ? this.context.oas.get(item.$ref) : item; if (resolved) resolvedSchemas.push(resolved); } const existingKeys = schemaWithoutAllOf.properties ? new Set(Object.keys(schemaWithoutAllOf.properties)) : null; const parsedItems = []; for (const key of schemaWithoutAllOf.required) { if (existingKeys?.has(key)) continue; for (const schema of resolvedSchemas) if (schema.properties?.[key]) { parsedItems.push({ properties: { [key]: schema.properties[key] }, required: [key] }); break; } } for (const item of parsedItems) { const parsed = this.parse({ schemaObject: item, name, parentName }); if (Array.isArray(parsed)) and.args = and.args ? and.args.concat(parsed) : parsed; } } if (schemaWithoutAllOf.properties) and.args = [...and.args || [], ...this.parse({ schemaObject: schemaWithoutAllOf, name, parentName })]; return SchemaGenerator.combineObjects([and, ...baseItems]); } if (schemaObject.enum) { if (options.enumSuffix === "") this.context.pluginManager.logger.emit("info", "EnumSuffix set to an empty string does not work"); const enumName = (0, __kubb_core_utils.getUniqueName)((0, __kubb_core_transformers.pascalCase)([ parentName, name, options.enumSuffix ].join(" ")), this.options.usedEnumNames || {}); const typeName = this.context.pluginManager.resolveName({ name: enumName, pluginKey: this.context.plugin.key, type: "type" }); if (schemaObject.enum.includes(null)) baseItems.push({ keyword: require_SchemaMapper.schemaKeywords.nullable }); const filteredValues = schemaObject.enum.filter((value) => value !== null); const extensionEnums = ["x-enumNames", "x-enum-varnames"].filter((extensionKey) => extensionKey in schemaObject).map((extensionKey) => { return [{ keyword: require_SchemaMapper.schemaKeywords.enum, args: { name, typeName, asConst: false, items: [...new Set(schemaObject[extensionKey])].map((name$1, index) => ({ name: __kubb_core_transformers.default.stringify(name$1), value: schemaObject.enum?.[index], format: (0, remeda.isNumber)(schemaObject.enum?.[index]) ? "number" : "string" })) } }, ...baseItems.filter((item) => item.keyword !== require_SchemaMapper.schemaKeywords.min && item.keyword !== require_SchemaMapper.schemaKeywords.max && item.keyword !== require_SchemaMapper.schemaKeywords.matches)]; }); if (schemaObject.type === "number" || schemaObject.type === "integer") { const enumNames = extensionEnums[0]?.find((item) => require_SchemaMapper.isKeyword(item, require_SchemaMapper.schemaKeywords.enum)); return [{ keyword: require_SchemaMapper.schemaKeywords.enum, args: { name: enumName, typeName, asConst: true, items: enumNames?.args?.items ? [...new Set(enumNames.args.items)].map(({ name: name$1, value }) => ({ name: name$1, value, format: "number" })) : [...new Set(filteredValues)].map((value) => { return { name: value, value, format: "number" }; }) } }, ...baseItems.filter((item) => item.keyword !== require_SchemaMapper.schemaKeywords.min && item.keyword !== require_SchemaMapper.schemaKeywords.max && item.keyword !== require_SchemaMapper.schemaKeywords.matches)]; } if (schemaObject.type === "boolean") { const enumNames = extensionEnums[0]?.find((item) => require_SchemaMapper.isKeyword(item, require_SchemaMapper.schemaKeywords.enum)); return [{ keyword: require_SchemaMapper.schemaKeywords.enum, args: { name: enumName, typeName, asConst: true, items: enumNames?.args?.items ? [...new Set(enumNames.args.items)].map(({ name: name$1, value }) => ({ name: name$1, value, format: "boolean" })) : [...new Set(filteredValues)].map((value) => { return { name: value, value, format: "boolean" }; }) } }, ...baseItems.filter((item) => item.keyword !== require_SchemaMapper.schemaKeywords.matches)]; } if (extensionEnums.length > 0 && extensionEnums[0]) return extensionEnums[0]; return [{ keyword: require_SchemaMapper.schemaKeywords.enum, args: { name: enumName, typeName, asConst: false, items: [...new Set(filteredValues)].map((value) => ({ name: __kubb_core_transformers.default.stringify(value), value, format: (0, remeda.isNumber)(value) ? "number" : "string" })) } }, ...baseItems.filter((item) => item.keyword !== require_SchemaMapper.schemaKeywords.min && item.keyword !== require_SchemaMapper.schemaKeywords.max && item.keyword !== require_SchemaMapper.schemaKeywords.matches)]; } if ("prefixItems" in schemaObject) { const prefixItems = schemaObject.prefixItems; const items = "items" in schemaObject ? schemaObject.items : []; const min$1 = schemaObject.minimum ?? schemaObject.minLength ?? schemaObject.minItems ?? void 0; const max$1 = schemaObject.maximum ?? schemaObject.maxLength ?? schemaObject.maxItems ?? void 0; return [{ keyword: require_SchemaMapper.schemaKeywords.tuple, args: { min: min$1, max: max$1, items: prefixItems.map((item) => { return this.parse({ schemaObject: item, name, parentName })[0]; }).filter(Boolean), rest: this.parse({ schemaObject: items, name, parentName })[0] } }, ...baseItems.filter((item) => item.keyword !== require_SchemaMapper.schemaKeywords.min && item.keyword !== require_SchemaMapper.schemaKeywords.max)]; } if (version === "3.1" && "const" in schemaObject) { if (schemaObject["const"] === null) return [{ keyword: require_SchemaMapper.schemaKeywords.null }]; if (schemaObject["const"] === void 0) return [{ keyword: require_SchemaMapper.schemaKeywords.undefined }]; let format = typeof schemaObject["const"]; if (format !== "number" && format !== "boolean") format = "string"; return [{ keyword: require_SchemaMapper.schemaKeywords.const, args: { name: schemaObject["const"], format, value: schemaObject["const"] } }, ...baseItems]; } /** * > Structural validation alone may be insufficient to allow an application to correctly utilize certain values. The "format" * > annotation keyword is defined to allow schema authors to convey semantic information for a fixed subset of values which are * > accurately described by authoritative resources, be they RFCs or other external specifications. * * In other words: format is more specific than type alone, hence it should override the type value, if possible. * * see also https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-00#rfc.section.7 */ if (schemaObject.format) { if (schemaObject.type === "integer" && (schemaObject.format === "int32" || schemaObject.format === "int64")) { baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.integer }); return baseItems; } if (schemaObject.type === "number" && (schemaObject.format === "float" || schemaObject.format === "double")) { baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.number }); return baseItems; } switch (schemaObject.format) { case "binary": baseItems.push({ keyword: require_SchemaMapper.schemaKeywords.blob }); return baseItems; case "date-time": if (options.dateType) { if (options.dateType === "date") { baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.date, args: { type: "date" } }); return baseItems; } if (options.dateType === "stringOffset") { baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.datetime, args: { offset: true } }); return baseItems; } if (options.dateType === "stringLocal") { baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.datetime, args: { local: true } }); return baseItems; } baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.datetime, args: { offset: false } }); return baseItems; } break; case "date": if (options.dateType) { if (options.dateType === "date") { baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.date, args: { type: "date" } }); return baseItems; } baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.date, args: { type: "string" } }); return baseItems; } break; case "time": if (options.dateType) { if (options.dateType === "date") { baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.time, args: { type: "date" } }); return baseItems; } baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.time, args: { type: "string" } }); return baseItems; } break; case "uuid": baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.uuid }); return baseItems; case "email": case "idn-email": baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.email }); return baseItems; case "uri": case "ipv4": case "ipv6": case "uri-reference": case "hostname": case "idn-hostname": baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.url }); return baseItems; default: break; } } if (schemaObject.pattern && schemaObject.type === "string") { baseItems.unshift({ keyword: require_SchemaMapper.schemaKeywords.matches, args: schemaObject.pattern }); return baseItems; } if ("items" in schemaObject || schemaObject.type === "array") { const min$1 = schemaObject.minimum ?? schemaObject.minLength ?? schemaObject.minItems ?? void 0; const max$1 = schemaObject.maximum ?? schemaObject.maxLength ?? schemaObject.maxItems ?? void 0; const items = this.parse({ schemaObject: "items" in schemaObject ? schemaObject.items : [], name, parentName }); const unique = !!schemaObject.uniqueItems; return [{ keyword: require_SchemaMapper.schemaKeywords.array, args: { items, min: min$1, max: max$1, unique } }, ...baseItems.filter((item) => item.keyword !== require_SchemaMapper.schemaKeywords.min && item.keyword !== require_SchemaMapper.schemaKeywords.max)]; } if (schemaObject.properties || schemaObject.additionalProperties) { if ((0, __kubb_oas.isDiscriminator)(schemaObject)) { const schemaObjectOverriden = Object.keys(schemaObject.properties || {}).reduce((acc, propertyName) => { if (acc.properties?.[propertyName] && propertyName === schemaObject.discriminator.propertyName) return { ...acc, properties: { ...acc.properties, [propertyName]: { ...acc.properties[propertyName] || {}, enum: schemaObject.discriminator.mapping ? Object.keys(schemaObject.discriminator.mapping) : void 0 } } }; return acc; }, schemaObject || {}); return [...this.#parseProperties({ schemaObject: schemaObjectOverriden, name }), ...baseItems]; } return [...this.#parseProperties({ schemaObject, name }), ...baseItems]; } if (schemaObject.type) { const type = Array.isArray(schemaObject.type) ? schemaObject.type.filter((item) => item !== "null")[0] : schemaObject.type; if (![ "boolean", "object", "number", "string", "integer", "null" ].includes(type)) this.context.pluginManager.logger.emit("warning", `Schema type '${schemaObject.type}' is not valid for schema ${parentName}.${name}`); return [{ keyword: type }, ...baseItems]; } return [{ keyword: emptyType }]; } async build(...generators) { const { oas, contentType, include } = this.context; const schemas = require_getSchemas.getSchemas({ oas, contentType, includes: include }); const schemaEntries = Object.entries(schemas); const generatorLimit = pLimit(1); const schemaLimit = pLimit(10); const writeTasks = generators.map((generator) => generatorLimit(async () => { const schemaTasks = schemaEntries.map(([name, schemaObject]) => schemaLimit(async () => { const options = this.#getOptions({ name }); const tree = this.parse({ name, schemaObject }); if (generator.type === "react") { await buildSchema({ name, value: schemaObject, tree }, { config: this.context.pluginManager.config, fabric: this.context.fabric, Component: generator.Schema, generator: this, plugin: { ...this.context.plugin, options: { ...this.options, ...options } } }); return []; } return await generator.schema?.({ config: this.context.pluginManager.config, generator: this, schema: { name, value: schemaObject, tree }, plugin: { ...this.context.plugin, options: { ...this.options, ...options } } }) ?? []; })); return (await Promise.all(schemaTasks)).flat(); })); return (await Promise.all(writeTasks)).flat(); } }; //#endregion Object.defineProperty(exports, 'SchemaGenerator', { enumerable: true, get: function () { return SchemaGenerator; } }); Object.defineProperty(exports, 'buildOperation', { enumerable: true, get: function () { return buildOperation; } }); Object.defineProperty(exports, 'buildOperations', { enumerable: true, get: function () { return buildOperations; } }); Object.defineProperty(exports, 'buildSchema', { enumerable: true, get: function () { return buildSchema; } }); Object.defineProperty(exports, 'pLimit', { enumerable: true, get: function () { return pLimit; } }); //# sourceMappingURL=SchemaGenerator-Bg5O155W.cjs.map