UNPKG

@kubb/plugin-faker

Version:
373 lines (368 loc) • 13.4 kB
'use strict'; var react = require('@kubb/react'); var transformers = require('@kubb/core/transformers'); var pluginOas = require('@kubb/plugin-oas'); var jsxRuntime = require('@kubb/react/jsx-runtime'); function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } var transformers__default = /*#__PURE__*/_interopDefault(transformers); // src/components/Faker.tsx var fakerKeywordMapper = { any: () => "undefined", unknown: () => "unknown", void: () => "void", number: (min, max) => { if (max !== void 0 && min !== void 0) { return `faker.number.float({ min: ${min}, max: ${max} })`; } if (max !== void 0) { return `faker.number.float({ max: ${max} })`; } if (min !== void 0) { return `faker.number.float({ min: ${min} })`; } return "faker.number.float()"; }, integer: (min, max) => { if (max !== void 0 && min !== void 0) { return `faker.number.int({ min: ${min}, max: ${max} })`; } if (max !== void 0) { return `faker.number.int({ max: ${max} })`; } if (min !== void 0) { return `faker.number.int({ min: ${min} })`; } return "faker.number.int()"; }, string: (min, max) => { if (max !== void 0 && min !== void 0) { return `faker.string.alpha({ length: { min: ${min}, max: ${max} } })`; } if (max !== void 0) { return `faker.string.alpha({ length: ${max} })`; } if (min !== void 0) { return `faker.string.alpha({ length: ${min} })`; } return "faker.string.alpha()"; }, boolean: () => "faker.datatype.boolean()", undefined: () => "undefined", null: () => "null", array: (items = [], min, max) => { if (items.length > 1) { return `faker.helpers.arrayElements([${items.join(", ")}])`; } const item = items.at(0); if (min !== void 0 && max !== void 0) { return `faker.helpers.multiple(() => (${item}), { count: { min: ${min}, max: ${max} }})`; } if (min !== void 0) { return `faker.helpers.multiple(() => (${item}), { count: ${min} })`; } if (max !== void 0) { return `faker.helpers.multiple(() => (${item}), { count: { min: 0, max: ${max} }})`; } return `faker.helpers.multiple(() => (${item}))`; }, tuple: (items = []) => `[${items.join(", ")}]`, enum: (items = [], type = "any") => `faker.helpers.arrayElement<${type}>([${items.join(", ")}])`, union: (items = []) => `faker.helpers.arrayElement<any>([${items.join(", ")}])`, /** * ISO 8601 */ datetime: () => "faker.date.anytime().toISOString()", /** * Type `'date'` Date * Type `'string'` ISO date format (YYYY-MM-DD) * @default ISO date format (YYYY-MM-DD) */ date: (type = "string", parser = "faker") => { if (type === "string") { if (parser !== "faker") { return `${parser}(faker.date.anytime()).format("YYYY-MM-DD")`; } return "faker.date.anytime().toISOString().substring(0, 10)"; } if (parser !== "faker") { throw new Error(`type '${type}' and parser '${parser}' can not work together`); } return "faker.date.anytime()"; }, /** * Type `'date'` Date * Type `'string'` ISO time format (HH:mm:ss[.SSSSSS]) * @default ISO time format (HH:mm:ss[.SSSSSS]) */ time: (type = "string", parser = "faker") => { if (type === "string") { if (parser !== "faker") { return `${parser}(faker.date.anytime()).format("HH:mm:ss")`; } return "faker.date.anytime().toISOString().substring(11, 19)"; } if (parser !== "faker") { throw new Error(`type '${type}' and parser '${parser}' can not work together`); } return "faker.date.anytime()"; }, uuid: () => "faker.string.uuid()", url: () => "faker.internet.url()", and: (items = []) => `Object.assign({}, ${items.join(", ")})`, object: () => "object", ref: () => "ref", matches: (value = "", regexGenerator = "faker") => { if (regexGenerator === "randexp") { return `${transformers__default.default.toRegExpString(value, "RandExp")}.gen()`; } return `faker.helpers.fromRegExp(${transformers__default.default.toRegExpString(value)})`; }, email: () => "faker.internet.email()", firstName: () => "faker.person.firstName()", lastName: () => "faker.person.lastName()", password: () => "faker.internet.password()", phone: () => "faker.phone.number()", blob: () => "faker.image.url() as unknown as Blob", default: void 0, describe: void 0, const: (value) => value ?? "", max: void 0, min: void 0, nullable: void 0, nullish: void 0, optional: void 0, readOnly: void 0, writeOnly: void 0, deprecated: void 0, example: void 0, schema: void 0, catchall: void 0, name: void 0, interface: void 0 }; function schemaKeywordSorter(_a, b) { if (b.keyword === "null") { return -1; } return 0; } function joinItems(items) { switch (items.length) { case 0: return "undefined"; case 1: return items[0]; default: return fakerKeywordMapper.union(items); } } function parse({ current, parent, name, siblings }, options) { const value = fakerKeywordMapper[current.keyword]; if (!value) { return void 0; } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.union)) { return fakerKeywordMapper.union( current.args.map((schema) => parse({ parent: current, current: schema, siblings }, { ...options, canOverride: false })).filter(Boolean) ); } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.and)) { return fakerKeywordMapper.and( current.args.map((schema) => parse({ parent: current, current: schema, siblings }, { ...options, canOverride: false })).filter(Boolean) ); } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.array)) { return fakerKeywordMapper.array( current.args.items.map( (schema) => parse( { parent: current, current: schema, siblings }, { ...options, typeName: `${options.typeName}["${name}"][number]`, canOverride: false } ) ).filter(Boolean), current.args.min, current.args.max ); } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.enum)) { const isParentTuple = parent ? pluginOas.isKeyword(parent, pluginOas.schemaKeywords.tuple) : false; if (isParentTuple) { return fakerKeywordMapper.enum( current.args.items.map((schema) => { if (schema.format === "number") { return schema.value; } if (schema.format === "boolean") { return schema.value; } return transformers__default.default.stringify(schema.value); }) ); } return fakerKeywordMapper.enum( current.args.items.map((schema) => { if (schema.format === "number") { return schema.value; } if (schema.format === "boolean") { return schema.value; } return transformers__default.default.stringify(schema.value); }), // TODO replace this with getEnumNameFromSchema name ? `NonNullable<${options.typeName}>['${name}']` : void 0 ); } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.ref)) { if (!current.args?.name) { throw new Error(`Name not defined for keyword ${current.keyword}`); } if (options.canOverride) { return `${current.args.name}(data)`; } return `${current.args.name}()`; } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.object)) { const argsObject = Object.entries(current.args?.properties || {}).filter((item) => { const schema = item[1]; return schema && typeof schema.map === "function"; }).map(([name2, schemas]) => { const nameSchema = schemas.find((schema) => schema.keyword === pluginOas.schemaKeywords.name); const mappedName = nameSchema?.args || name2; if (options.mapper?.[mappedName]) { return `"${name2}": ${options.mapper?.[mappedName]}`; } return `"${name2}": ${joinItems( schemas.sort(schemaKeywordSorter).map((schema) => parse({ name: name2, parent: current, current: schema, siblings: schemas }, { ...options, canOverride: false })).filter(Boolean) )}`; }).join(","); return `{${argsObject}}`; } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.tuple)) { if (Array.isArray(current.args.items)) { return fakerKeywordMapper.tuple( current.args.items.map((schema) => parse({ parent: current, current: schema, siblings }, { ...options, canOverride: false })).filter(Boolean) ); } return parse({ parent: current, current: current.args.items, siblings }, { ...options, canOverride: false }); } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.const)) { if (current.args.format === "number" && current.args.name !== void 0) { return fakerKeywordMapper.const(current.args.name?.toString()); } return fakerKeywordMapper.const(transformers__default.default.stringify(current.args.value)); } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.matches) && current.args) { return fakerKeywordMapper.matches(current.args, options.regexGenerator); } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.null) || pluginOas.isKeyword(current, pluginOas.schemaKeywords.undefined) || pluginOas.isKeyword(current, pluginOas.schemaKeywords.any)) { return value() || ""; } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.string)) { if (siblings) { const minSchema = pluginOas.SchemaGenerator.find(siblings, pluginOas.schemaKeywords.min); const maxSchema = pluginOas.SchemaGenerator.find(siblings, pluginOas.schemaKeywords.max); return fakerKeywordMapper.string(minSchema?.args, maxSchema?.args); } return fakerKeywordMapper.string(); } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.number)) { if (siblings) { const minSchema = pluginOas.SchemaGenerator.find(siblings, pluginOas.schemaKeywords.min); const maxSchema = pluginOas.SchemaGenerator.find(siblings, pluginOas.schemaKeywords.max); return fakerKeywordMapper.number(minSchema?.args, maxSchema?.args); } return fakerKeywordMapper.number(); } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.integer)) { if (siblings) { const minSchema = pluginOas.SchemaGenerator.find(siblings, pluginOas.schemaKeywords.min); const maxSchema = pluginOas.SchemaGenerator.find(siblings, pluginOas.schemaKeywords.max); return fakerKeywordMapper.integer(minSchema?.args, maxSchema?.args); } return fakerKeywordMapper.integer(); } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.datetime)) { return fakerKeywordMapper.datetime(); } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.date)) { return fakerKeywordMapper.date(current.args.type, options.dateParser); } if (pluginOas.isKeyword(current, pluginOas.schemaKeywords.time)) { return fakerKeywordMapper.time(current.args.type, options.dateParser); } if (current.keyword in fakerKeywordMapper && "args" in current) { const value2 = fakerKeywordMapper[current.keyword]; const options2 = JSON.stringify(current.args); return value2(options2); } if (current.keyword in fakerKeywordMapper) { return value(); } return void 0; } function Faker({ tree, description, name, typeName, seed, regexGenerator, canOverride, mapper, dateParser }) { const fakerText = joinItems( tree.map( (schema, _index, siblings) => parse( { parent: void 0, current: schema, siblings }, { name, typeName, seed, regexGenerator, mapper, canOverride, dateParser } ) ).filter(Boolean) ); const isArray = fakerText.startsWith("faker.helpers.arrayElements") || fakerText.startsWith("faker.helpers.multiple"); const isObject = fakerText.startsWith("{"); const isTuple = fakerText.startsWith("faker.helpers.arrayElement"); let fakerTextWithOverride = fakerText; if (canOverride && isObject) { fakerTextWithOverride = `{ ...${fakerText}, ...data || {} }`; } if (canOverride && isTuple) { fakerTextWithOverride = `data || ${fakerText}`; } if (canOverride && isArray) { fakerTextWithOverride = `[ ...${fakerText}, ...data || [] ]`; } const params = react.FunctionParams.factory({ data: { // making a partial out of an array does not make sense type: isArray ? typeName : `Partial<${typeName}>`, optional: true } }); return /* @__PURE__ */ jsxRuntime.jsx(react.File.Source, { name, isExportable: true, isIndexable: true, children: /* @__PURE__ */ jsxRuntime.jsxs( react.Function, { export: true, name, JSDoc: { comments: [description ? `@description ${transformers__default.default.jsStringEscape(description)}` : void 0].filter(Boolean) }, params: canOverride ? params.toConstructor() : void 0, returnType: canOverride ? typeName : void 0, children: [ seed ? `faker.seed(${JSON.stringify(seed)})` : void 0, /* @__PURE__ */ jsxRuntime.jsx("br", {}), `return ${fakerTextWithOverride}` ] } ) }); } exports.Faker = Faker; //# sourceMappingURL=chunk-V3J6VCNW.cjs.map //# sourceMappingURL=chunk-V3J6VCNW.cjs.map