-
#1459
6b485ddThanks @smorimoto! - Downgrade eta from 4.0.1 to 3.5.0 to fix module resolution error.After the upgrade to eta@4.0.1 in version 13.2.11, API generation started failing with
ERR_PACKAGE_PATH_NOT_EXPORTED: No "exports" main defined in eta/package.json. This issue is caused by incorrect package export configuration in eta@4.0.1, which is tracked in the upstream repository.Downgrading to eta@3.5.0 resolves the module resolution error whilst maintaining compatibility with the existing template system.
Fixes #1427.
afc2448Thanks @js2me! - added ability to override usageSchema and originalSchema after onInit hook and before all other operations
-
#1398
d987aeeThanks @k1rd3rf! - Fix modular template to always generate class property syntax.The modular template was incorrectly using object method syntax (
:and,) when route.namespace was present, introduced by PR #1326. This caused TypeScript syntax errors in generated code.The modular template should always generate class properties with arrow functions (
=and;), regardless of namespace presence.This resolves the issue reported in #1366 where version 13.2.8 generated invalid TypeScript code with modular templates.
-
#1424
aa79764Thanks @smorimoto! - Ensure discriminator mappings use union enum literals.Resolve discriminator mapping generation to use literal values when
generateUnionEnumsis enabled to avoid emitting enum member references. Add regression coverage that snapshots the discriminator output with union enums. -
#1422
724b0cdThanks @smorimoto! - Replacejs-yamlwithyaml.Switch YAML parsing from
js-yamltoyaml. Update the resolver to useYAML.parsewhenJSON.parsefails. Removejs-yamland its types, addyamlas a runtime dependency. No public API changes.
-
#1420
426433bThanks @smorimoto! - Move@types/lodashandopenapi-typesto dependencies.These type packages are referenced by the published declarations, so consumers require them at install time for correct type resolution. Moving them from
devDependenciesprevents downstream TypeScript errors whilst having no runtime impact.
-
#1390
5897e4bThanks @MatanAvneri! - Fix being able to call getComponentByRef from templates. -
#1393
9a7c788Thanks @RoCat! - Ensure discriminators are just after enums in components list to avoid cyclic errors. -
#1416
cd127a9Thanks @smorimoto! - Fix fetch client response parsing without re-reading body.
-
#1384
0caea2cThanks @smorimoto! - Fix enum const parsing for substrings of primitive types. -
#1381
ba052f4Thanks @smorimoto! - Support extracting request parameters for routes that only declare path parameters, such asDELETEmethods. -
#1382
792e96cThanks @smorimoto! - Fix enum string value quoting when schema type mismatches. -
#1385
859fc64Thanks @smorimoto! - Avoid response cloning in fetch HTTP client to prevent memory leaks (#779). -
#1383
8191970Thanks @smorimoto! - Automatically extract enums when using enum names as values. -
#1376
bec35e8Thanks @smorimoto! - MergeGenerateApiParamsBaseintoGenerateApiConfigurationto remove duplicated type definitions and expose missing configuration fields. Document configuration defaults with JSDoc tags. -
#1378
912e521Thanks @smorimoto! - Allow partialextractingOptionsingenerateApiconfiguration. -
#1380
fec0a09Thanks @smorimoto! - Add test verifying primitive + objectanyOfunions. -
#1376
bec35e8Thanks @smorimoto! - Restoremodularoption typing ingenerateApiparameters. -
#1379
339a167Thanks @smorimoto! - Support synchronousrequirein templates using Node'screateRequire.
-
#1326
99b5f50Thanks @thejhh! - Fix TypeScript generation failure for operationIds starting with numbersWhat: Fixed an issue where operationIds starting with numbers (e.g., "123getUser") would cause TypeScript generation to fail due to invalid identifier names.
Why: OperationIds that start with numbers are not valid JavaScript identifiers, causing syntax errors in the generated TypeScript code.
How: Modified the template logic to quote property names for invalid identifiers. OperationIds starting with numbers are now generated as quoted properties (e.g.,
"123GetUser": ...) instead of unquoted invalid identifiers.This resolves GitHub issue #952.
-
#1008
c2d3e6aThanks @frazar! - Fix handling of FormData inputs in Fetch HTTP clientPreviously, when users passed a
FormDataobject directly to the Fetch client'smultipart/form-dataformatter, it would incorrectly attempt to useObject.keys()on the FormData instance, which returns an empty array. This caused the FormData to be processed incorrectly.The fix adds a type check to return FormData instances unchanged, allowing users to have full control over FormData construction when needed whilst maintaining backwards compatibility for object inputs. This aligns the Fetch client behaviour with the existing Axios client implementation.
This resolves issues where users needed to send multipart requests with multiple entries for the same key, which is only possible with direct FormData manipulation.
- #1293
a87883bThanks @smorimoto! - Bump Biome to 2.0.
- #1287
87da340Thanks @smorimoto! - Pin versions of internal Biome packages.
-
#1260
31b628fThanks @parsaghk! - Fix enum key generation for values likeENUM_123_VALUE_456. -
#1277
3fd6224Thanks @smorimoto! - Revert "IntegrategenerateCommandarguments and run method into main command (#1198)". -
8a059bdThanks @smorimoto! - Update Node.js version requirements.
- #1187
1039ff1Thanks @gletournel! - Add support for json:api content type.
-
#1225
a013686Thanks @smorimoto! - Update the internal Biome to latest beta release. -
#1266
469ded7Thanks @dependabot! - Update the internal Biome to latest beta release. -
#1235
0e251bbThanks @smorimoto! - Fix typos in CLI option description and warning message. -
#1270
c79625eThanks @smorimoto! - Removerequiredfield from command definitions for now.
- #1200
3cc0194Thanks @smorimoto! - Searchswagger-typescript-api.configinstead ofconfigby default.
- #1198
1cb1c9cThanks @smorimoto! - IntegrategenerateCommandarguments and run method into main command.
- #1163
e477b58Thanks @RoXuS! - Ensure enums are at the top of the components to avoid issue on recursive schema parsing.
- #1144
ea1df18Thanks @smorimoto! - Usec12for wider configuration file format support.
-
#1171
c1cc45aThanks @smorimoto! - Fix TypeScript declaration file path. -
#1149
9d2d66aThanks @smorimoto! - Re-add TypeScript definitions for better type support. -
#1145
73f6bfdThanks @smorimoto! - Replace Prettier with Biome as the code formatter to improve performance during the code generation phase. -
#1141
821bfadThanks @dding-g! - Remove redundantunion-enumsoption in favor ofgenerate-union-enums.
-
6851bdcThanks @smorimoto! - Fix description forclientoption ingenerateCommand. -
#1121
5eadf67Thanks @takayukioda! - Fix to not useno-prefix in options. -
edca5deThanks @smorimoto! - Fix option name forgenerateUnionEnumsingenerateCommand. -
9fa8f41Thanks @smorimoto! - Sort the CLI arguments alphabetically.
-
#1119
c5e8d45Thanks @smorimoto! - Addshimsoption in tsup configuration and updaterootDirpath in templates generation process. -
#1119
c5e8d45Thanks @smorimoto! - Resolve internal references in Swagger v2 to OpenAPI v3 conversion by addingresolveInternaloption and enhancing type definitions for request payloads. -
#1119
c5e8d45Thanks @smorimoto! - Fix default value forno-clientoption ingenerateCommandtofalse. -
#1119
c5e8d45Thanks @smorimoto! - Addrequiredproperty to output path ingenerateTemplatesCommand. -
#1119
c5e8d45Thanks @smorimoto! - Fix documentation and type definition to align with actual implementation by renamingnametofileName.
-
#1106
9208816Thanks @smorimoto! - Add boolean type forextract-request-paramsin command configuration. -
#1106
c124f88Thanks @smorimoto! - Fix generateClient logic to exclude onlyno-clientargument. -
#1108
1e3b70eThanks @smorimoto! - Fix default value forno-clientargument in command configuration. -
#1106
4809884Thanks @smorimoto! - InitialisecustomConfigtoundefinedin command run function.
-
#1102
13da52aThanks @smorimoto! - Fix CLI executable by adding the required shebang to the entry file. -
#1102
13da52aThanks @smorimoto! - Fix query params detection on route name parsing -
#1102
13da52aThanks @smorimoto! - Improve type safety by adding proper types to SchemaComponent and introducing flags for extracted elements such as request parameters, request body, response body, and response errors.
-
#1046
40dd9d8Thanks @AugusDogus! - Respect debug and silent logging configuration for both cli and lib modes -
#1048
bd49e34Thanks @smorimoto! - Remove types fields from package.json as there are no types yet -
#929
1e2e00eThanks @BoltDoggy! - Fix route regex pattern in route name generation -
#701
0a71f2bThanks @nicky1038! - Remove unnecessary camel case conversion for query params -
#1041
47381deThanks @Jerome1337! - Add ts-nocheck comment to auto-generated file
- use import pattern that supports windows external drives by @smorimoto in #983
- Consola by @smorimoto in #903
- Fix
e.values(...).some is not a functionby @smorimoto in #884
- Fix #880 by @smorimoto in #881
- Use default export for lodash by @smorimoto in #878
- This was a version bump only, there were no code changes.
- Fix types by @smorimoto in #872
- Fix build warnings by @smorimoto in #873
- Reduce use of lodash by @smorimoto in #874
- Fix build warnings by @smorimoto in #875
- Revert "Fix contentFormatter for FormData returning an empty FormData object" by @smorimoto in #863
- Make types slightly better by @smorimoto in #859
- Set the build target to Node.js 18 by @smorimoto in #861
- fix: format option of requests when using extractResponseBody by @TaopaiC in #742
- Fix #671 - Content-Type: "multipart/form-data" is ignored (when using axios) by @cf-dlangston in #831
- Fix types by @smorimoto in #812
- Fix contentFormatter for FormData returning an empty FormData object by @JorensM in #747
- Checking if instanceof FormData before creating one by @dolevl in #680
- feat: add security in raw route info by @xfoxfu in #602
- Get rid of
requireby @smorimoto in #807
- Add support for both ESM and CJS by @smorimoto in #803
- ESM by @smorimoto in #788
- Fix type errors by @smorimoto in #787
- fix: support shared prettier config files by @pebo in #781
- Relax version constraints on dependencies by @smorimoto in #773
- Keep some dependency constraints tight by @smorimoto in #774
- This was a version bump only, there were no code changes.
- add missing apiClassName to GenerateApiParamsBase by @Mearman in #635
- fix: fix options manipulation by @vgprst in #631
- Fix typos by @szepeviktor in #698
- The default branch has been renamed and the next branch has been deprecated by @smorimoto in #735
- Clone the response in fetch HTTP client by @depsimon in #670
fix: problem with type any as base type of discriminator schema (cases when schema without discriminator is empty)
fix: problem with incorrect settings type suffix for internal discriminator mappings
feat: const keyword OpenAPI 3.0 draft
fix: problem with using anyOf
feat: --extract-responses (nodejs: extractResponses) option to extract all schemas from /components/responses
fix: discriminator and mapping with invalid discriminator property name (#551)
fix: problem with incorrect resolving type name of discriminator mapping types data contracts
BREAKING_CHANGE: disable support NodeJS 14.x
BREAKING_CHANGE: change swagger-typescript-api NodeJS "generateApi" function return type
BREAKING_CHANGE: remove rawModelTypes from output api configuration
feat: --custom-config <string> option (#503)
feat: --sort-routes option, ability to sort routes;
fix: critical bugs based with extract types and enums
fix: sort types option (sort was not correctly work with nested or extracted types)
fix: problems based with extracting enums;
fix: nullable enum with integer values (#543)
fix: generation enum numbers as strings one (#534)
chore: refactoring the axios imports
fix: non-object custom spec extensions (#500)
fix(docs): input instead of output in readme
internal: remove redundant internal scripts
internal: change process with using custom templates
interface GenerateApiOutput {
...
- files: { name: string; content: string; declaration: { name: string; content: string } | null }[];
+ files: { fileName: string; fileContent: string; fileExtension: string }[];
...
}internal: refactor schema parser code (preparing it for async code execution) fix: problem with filtering primitive in complex types (#459) feat: add discriminator property support (#456) internal: prepare code + templates for async code execution (next plans) fix: problems with dot in query params (hard fix) (#460) feature: ability to send custom Ts output code translator to js. Example:
const {
Translator,
} = require("swagger-typescript-api/src/translators/translator");
const {
JavascriptTranslator,
} = require("swagger-typescript-api/src/translators/javascript");
class MyTranslator extends Translator {
// or use extends JavascriptTranslator
translate({ fileName, fileExtension, fileContent }) {
// format ts\js code with using this codeFormatter (prettier + ts import fixer)
this.codeFormatter.format(fileContent);
// config of the code gen process
// logger
this.config.this.logger.return[
{
fileName,
fileExtension,
fileContent,
}
];
}
}fix: onCreateRoute skip behaviour fix: problems with prefixes\suffixes for extracted requests params, enums
Full Changelog: https://github.com/acacode/swagger-typescript-api/compare/12.0.3...12.0.4
security: update the eta package to address CVE-2022-25967
fix: missing option --extract-enums (#344)
fix: problem based with http requests and disableStrictSSL option (#453)
docs: update docs for requestOptions nodejs option
new hooks:
/** calls before parse\process route path */
onPreBuildRoutePath: (routePath: string) => string | void;
/** calls after parse\process route path */
onBuildRoutePath: (data: BuildRoutePath) => BuildRoutePath | void;
/** calls before insert path param name into string path interpolation */
onInsertPathParam: (paramName: string, index: number, arr: BuildRouteParam[], resultRoute: string) => string | void;
/** calls before parse any kind of schema */
onPreParseSchema: (originalSchema: any, typeName: string, schemaType: string) => any;BREAKING_CHANGE: add ability to custom prefix for autofix invalid enum keys, invalid type names with nodejs options (fixInvalidTypeNamePrefix: string, fixInvalidEnumKeyPrefix: string)
BREAKING_CHANGE: by default all component enum schemas (even numeric) extracting as enum TS constructions (#344)
feature: ability to extract all enums from nested types\interfaces to enum TS construction using --extract-enums option (#344)
feature: ability to modify route path params before insert them into string (request url, #446, with using hook onInsertPathParam)
feature: (nodejs) ability to add prefix\suffix for type names and enum keys
typePrefix?: string;
typeSuffix?: string;
enumKeyPrefix?: string;
enumKeySuffix?: string;feature: ability to customize resolving process of the extracting type names (extractingOptions nodejs option)
extractingOptions = {
// requestBodySuffix: ["Payload", "Body", "Input"],
// or
// requestBodyNameResolver: (typeName, reservedNames) => string;
// requestParamsSuffix: ["Params"],
// or
// requestParamsNameResolver: (typeName, reservedNames) => string;
// responseBodySuffix: ["Data", "Result", "Output"],
// or
// responseBodyNameResolver: (typeName, reservedNames) => string;
// responseErrorSuffix: ["Error", "Fail", "Fails", "ErrorData", "HttpError", "BadResponse"],
// or
// responseErrorNameResolver: (typeName, reservedNames) => string;
};docs: update docs for extraTemplates option
fix: problem with default name of single api file (Api.ts)
fix: problem based with tuple types (#445)
fix: problem with defaultResponseType declaration type
fix: problems with text/* content types (axios, fetch http clients) (thanks @JochenDiekenbrock, #312, #443)
fix: problem with application/json* content type (thanks @JochenDiekenbrock, #440, #441)
fix: different query type parameters declarations (in route name {?accountStatus,createdT, #439)
fix: problems with missing type imports in .d.ts files with using option --js
internal: add extra spec tests
fix: additionalProperties management problem in Swagger 2 (#343)
fix: hanging cli after execution finished (#436, thanks @Soarc)
fix: --api-class-name option has no default value (#433)
BREAKING_CHANGE: replace axios to node-fetch
feat: ability to send request options for getting swagger schema by url (requestOptions property)
- fix: problems with --http-client option in
generate-templatescommand - fix: rewrite file content in
generate-templatescommand (--rewriteflag)
data-contract-jsdoc.ejsfile uses new input structure. Please update your local copy.- new codebase (class way)
- ability to change everything in codegen process configuration with using NodeJS Api
- ability to call
generateApifunction 2 and more times per 1 NodeJS process. - new command
generate-templatesto create source templates
New command generate-templates which allow you to generate source templates which using with option --templates
Everything which creates codegen about output typescript code now contains in Ts field in src/configuration.
And this thing is available for end user modifications with using NodeJS Cli option codeGenConstructs.
It contains almost all which is not contains in .eta\ .ejs templates. For example: Record<string, any>, readonly typeField?: value, etc
Structure of Ts property
const Ts = {
Keyword: {
Number: "number",
String: "string",
Boolean: "boolean",
Any: "any",
Void: "void",
Unknown: "unknown",
Null: "null",
Undefined: "undefined",
Object: "object",
File: "File",
Date: "Date",
Type: "type",
Enum: "enum",
Interface: "interface",
Array: "Array",
Record: "Record",
Intersection: "&",
Union: "|",
},
CodeGenKeyword: {
UtilRequiredKeys: "UtilRequiredKeys",
},
/**
* $A[] or Array<$A>
*/
ArrayType: (content) => {
if (this.anotherArrayType) {
return Ts.TypeWithGeneric(Ts.Keyword.Array, [content]);
}
return `${Ts.ExpressionGroup(content)}[]`;
},
/**
* "$A"
*/
StringValue: (content) => `"${content}"`,
/**
* $A
*/
BooleanValue: (content) => `${content}`,
/**
* $A
*/
NumberValue: (content) => `${content}`,
/**
* $A
*/
NullValue: (content) => content,
/**
* $A1 | $A2
*/
UnionType: (contents) => _.join(_.uniq(contents), ` ${Ts.Keyword.Union} `),
/**
* ($A1)
*/
ExpressionGroup: (content) => (content ? `(${content})` : ""),
/**
* $A1 & $A2
*/
IntersectionType: (contents) =>
_.join(_.uniq(contents), ` ${Ts.Keyword.Intersection} `),
/**
* Record<$A1, $A2>
*/
RecordType: (key, value) =>
Ts.TypeWithGeneric(Ts.Keyword.Record, [key, value]),
/**
* readonly $key?:$value
*/
TypeField: ({ readonly, key, optional, value }) =>
_.compact([
readonly && "readonly ",
key,
optional && "?",
": ",
value,
]).join(""),
/**
* [key: $A1]: $A2
*/
InterfaceDynamicField: (key, value) => `[key: ${key}]: ${value}`,
/**
* $A1 = $A2
*/
EnumField: (key, value) => `${key} = ${value}`,
/**
* $A0.key = $A0.value,
* $A1.key = $A1.value,
* $AN.key = $AN.value,
*/
EnumFieldsWrapper: (contents) =>
_.map(contents, ({ key, value }) => ` ${Ts.EnumField(key, value)}`).join(
",\n"
),
/**
* {\n $A \n}
*/
ObjectWrapper: (content) => `{\n${content}\n}`,
/**
* /** $A *\/
*/
MultilineComment: (contents, formatFn) =>
[
...(contents.length === 1
? [`/** ${contents[0]} */`]
: ["/**", ...contents.map((content) => ` * ${content}`), " */"]),
].map((part) => `${formatFn ? formatFn(part) : part}\n`),
/**
* $A1<...$A2.join(,)>
*/
TypeWithGeneric: (typeName, genericArgs) => {
return `${typeName}${
genericArgs.length ? `<${genericArgs.join(",")}>` : ""
}`;
},
};Swagger schema has constructions like { "type": "string" | "integer" | etc, "format": "date-time" | "float" | "etc" } where field type is not "readable" for TypeScript.
And because of this swagger-typescript-api has key value group to translate swagger schema fields type/format to TypeScript constructions.
See more about swagger schema type/format data here
For example, current version of default configuration translates this schema
{
"type": "string",
"format": "date-time"
}translates to
string;If you need to see Date instead of string you are able to change it with using primitiveTypeConstructs
generateApiForTest({
// ...
primitiveTypeConstructs: (construct) => ({
string: {
"date-time": "Date",
},
}),
});Structure of primitiveTypes property
const primitiveTypes = {
integer: () => Ts.Keyword.Number,
number: () => Ts.Keyword.Number,
boolean: () => Ts.Keyword.Boolean,
object: () => Ts.Keyword.Object,
file: () => Ts.Keyword.File,
string: {
$default: () => Ts.Keyword.String,
/** formats */
binary: () => Ts.Keyword.File,
file: () => Ts.Keyword.File,
"date-time": () => Ts.Keyword.String,
time: () => Ts.Keyword.String,
date: () => Ts.Keyword.String,
duration: () => Ts.Keyword.String,
email: () => Ts.Keyword.String,
"idn-email": () => Ts.Keyword.String,
"idn-hostname": () => Ts.Keyword.String,
ipv4: () => Ts.Keyword.String,
ipv6: () => Ts.Keyword.String,
uuid: () => Ts.Keyword.String,
uri: () => Ts.Keyword.String,
"uri-reference": () => Ts.Keyword.String,
"uri-template": () => Ts.Keyword.String,
"json-pointer": () => Ts.Keyword.String,
"relative-json-pointer": () => Ts.Keyword.String,
regex: () => Ts.Keyword.String,
},
array: ({ items, ...schemaPart }, parser) => {
const content = parser.getInlineParseContent(items);
return parser.safeAddNullToType(schemaPart, Ts.ArrayType(content));
},
};feat: --another-array-type cli option (#414)
fix: path params with dot style (truck.id) (#413)
fix: CRLF -> LF (#423) docs: add docs for addReadonly nodeJS api flag (#425) chore: remove useless trailing whitespaces which make test edit harder (thanks @qboot, #422) internal: add test snapshots (git diff + nodejs assertions) chore: add logging (project version, node version, npm version)
fix: host.fileExists is not a function
fix: other problems linked with new typescript version (4.8.*) (thanks @elkeis, @Jnig)
fix: problem with required nested properties based on root required properties list
fix: fetch http client headers content type priority
fix: fs.rmSync (thanks @smorimoto)
fix: locally overridden security schemes (security flag) (#418, thanks @EdwardSalter)
docs: add documentation for unwrapResponseData nodejs option (thanks @simowe)
BREAKING_CHANGE: rename .eta file extensions to .ejs. Backward capability should be existed.
fix: problem with --sort-types option
fix: problem with default http request headers in axios client
- fix problem linked with this.name is not a function
- [internal] add cli tests
- fix problem with not correct working the
--no-clientoption - separate data-contracts.ejs onto 4 pieces (enum, interface, type, jsdoc)
--extract-response-bodyoption - extract response body type to data contract--extract-response-erroroption - extract response error type to data contract--add-readonlyoption - generate readonly propertiesauthorizationTokenfor axios fetch swagger schema request- fix: change COMPLEX_NOT_OF to COMPLEX_NOT (internal)
- feat: improve
@deprecatedjsdoc info - feat: improve
requiredfield in complex data schemas (anyOf, oneOf, allOf etc) - feat: abortSignal for fetch http client
- chore: improve typings in index.d.ts
- fixed Request falls if FormData attachment is File instance
- fixed Response format - global default or override ?
Co-authored-by: Sergey S. Volkov js2me@outlook.com Co-authored-by: Xavier Cassel 57092100+xcassel@users.noreply.github.com Co-authored-by: cassel xavier.cassel35@gmail.com Co-authored-by: Adrian Wieprzkowicz Argeento@users.noreply.github.com Co-authored-by: EvgenBabenko evgen.babenko@gmail.com Co-authored-by: RoCat catoio.romain@gmail.com Co-authored-by: rcatoio rcatoio@doubletrade.com Co-authored-by: 卡色 cipchk@qq.com Co-authored-by: 江麻妞 50100681+jiangmaniu@users.noreply.github.com Co-authored-by: Kasper Moskwiak kasper.moskwiak@gmail.com Co-authored-by: Ben Watkins ben@outdatedversion.com Co-authored-by: bonukai bonukai@protonmail.com Co-authored-by: baggoedw 92381702+baggoedw@users.noreply.github.com Co-authored-by: Marcus Dunn 51931484+MarcusDunn@users.noreply.github.com Co-authored-by: Daniele De Matteo daniele@kuama.net Co-authored-by: Daniel Playfair Cal daniel.playfair.cal@gmail.com Co-authored-by: Anders Cassidy anders.cassidy@dailypay.com Co-authored-by: Daniel Playfair Cal dcal@atlassian.com
Features:
- full response typing for status code, data and headers. (#272, thanks @rustyconover)
- --unwrap-response-data to unwrap the data item from the response (#268, thanks @laktak)
Fixes:
- fix: formdata in axios template (#277, thanks @tiagoskaneta)
Fixes:
- Bug with --single-http-client and private
httpproperty
Fixes:
- Bug with nested objects in FormData (issue #262, thanks @avlnche64)
Fixes:
- Critical bug linked with
templateRequirein ETA templates - Critical bugs linked with
--type-prefix,--type-suffix
Internal:
- Improve manual testing scripts
Fixes:
- 9.0.1 won't build with tsc when imported (thanks @mastermatt)
Fixes:
- Can't compile 9.0.0 version (thanks @Nihisil )
NOTE: This version is not compatible with previous templates (removed route.request.params, apiConfig.props, apiConfig.generic, apiConfig.description, apiConfig.hasDescription)
Fixes:
- Consider 2xx a successful status (thanks @wyozi)
- GET method query option bug (thanks @rhkdgns95, @SaschaGalley)
silentproperty missed in.d.tsfile (thanks @mastermatt)- axios file upload
formDatatype (thanks @guhyeon) - make property
instanceto public in axios http client (It can be helpful in #226) - variable name "params" doesn't uniq (thanks @mixalbl4-127 )
Features:
--disableProxyoption (thanks @kel666)--extract-request-bodyoption. Allows to extract request body type to data contract- Add TSDoc tag for deprecated route (thanks @wyozi)
- Fixes encoding array query params in
fetchhttp templates (thanks @prog13)
Fixes:
- Wrong working the
formatoption infetchhttp client
Fixes:
- Not working
customFetchError:Failed to execute 'fetch' on 'Window': Illegal invocation
BREAKING_CHANGES:
- remove default
jsonformat of the response type (both foraxiosandfetchhttp clients) (issue #213, thanks @po5i)
Features:
- Allow passing custom fetch function (
fetchhttp client only) - Allow to set global response type format through
HttpClientconstructor Example:
const httpClient = new HttpClient({ format: "json" });
// all request responses will been formatted as jsonFixes:
- Missing
schema.$refin inline enum schemas - Array query param values are serialized with the (non-default) comma separated style (issue #222, thanks @Styn, PR #223)
- TypeScript error "TS6133: 'E' is declared but its value is never read." (
axioshttp client) (issue #220, thanks @pmbednarczyk )
Fixes:
- "securityWorker" is only used if "secure" option is specified on each request (issue #212, thanks @dkamyshov)
NOTE: added global
secureoption foraxioshttp client index.d.tsfile (addrawModelTypes)
BREAKING_CHANGES:
- format
namespacename in--route-typesas camelCase with upper first capitalized letterfoo_bar->FooBar
Fixes:
- Incorrect working the
--route-typesoption with--modularoption (route types should be splitted on files) - Fix critical bug linked with enums with boolean type (thanks @haedaal)
Features:
- Ability to return
falseinonCreateRoutehook, it allow to ignore route - Add output util functions
createFile: (params: {
path: string;
fileName: string;
content: string;
withPrefix?: boolean;
}) => void;
renderTemplate: (
templateContent: string,
data: Record<string, unknown>,
etaOptions?: import("eta/dist/types/config").PartialConfig
) => string;
getTemplate: (params: {
fileName?: string;
name?: string;
path?: string;
}) => string
formatTSContent: (content: string) => Promise<string>;
// ...
generateApi({ /* ... */ }).then(({ createFile, renderTemplate, getTemplate }) => {
// do something
})Fixes:
- Bug with missing
nameproperty in in-path requests parameters - Problem with usage
--route-typeswith--modularoption (mising import data contracts)
Fixes:
- Bug with axios headers (thanks @mutoe)
Features:
onFormatRouteName(routeInfo: RawRouteInfo, templateRouteName: string)hook. Allows to format route name, as you like :)
Fixes:
- Bug with wrong complex types (anyOf, oneOf, allOf) when some child schema contains only description

- Bug with number enums which have
x-enumNames - Problem with not existing
titleproperty ininfo
Minor:
- Improve description for complex types
- Improve description in single api file
Features:
--type-suffixoption. Allows to set suffix for data contract name. (issue #191, thanks @the-ult)--type-prefixoption. Allows to set prefix for data contract name. (issue #191, thanks @the-ult) Examples hereonFormatTypeName(usageTypeName, rawTypeName, schemaType)hook. Allow to format data contract names as you want.
Internal:
- rename and split
checkAndRenameModelName->formatModelName,fixModelName
Fixes:
- missing
generateUnionEnums?: boolean;inindex.d.tsfile (thanks @artsaban) - missing default params to axios http client (
--axios) (issue #192, thanks @Nihisil)
Features:
--module-name-first-tagoption. Splits routes based on the first tag (thanks @jnpoyser)
Fixes:
- Problems with using both
--axiosand--modularoptions together (TS,organizeImportscrashed the codegeneration)
Fixes:
- Problems with
--axiosoption- ignoring
path,format,typepayload properties inrequest()method ofHttpClient
- ignoring
- Missing
formatproperty for requests in--modularoption
Features:
--silentoption. Output only errors to console (default: false)
Fixes:
- Bug with
kebab-casepath params (issue #184, thanks @Mr-sgreen) - Typings for
--jsoption
- Ability to override only one template (issue #166, thanks @Nihisil)
- removed
TPromisetype for--responsesoptions (perf. problem, issue #182, thanks @mixalbl4-127) - breaking changes in
http-client.eta securityWorkernow can returnPromise<RequestParams | void> | RequestParams | void
- template path prefixes
@base,@default,@modular(using in Eta templates,includeFile(), see README.md) --axiosoption for axios http client (issue #142, thanks @msklvsk, @mixalbl4-127 )
- Do not fail if template file does not exist (issue #166, thanks @armsnyder )
Caveat: With this fix it will still error if the overridden template uses
includeFileon a template file that is not overridden
- The contentFormatter for ContentType:Json does not correctly format strings (issue #176, thanks @Styn)
- ContentType.FormData no longer sets the correct boundary (issue #172, thanks @Styn)
- header overwrite in
defaultandmodularAPI templates (issue #171 by @Styn, thanks @emilecantin for PR with fix)
- Ignored
x-nullablefield - Schema type names which starts with number or special characters
- Linter disable rules is not working (issue #164, thanks @Haritaso)
- The HttpResponse type is no longer exported from http-client (issue #161, thanks @Styn)
- Bug with optional nested properties of object schema type (issue #156, thanks @Fabiencdp)
onCreateRouteName(routeNameInfo: RouteNameInfo, rawRouteInfo: RawRouteInfo): RouteNameInfo | voidhook Which allows to customize route name without customizingroute-name.etatemplate- Improved content kinds for request infos
--single-http-clientoption which allows to send HttpClient instance to Api constructor and not to create many count of HttpClient instances with--modularapi (issue #155)
- A bit improve type declaration file (index.d.ts) for this tool
- make exportable
ApiConfiginterface
- clearing
routeNameDuplicatesMapbefore eachparseRoutes()function call - Changed templates:
http-client.etaprocedure-call.etaapi.eta
- Request content types auto substitution
i.e. if request body is form data, then request body content type will be
multipart/form-data - Strange method name (issue #152, thanks @RoXuS)
- Hardcoded Content-Type causes issues with some endpoints (issue #153, thanks @po5i)
- Critical bug with
:paramNamepath params (issue #154)
- Ability to provide custom formatting
fetchresponse "IMAGE"content kind for response\request data objectsRequestParamsRequestHeaderstypes for--route-types(routeTypes: true) option (issue #150, thanks @Fabiencdp )--default-responseoption. Allows to set default type for empty response schema (default:void) (based on issue #14)- Request cancellation support (issue #96, thanks @ApacheEx)
RequestParamstype now have thecancelTokenfieldHttpClientinstance now have theabortRequest(cancelToken)method
- Fully refactored
http-client.etatemplate, make it more flexible and simpler.HttpClient["request"]takes one argument with typeFullRequestParams(previously it takes many count of arguments which was not flexible) - Changed the default response body type from
anytovoid(issue #14)
- Changed templates:
http-client.etaprocedure-call.etaapi.eta
This version works with previous templates.
- Client generation for
Content-Type: application/x-www-form-urlencoded(issue #146, thanks @Larox)
- Changed templates:
http-client.etaprocedure-call.eta
- enum + nullable: true doesn't compute the good type (issue #145, thanks @RoXuS)
- Underscores are omitted from enum keys (issue #108, thanks @eolant)
- CLI silently fails if the directory to put new files in doesn't exist yet (issue #141, thanks @Styn)
- Improved type description
- dependencies update:
"js-yaml": "^4.0.0"("^3.14.1")"make-dir": "^3.1.0""swagger2openapi": "^7.0.5"("^7.0.4")
- Difference in templates:
-
new hook
onCreateRequestParamswhich allows modify request params (--extract-request-paramsoption) before sending it to route info
How to use:generateApi({ // ... your config, hooks: { onCreateRequestParams: (rawType) => { if (Object.keys(rawType.properties).length > 1) return rawType; return rawType; }, }, });
-
response content types (array of string like
application/json,image/png) which allows to customize declaration of request response Exist inprocedure-call.etatemplateit.route.response.contentTypes
- Improve
require()function used in ETA templates (using relative path imports) --clean-outputoption. clean output folder before generate api
- Error:
Unexpected token =(Issue #136, Thanks @jlow-mudbath) - Output folder creation (Issue #137, Thanks @Rinta01) Create output folder if it is not exist
- remove
'prettier-plugin-organize-imports'dependency from package
- issue #134 (Thanks @mrfratello)
- add
require()to templateutilsobject
- add information about contributors
--disableStrictSSLoption for disable strict SSL statement with fetching swagger schema. (Thanks @kel666 for PR with feature request) This option fix problem #114
Unexpected token '.'on v4 (Thanks @savingprivatebryan for issue #111) Replaced all new syntax sugar like?.or??to prev. alternatives for support nodejs 12
Cannot find module 'prettier-plugin-organize-imports'#109
- Migrate from mustache template engine to ETA template engine. (Thanks @Fl0pZz)
- Critical change in
HttpResponsetype (RemoveD | null,E | nullunions)
interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response {
- data: D | null;
+ data: D;
- error: E | null;
+ error: E;
}-
--modularoption. Allows to generate api class per module name. Example: here -
new templates on ETA (enhanced EJS) which can improve your templates! (Thanks @Fl0pZz) ETA extension for Visual Studio Code (thanks @shadowtime2000) Also moved out to templates:
procedure-call.eta(request api method template)route-name.eta(api method name template)route-docs.eta(api method docs template)
No worry about strange syntax it is very simple in usage :)
-
Optional templates feature (Except templates using in
includeFileETAdirective) Now you can store only theETAtemplates which you need to change for yourself. -
--extract-request-paramsoption. Generate path and query request params data contract and modify request payload args Example:
-
Improve
data-contracts.etatemplate. Added more power :) -
Add
extraTemplatesproperty forgenerateApi(). Allows to generate extra files via this tool. -
Add
hooksproperty forgenerateApi()hooks?: Partial<{ onCreateComponent: (component: SchemaComponent) => SchemaComponent | void; onParseSchema: (originalSchema: any, parsedSchema: any) => any | void; onCreateRoute: (routeData: ParsedRoute) => ParsedRoute | void; /** Start point of work this tool (after fetching schema) */ onInit?: <C extends GenerateApiConfiguration["config"]>(configuration: C) => C | void; /** Allows to customize configuration object before sending it to templates. */ onPrepareConfig?: <C extends GenerateApiConfiguration>(currentConfiguration: C) => C | void; }>;
generateApi({ input: "./schema.json", output: "./__generated__", hooks: { onCreateComponent(component) { // do something return component; }, // ... }, });
- Update all dependencies to latest
x-enumNamessupport for enums- Problem of complex types (
oneOf,allOf) withpropertiesfield additionalProperties: trueshould make[key: string]: anyfor object types (Thanks @brookjordan for issue #103)
HttpClientis exportable by default- Improve typings when use
swagger-typescript-apiwith NodeJS (index.d.ts)
- axios vulnerability (#101 issue, thanks @Mvbraathen)
name.includes is not a function(issue #98)
--moduleNameIndexoption. determines which path index should be used for routes separation (Thanks @nikalun) Examples: GET:api/v1/fruites/getFruit -> index:2 -> moduleName -> fruites GET:api/v1/fruites/getFruit -> index:0 -> moduleName -> api
- invalid default templates path (#92, thanks @larrybotha for quick fix)
- Renamed mustache templates:
api.mustache->data-contracts.mustacheclient.mustache->http.client.mustache+api.mustache
- Split the
client.mustachetemplate into two parts:http-client.mustacheandapi.mustache
- Fixed unsafe clone() of Response causing json() hang. (Thanks @Benjamin-Dobell)
--jsCLI option. [feature request]
-
Requests returns
Promise<HttpResponse<Data, Error>>type.HttpResponseit is Fetch.Response wrapper with fieldsdataanderrorExample:const api = new Api(); // const response: HttpResponse<Data, Error> = await api.fruits.getAll(); response.data; // Data (can be null if response.ok is false) response.error; // Error (can be null if response.ok is true)
-
Breaking changes in the
client.mustachetemplate. Needs to update local custom templates.
- Security configuration in methods. When the security definition is in the main configuration of the swagger definition
- Can provide ability to generate from swagger JSON directly not from a file? #69 (Thanks @JennieJi)
- handling
x-omitemptyproperty for definition properties #68 - Additional properties map to empty interfaces (OpenAPI v3) #76
- Pattern fields in Path Item Object are treated as operations #75
- Remove const enum from default template #73
- enums with spaces throw an error #71
- Improve the naming of model types (#65 issue)
--templatesCLI option. [feature request] Provide custommustachetemplates folder which allows to generate custom code (models, Api class, routes)--union-enumsCLI option. [feature request] Allows to generate all enums as union types. For example, schema part:will be converted into:"StringEnum": { "enum": ["String1", "String2", "String3", "String4"], "type": "string" }export type StringEnum = "String1" | "String2" | "String3" | "String4";
- Multiple types for a property in Swagger 2 are not handled correctly (#55 issue)
- Generating invalid code in composed schema contexts (#51 issue)
components: schemas: Test: type: object allOf: - type: object properties: x: type: array items: type: string enum: - A-B - type: object properties: y: type: string
export type Test = XAB & { y?: string };
- Broken types for arrays of union types (issue)
- form data request body (request body content
multipart/form-data)
- inline comments of the data contract type properties

- remove
Array<T>type usage (now the more simple typeT[])
- Partially support FormData body types
- Support to generate query params of nested query objects (Partial fix of this issue)
- Critical bug with converting inline object into name of type for request body.
- Fix bug when path parameters is not set but contains in endpoint url.

- Remove
titleandversionpublic Api class properties (moved it to Api class JSDOC)(fixes this issue)
- Move out all http client handlers/properties into
HttpClientlocal class in module

- default value for
SecurityDataTypeApi class generic type
- Handling of nullable for $ref in OpenAPI 3.0 (issue)
Plus based on this issue was fixed most other problems with using
requiredandnullableproperties
- Nullable not included in type definition (issue)
- Update
swagger2openapi(6.0.0) dependency
- Update
prettier(2.0.2),swagger2openapi(5.4.0) dependencies
- Improvenment in optional request params (request body, query params, path params)
- Fix bug when
pathrequest param have the same name asquery - Fix bug when
pathrequest param have the same name asparams
- changed
addQueryParams()method - up
swagger2openapidependency version to5.3.4
- Fix problem with array
typedefinitions withouttypeproperty(#26)
- Rename default typescript output api file name (prev
api.ts, nowApi.ts) Features: -d, --default-as-successoption. Allows to use "default" status codes as success response type-r, --responsesoption. Response declarations in request rescription This option adds comments of the possible responses from request
Also typings for .catch()callback
- Improve response body type definitions
- Types for bad responses Changes:
- [minor] fix jsdoc comments space

- Api module description from schema info

- Generate API type declarations (CLI flag
--route-types, thanks azz)
- Ability to not generate clint API class (CLI flag
--no-client, thanks azz)
- Improve response body type definition
- refactored
generateandvalidatetest scripts
Fixes: create api without -o option (use default ./ output)
Features: better naming of routes without operationId
Changes: rename @security true -> @secure, @duplicate true -> @duplicate
Fixes: Support generated swagger schemes from tsoa 3.x with complex types (Omit, Pick, etc)
Features: add .d.ts file into npm package Changes: update help block in CLI Internal: add greenkeeper, update npm keywords
Features: @summary, @description comments at each route Fixes: parsing schema without routes Changes: update documentation Internal: add anyOf, allOf test schemas, slack notifications in CI
Fixes: fix complex types (oneOf, anyOf), required fields of object type was not required
Changes: rename ApiParams to RequestParams, secure module always exist in generated API module, update documentation
Fixes: Query params was all required, parse yaml files, typescript minor warnings (;)
Internal: test schemas + manual testing, add travis CI/CD
Fixes: catching http errors with use API module
Features: add description to interfaces and their fields Changes: update documentation
Changes: update documentation
Changes: update documentation (+ add logo), add comment about author in generated module
Fixes: route naming, http(s) requests for getting swagger schema, integer enums Changes: include only required files into npm pacakge
Changes: update documentation
Changes: disable linters rules for generated API module Fixes: TS issues in template
Fixes: NodeJS main script cannot been called on Unix* machines Changes: add LICENSE, update README
Changes(Internal): change dependencies
New features: query params, separating routes on submodules, common params in constructor, swagger v2 + yaml parsers Enhancements: better type extracting. Fixes: mustache escaping chars Changes: order of request params, emojis messages in console
Initial project.


