api-farmer 0.0.17 → 0.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 varletjs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -56,6 +56,16 @@ npx af
56
56
 
57
57
  Some simple usage examples can be found [here](fixtures)
58
58
 
59
+ ### Custom code generation templates
60
+
61
+ Create `api-farmer.ejs` in the project root, which will replace the `preset` template.
62
+ The template format can refer to the preset template listed below:
63
+
64
+ - [Axle](templates/axle.ejs)
65
+ - [Axios](templates/axios.ejs)
66
+
67
+ And see the bottom of the document for template variable definitions.
68
+
59
69
  ### Transformer API
60
70
 
61
71
  You can use the Transformer API to further define template variables, which will override the default transformation rules.
@@ -86,26 +96,18 @@ export default defineConfig({
86
96
  })
87
97
  ```
88
98
 
89
- ### Custom EJS Template
90
-
91
- Create `api-farmer.ejs` in the project root, which will replace the `preset` template.
92
- The template format can refer to the preset template listed below:
93
-
94
- - [Axle](templates/axle.ejs)
95
- - [Axios](templates/axios.ejs)
96
-
97
- See the bottom of the document for template variable definitions.
98
-
99
99
  ### Configuration Options
100
100
 
101
101
  ```ts
102
102
  export interface Config {
103
103
  /**
104
104
  * The path to the OpenAPI/Swagger schema file.
105
+ * @default './schema.json'
105
106
  */
106
107
  input?: string
107
108
  /**
108
109
  * The path to the output directory.
110
+ * @default './src/apis/generated'
109
111
  */
110
112
  output?: string
111
113
  /**
@@ -114,28 +116,38 @@ export interface Config {
114
116
  base?: string
115
117
  /**
116
118
  * The filename of the generated openapi types file.
119
+ * @default '_types.ts'
117
120
  */
118
121
  typesFilename?: string
119
- /**
120
- * The transformer api options, used to override the default transformation rules.
121
- */
122
- transformer?: Partial<Transformer>
123
122
  /**
124
123
  * Whether to generate TypeScript code.
124
+ * @default true
125
125
  */
126
126
  ts?: boolean
127
127
  /**
128
128
  * Whether to generate only types.
129
+ * @default false
129
130
  */
130
131
  typesOnly?: boolean
131
132
  /**
132
133
  * Whether to override the existing files, or an array of filenames to override.
134
+ * @default true
133
135
  */
134
136
  overrides?: boolean | string[]
135
137
  /**
136
138
  * The preset ejs template to use.
139
+ * @default 'axle'
137
140
  */
138
141
  preset?: Preset
142
+ /**
143
+ * Defines which return status codes will be typed
144
+ * @default (status) => status >= 200 && status < 300
145
+ */
146
+ validateStatus?: (status: number) => boolean
147
+ /**
148
+ * The transformer api options, used to override the default transformation rules.
149
+ */
150
+ transformer?: Partial<Transformer>
139
151
  }
140
152
  ```
141
153
 
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  CWD,
3
3
  SUPPORTED_HTTP_METHODS,
4
- getSuccessfulResponseMeme,
4
+ getValidResponseMetadataItems,
5
5
  hasQueryParameter,
6
6
  isRequiredRequestBody,
7
7
  readSchema,
8
8
  readTemplateFile
9
- } from "./chunk-MLHGCJ6R.js";
9
+ } from "./chunk-SKKHIIUE.js";
10
10
  import {
11
11
  __export
12
12
  } from "./chunk-6OIOYGN7.js";
@@ -22803,10 +22803,9 @@ function transformTypeResponseBody({
22803
22803
  }
22804
22804
  function transformTypeResponseBodyValue({
22805
22805
  type: type2,
22806
- statusCode,
22807
- mime
22806
+ responseMetadataItems
22808
22807
  }) {
22809
- return `${type2}['responses']['${statusCode}']['content']['${mime}']`;
22808
+ return responseMetadataItems.map(({ status, mime }) => `${type2}['responses']['${status}']['content']['${mime}']`).join(" | ");
22810
22809
  }
22811
22810
  function createTransformer() {
22812
22811
  return {
@@ -22828,7 +22827,7 @@ function createTransformer() {
22828
22827
 
22829
22828
  // src/generate.ts
22830
22829
  function transformPayloads(pathItems, options8) {
22831
- const { transformer, path: path13, base } = options8;
22830
+ const { transformer, path: path13, base, validateStatus } = options8;
22832
22831
  return Object.entries(pathItems).filter(([key2]) => SUPPORTED_HTTP_METHODS.includes(key2)).reduce((payloads, [method, operation]) => {
22833
22832
  const url2 = transformer.url({ path: path13, base });
22834
22833
  const args = { path: path13, base, url: url2, method, operation };
@@ -22847,9 +22846,9 @@ function transformPayloads(pathItems, options8) {
22847
22846
  entity,
22848
22847
  required: isRequiredRequestBody(operation.requestBody)
22849
22848
  }) : "undefined";
22850
- const { mime, statusCode } = getSuccessfulResponseMeme(operation);
22851
22849
  const typeResponseBody = transformer.typeResponseBody({ ...args, type: type2, verb, entity });
22852
- const typeResponseBodyValue = mime && statusCode ? transformer.typeResponseBodyValue({ ...args, type: type2, verb, entity, statusCode, mime }) : "undefined";
22850
+ const responseMetadataItems = getValidResponseMetadataItems(operation, validateStatus);
22851
+ const typeResponseBodyValue = responseMetadataItems.length > 0 ? transformer.typeResponseBodyValue({ ...args, type: type2, verb, entity, responseMetadataItems }) : "undefined";
22853
22852
  payloads.push({
22854
22853
  fn,
22855
22854
  url: url2,
@@ -22869,14 +22868,16 @@ function transformPayloads(pathItems, options8) {
22869
22868
  }, []);
22870
22869
  }
22871
22870
  function partitionApiModules(schema2, options8) {
22872
- const { base, transformer } = options8;
22871
+ const { base, transformer, validateStatus } = options8;
22873
22872
  const schemaPaths = schema2.paths ?? {};
22874
22873
  const schemaPathKeys = base ? Object.keys(schemaPaths).map((key2) => key2.replace(base, "")) : Object.keys(schemaPaths);
22875
22874
  const keyToPaths = groupBy(schemaPathKeys, (key2) => key2.split("/")[1]);
22876
22875
  const apiModules = Object.entries(keyToPaths).reduce((apiModules2, [name, paths]) => {
22877
22876
  const payloads = paths.reduce((payloads2, path13) => {
22878
22877
  const pathItems = schemaPaths[path13];
22879
- payloads2.push(...transformPayloads(pathItems, { ...options8, path: base ? base + path13 : path13, transformer }));
22878
+ payloads2.push(
22879
+ ...transformPayloads(pathItems, { ...options8, path: base ? base + path13 : path13, transformer, validateStatus })
22880
+ );
22880
22881
  return payloads2;
22881
22882
  }, []);
22882
22883
  apiModules2.push({ name: transformer.moduleName({ name }), payloads });
@@ -22937,6 +22938,7 @@ async function generate(userOptions = {}) {
22937
22938
  input = "./schema.json",
22938
22939
  output = "./src/apis/generated",
22939
22940
  typesFilename = "_types.ts",
22941
+ validateStatus = (status) => status >= 200 && status < 300,
22940
22942
  transformer = {}
22941
22943
  } = options8;
22942
22944
  const mergedTransformer = { ...createTransformer(), ...transformer };
@@ -22947,7 +22949,8 @@ async function generate(userOptions = {}) {
22947
22949
  }
22948
22950
  const apiModules = partitionApiModules(schema2, {
22949
22951
  base,
22950
- transformer: mergedTransformer
22952
+ transformer: mergedTransformer,
22953
+ validateStatus
22951
22954
  });
22952
22955
  await renderApiModules(apiModules, { output, typesFilename, ts, typesOnly, overrides, preset });
22953
22956
  logger.success("Done");
@@ -68,22 +68,18 @@ function getCliVersion() {
68
68
  function isRequiredRequestBody(value) {
69
69
  return "required" in value && value.required === true;
70
70
  }
71
- function getSuccessfulResponseMeme(operation) {
71
+ function getValidResponseMetadataItems(operation, validateStatus) {
72
72
  const responses = operation.responses ?? {};
73
- const codeKey = Object.keys(responses).sort((a, b) => Number(a) - Number(b)).find((codeKey2) => Number(codeKey2) >= 200 && Number(codeKey2) <= 299);
74
- if (!codeKey) {
73
+ const validStatusResults = Object.keys(responses).sort((a, b) => Number(a) - Number(b)).filter((key) => validateStatus(Number(key))).map(Number);
74
+ const results = validStatusResults.map((status) => {
75
+ const content = operation.responses?.[status]?.content;
76
+ const mime = content?.["application/json"] ? "application/json" : content?.["*/*"] ? "*/*" : void 0;
75
77
  return {
76
- statusCode: void 0,
77
- mime: void 0
78
+ status,
79
+ mime
78
80
  };
79
- }
80
- const statusCode = Number(codeKey);
81
- const content = operation.responses?.[statusCode]?.content;
82
- const mime = content?.["application/json"] ? "application/json" : content?.["*/*"] ? "*/*" : void 0;
83
- return {
84
- statusCode,
85
- mime
86
- };
81
+ }).filter((result) => result.mime);
82
+ return results;
87
83
  }
88
84
 
89
85
  export {
@@ -95,5 +91,5 @@ export {
95
91
  hasQueryParameter,
96
92
  getCliVersion,
97
93
  isRequiredRequestBody,
98
- getSuccessfulResponseMeme
94
+ getValidResponseMetadataItems
99
95
  };
package/dist/cli.cjs CHANGED
@@ -78,22 +78,18 @@ function getCliVersion() {
78
78
  function isRequiredRequestBody(value) {
79
79
  return "required" in value && value.required === true;
80
80
  }
81
- function getSuccessfulResponseMeme(operation) {
81
+ function getValidResponseMetadataItems(operation, validateStatus) {
82
82
  const responses = operation.responses ?? {};
83
- const codeKey = Object.keys(responses).sort((a5, b8) => Number(a5) - Number(b8)).find((codeKey2) => Number(codeKey2) >= 200 && Number(codeKey2) <= 299);
84
- if (!codeKey) {
83
+ const validStatusResults = Object.keys(responses).sort((a5, b8) => Number(a5) - Number(b8)).filter((key2) => validateStatus(Number(key2))).map(Number);
84
+ const results = validStatusResults.map((status) => {
85
+ const content = operation.responses?.[status]?.content;
86
+ const mime = content?.["application/json"] ? "application/json" : content?.["*/*"] ? "*/*" : void 0;
85
87
  return {
86
- statusCode: void 0,
87
- mime: void 0
88
+ status,
89
+ mime
88
90
  };
89
- }
90
- const statusCode = Number(codeKey);
91
- const content = operation.responses?.[statusCode]?.content;
92
- const mime = content?.["application/json"] ? "application/json" : content?.["*/*"] ? "*/*" : void 0;
93
- return {
94
- statusCode,
95
- mime
96
- };
91
+ }).filter((result) => result.mime);
92
+ return results;
97
93
  }
98
94
  var import_path2, import_fs_extra, import_swagger2openapi, import_yaml;
99
95
  var init_utils = __esm({
@@ -102055,10 +102051,9 @@ function transformTypeResponseBody({
102055
102051
  }
102056
102052
  function transformTypeResponseBodyValue({
102057
102053
  type: type2,
102058
- statusCode,
102059
- mime
102054
+ responseMetadataItems
102060
102055
  }) {
102061
- return `${type2}['responses']['${statusCode}']['content']['${mime}']`;
102056
+ return responseMetadataItems.map(({ status, mime }) => `${type2}['responses']['${status}']['content']['${mime}']`).join(" | ");
102062
102057
  }
102063
102058
  function createTransformer() {
102064
102059
  return {
@@ -102097,7 +102092,7 @@ __export(generate_exports, {
102097
102092
  transformPayloads: () => transformPayloads
102098
102093
  });
102099
102094
  function transformPayloads(pathItems, options8) {
102100
- const { transformer, path: path13, base } = options8;
102095
+ const { transformer, path: path13, base, validateStatus } = options8;
102101
102096
  return Object.entries(pathItems).filter(([key2]) => SUPPORTED_HTTP_METHODS.includes(key2)).reduce((payloads, [method, operation]) => {
102102
102097
  const url2 = transformer.url({ path: path13, base });
102103
102098
  const args = { path: path13, base, url: url2, method, operation };
@@ -102116,9 +102111,9 @@ function transformPayloads(pathItems, options8) {
102116
102111
  entity,
102117
102112
  required: isRequiredRequestBody(operation.requestBody)
102118
102113
  }) : "undefined";
102119
- const { mime, statusCode } = getSuccessfulResponseMeme(operation);
102120
102114
  const typeResponseBody = transformer.typeResponseBody({ ...args, type: type2, verb, entity });
102121
- const typeResponseBodyValue = mime && statusCode ? transformer.typeResponseBodyValue({ ...args, type: type2, verb, entity, statusCode, mime }) : "undefined";
102115
+ const responseMetadataItems = getValidResponseMetadataItems(operation, validateStatus);
102116
+ const typeResponseBodyValue = responseMetadataItems.length > 0 ? transformer.typeResponseBodyValue({ ...args, type: type2, verb, entity, responseMetadataItems }) : "undefined";
102122
102117
  payloads.push({
102123
102118
  fn: fn8,
102124
102119
  url: url2,
@@ -102138,14 +102133,16 @@ function transformPayloads(pathItems, options8) {
102138
102133
  }, []);
102139
102134
  }
102140
102135
  function partitionApiModules(schema2, options8) {
102141
- const { base, transformer } = options8;
102136
+ const { base, transformer, validateStatus } = options8;
102142
102137
  const schemaPaths = schema2.paths ?? {};
102143
102138
  const schemaPathKeys = base ? Object.keys(schemaPaths).map((key2) => key2.replace(base, "")) : Object.keys(schemaPaths);
102144
102139
  const keyToPaths = (0, import_rattail2.groupBy)(schemaPathKeys, (key2) => key2.split("/")[1]);
102145
102140
  const apiModules = Object.entries(keyToPaths).reduce((apiModules2, [name, paths]) => {
102146
102141
  const payloads = paths.reduce((payloads2, path13) => {
102147
102142
  const pathItems = schemaPaths[path13];
102148
- payloads2.push(...transformPayloads(pathItems, { ...options8, path: base ? base + path13 : path13, transformer }));
102143
+ payloads2.push(
102144
+ ...transformPayloads(pathItems, { ...options8, path: base ? base + path13 : path13, transformer, validateStatus })
102145
+ );
102149
102146
  return payloads2;
102150
102147
  }, []);
102151
102148
  apiModules2.push({ name: transformer.moduleName({ name }), payloads });
@@ -102206,6 +102203,7 @@ async function generate(userOptions = {}) {
102206
102203
  input = "./schema.json",
102207
102204
  output = "./src/apis/generated",
102208
102205
  typesFilename = "_types.ts",
102206
+ validateStatus = (status) => status >= 200 && status < 300,
102209
102207
  transformer = {}
102210
102208
  } = options8;
102211
102209
  const mergedTransformer = { ...createTransformer(), ...transformer };
@@ -102216,7 +102214,8 @@ async function generate(userOptions = {}) {
102216
102214
  }
102217
102215
  const apiModules = partitionApiModules(schema2, {
102218
102216
  base,
102219
- transformer: mergedTransformer
102217
+ transformer: mergedTransformer,
102218
+ validateStatus
102220
102219
  });
102221
102220
  await renderApiModules(apiModules, { output, typesFilename, ts: ts9, typesOnly, overrides, preset });
102222
102221
  import_rslog.logger.success("Done");
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  getCliVersion
4
- } from "./chunk-MLHGCJ6R.js";
4
+ } from "./chunk-SKKHIIUE.js";
5
5
  import "./chunk-6OIOYGN7.js";
6
6
 
7
7
  // src/cli.ts
@@ -9,7 +9,7 @@ import { Command } from "commander";
9
9
  var program = new Command();
10
10
  program.version(getCliVersion());
11
11
  program.action(async () => {
12
- const { generate } = await import("./generate-7X5RRT3J.js");
12
+ const { generate } = await import("./generate-IJGTBA2I.js");
13
13
  return generate();
14
14
  });
15
15
  program.parse();
@@ -4,8 +4,8 @@ import {
4
4
  partitionApiModules,
5
5
  renderApiModules,
6
6
  transformPayloads
7
- } from "./chunk-J2G2MBMU.js";
8
- import "./chunk-MLHGCJ6R.js";
7
+ } from "./chunk-K46PCBCF.js";
8
+ import "./chunk-SKKHIIUE.js";
9
9
  import "./chunk-6OIOYGN7.js";
10
10
  export {
11
11
  generate,
package/dist/index.cjs CHANGED
@@ -79232,7 +79232,7 @@ __export(index_exports, {
79232
79232
  generateTypes: () => generateTypes,
79233
79233
  getCliVersion: () => getCliVersion,
79234
79234
  getConfig: () => getConfig,
79235
- getSuccessfulResponseMeme: () => getSuccessfulResponseMeme,
79235
+ getValidResponseMetadataItems: () => getValidResponseMetadataItems,
79236
79236
  hasQueryParameter: () => hasQueryParameter,
79237
79237
  isRequiredRequestBody: () => isRequiredRequestBody,
79238
79238
  partitionApiModules: () => partitionApiModules,
@@ -79328,10 +79328,9 @@ function transformTypeResponseBody({
79328
79328
  }
79329
79329
  function transformTypeResponseBodyValue({
79330
79330
  type: type2,
79331
- statusCode,
79332
- mime
79331
+ responseMetadataItems
79333
79332
  }) {
79334
- return `${type2}['responses']['${statusCode}']['content']['${mime}']`;
79333
+ return responseMetadataItems.map(({ status, mime }) => `${type2}['responses']['${status}']['content']['${mime}']`).join(" | ");
79335
79334
  }
79336
79335
  function createTransformer() {
79337
79336
  return {
@@ -102146,27 +102145,23 @@ function getCliVersion() {
102146
102145
  function isRequiredRequestBody(value) {
102147
102146
  return "required" in value && value.required === true;
102148
102147
  }
102149
- function getSuccessfulResponseMeme(operation) {
102148
+ function getValidResponseMetadataItems(operation, validateStatus) {
102150
102149
  const responses = operation.responses ?? {};
102151
- const codeKey = Object.keys(responses).sort((a5, b8) => Number(a5) - Number(b8)).find((codeKey2) => Number(codeKey2) >= 200 && Number(codeKey2) <= 299);
102152
- if (!codeKey) {
102150
+ const validStatusResults = Object.keys(responses).sort((a5, b8) => Number(a5) - Number(b8)).filter((key2) => validateStatus(Number(key2))).map(Number);
102151
+ const results = validStatusResults.map((status) => {
102152
+ const content = operation.responses?.[status]?.content;
102153
+ const mime = content?.["application/json"] ? "application/json" : content?.["*/*"] ? "*/*" : void 0;
102153
102154
  return {
102154
- statusCode: void 0,
102155
- mime: void 0
102155
+ status,
102156
+ mime
102156
102157
  };
102157
- }
102158
- const statusCode = Number(codeKey);
102159
- const content = operation.responses?.[statusCode]?.content;
102160
- const mime = content?.["application/json"] ? "application/json" : content?.["*/*"] ? "*/*" : void 0;
102161
- return {
102162
- statusCode,
102163
- mime
102164
- };
102158
+ }).filter((result) => result.mime);
102159
+ return results;
102165
102160
  }
102166
102161
 
102167
102162
  // src/generate.ts
102168
102163
  function transformPayloads(pathItems, options8) {
102169
- const { transformer, path: path13, base } = options8;
102164
+ const { transformer, path: path13, base, validateStatus } = options8;
102170
102165
  return Object.entries(pathItems).filter(([key2]) => SUPPORTED_HTTP_METHODS.includes(key2)).reduce((payloads, [method, operation]) => {
102171
102166
  const url2 = transformer.url({ path: path13, base });
102172
102167
  const args = { path: path13, base, url: url2, method, operation };
@@ -102185,9 +102180,9 @@ function transformPayloads(pathItems, options8) {
102185
102180
  entity,
102186
102181
  required: isRequiredRequestBody(operation.requestBody)
102187
102182
  }) : "undefined";
102188
- const { mime, statusCode } = getSuccessfulResponseMeme(operation);
102189
102183
  const typeResponseBody = transformer.typeResponseBody({ ...args, type: type2, verb, entity });
102190
- const typeResponseBodyValue = mime && statusCode ? transformer.typeResponseBodyValue({ ...args, type: type2, verb, entity, statusCode, mime }) : "undefined";
102184
+ const responseMetadataItems = getValidResponseMetadataItems(operation, validateStatus);
102185
+ const typeResponseBodyValue = responseMetadataItems.length > 0 ? transformer.typeResponseBodyValue({ ...args, type: type2, verb, entity, responseMetadataItems }) : "undefined";
102191
102186
  payloads.push({
102192
102187
  fn: fn8,
102193
102188
  url: url2,
@@ -102207,14 +102202,16 @@ function transformPayloads(pathItems, options8) {
102207
102202
  }, []);
102208
102203
  }
102209
102204
  function partitionApiModules(schema2, options8) {
102210
- const { base, transformer } = options8;
102205
+ const { base, transformer, validateStatus } = options8;
102211
102206
  const schemaPaths = schema2.paths ?? {};
102212
102207
  const schemaPathKeys = base ? Object.keys(schemaPaths).map((key2) => key2.replace(base, "")) : Object.keys(schemaPaths);
102213
102208
  const keyToPaths = (0, import_rattail2.groupBy)(schemaPathKeys, (key2) => key2.split("/")[1]);
102214
102209
  const apiModules = Object.entries(keyToPaths).reduce((apiModules2, [name, paths]) => {
102215
102210
  const payloads = paths.reduce((payloads2, path13) => {
102216
102211
  const pathItems = schemaPaths[path13];
102217
- payloads2.push(...transformPayloads(pathItems, { ...options8, path: base ? base + path13 : path13, transformer }));
102212
+ payloads2.push(
102213
+ ...transformPayloads(pathItems, { ...options8, path: base ? base + path13 : path13, transformer, validateStatus })
102214
+ );
102218
102215
  return payloads2;
102219
102216
  }, []);
102220
102217
  apiModules2.push({ name: transformer.moduleName({ name }), payloads });
@@ -102275,6 +102272,7 @@ async function generate(userOptions = {}) {
102275
102272
  input = "./schema.json",
102276
102273
  output = "./src/apis/generated",
102277
102274
  typesFilename = "_types.ts",
102275
+ validateStatus = (status) => status >= 200 && status < 300,
102278
102276
  transformer = {}
102279
102277
  } = options8;
102280
102278
  const mergedTransformer = { ...createTransformer(), ...transformer };
@@ -102285,7 +102283,8 @@ async function generate(userOptions = {}) {
102285
102283
  }
102286
102284
  const apiModules = partitionApiModules(schema2, {
102287
102285
  base,
102288
- transformer: mergedTransformer
102286
+ transformer: mergedTransformer,
102287
+ validateStatus
102289
102288
  });
102290
102289
  await renderApiModules(apiModules, { output, typesFilename, ts: ts9, typesOnly, overrides, preset });
102291
102290
  import_rslog.logger.success("Done");
@@ -102302,7 +102301,7 @@ var import_pluralize2 = __toESM(require("pluralize"), 1);
102302
102301
  generateTypes,
102303
102302
  getCliVersion,
102304
102303
  getConfig,
102305
- getSuccessfulResponseMeme,
102304
+ getValidResponseMetadataItems,
102306
102305
  hasQueryParameter,
102307
102306
  isRequiredRequestBody,
102308
102307
  partitionApiModules,
package/dist/index.d.cts CHANGED
@@ -1,6 +1,53 @@
1
- import { OperationObject, OpenAPI3, RequestBodyObject, ReferenceObject } from 'openapi-typescript';
1
+ import { OpenAPI3, OperationObject, RequestBodyObject, ReferenceObject } from 'openapi-typescript';
2
2
  export { default as pluralize } from 'pluralize';
3
3
 
4
+ type Preset = 'axle' | 'axios';
5
+ type StatusCodeStrategy = 'strict' | 'loose' | 'smart';
6
+ interface StatusCodes {
7
+ get?: number;
8
+ post?: number;
9
+ put?: number;
10
+ delete?: number;
11
+ patch?: number;
12
+ options?: number;
13
+ head?: number;
14
+ }
15
+ declare function createStatusCodesByStrategy(strategy: StatusCodeStrategy): {
16
+ get: number;
17
+ post: number;
18
+ put: number;
19
+ delete: number;
20
+ patch: number;
21
+ options: number;
22
+ head: number;
23
+ } | {
24
+ get: number;
25
+ post: number;
26
+ put: number;
27
+ delete: number;
28
+ patch: number;
29
+ options: number;
30
+ head: number;
31
+ } | {
32
+ get: number;
33
+ post: number;
34
+ put: number;
35
+ delete: number;
36
+ patch: number;
37
+ options: number;
38
+ head: number;
39
+ };
40
+ declare function readSchema(input: string): Promise<OpenAPI3>;
41
+ declare function readTemplateFile(preset?: Preset): string;
42
+ declare function hasQueryParameter(operation: OperationObject): boolean;
43
+ declare function getCliVersion(): any;
44
+ declare function isRequiredRequestBody(value: RequestBodyObject | ReferenceObject): boolean;
45
+ type ResponseMetadataItem = {
46
+ status: number;
47
+ mime: string;
48
+ };
49
+ declare function getValidResponseMetadataItems(operation: OperationObject, validateStatus: (status: number) => boolean): ResponseMetadataItem[];
50
+
4
51
  type TransformerBaseArgs = {
5
52
  path: string;
6
53
  base: string | undefined;
@@ -57,12 +104,11 @@ declare function transformTypeResponseBody({ type, }: {
57
104
  verb: string;
58
105
  entity: string;
59
106
  } & TransformerBaseArgs): string;
60
- declare function transformTypeResponseBodyValue({ type, statusCode, mime, }: {
107
+ declare function transformTypeResponseBodyValue({ type, responseMetadataItems, }: {
61
108
  type: string;
62
109
  verb: string;
63
110
  entity: string;
64
- statusCode: number;
65
- mime: string;
111
+ responseMetadataItems: ResponseMetadataItem[];
66
112
  } & TransformerBaseArgs): string;
67
113
  interface Transformer {
68
114
  moduleName: typeof transformModuleName;
@@ -81,55 +127,6 @@ interface Transformer {
81
127
  }
82
128
  declare function createTransformer(): Transformer;
83
129
 
84
- type Preset = 'axle' | 'axios';
85
- type StatusCodeStrategy = 'strict' | 'loose' | 'smart';
86
- interface StatusCodes {
87
- get?: number;
88
- post?: number;
89
- put?: number;
90
- delete?: number;
91
- patch?: number;
92
- options?: number;
93
- head?: number;
94
- }
95
- declare function createStatusCodesByStrategy(strategy: StatusCodeStrategy): {
96
- get: number;
97
- post: number;
98
- put: number;
99
- delete: number;
100
- patch: number;
101
- options: number;
102
- head: number;
103
- } | {
104
- get: number;
105
- post: number;
106
- put: number;
107
- delete: number;
108
- patch: number;
109
- options: number;
110
- head: number;
111
- } | {
112
- get: number;
113
- post: number;
114
- put: number;
115
- delete: number;
116
- patch: number;
117
- options: number;
118
- head: number;
119
- };
120
- declare function readSchema(input: string): Promise<OpenAPI3>;
121
- declare function readTemplateFile(preset?: Preset): string;
122
- declare function hasQueryParameter(operation: OperationObject): boolean;
123
- declare function getCliVersion(): any;
124
- declare function isRequiredRequestBody(value: RequestBodyObject | ReferenceObject): boolean;
125
- declare function getSuccessfulResponseMeme(operation: OperationObject): {
126
- statusCode: undefined;
127
- mime: undefined;
128
- } | {
129
- statusCode: number;
130
- mime: string | undefined;
131
- };
132
-
133
130
  interface ApiModuleTemplateData {
134
131
  /**
135
132
  * API module metadata
@@ -215,10 +212,12 @@ interface ApiModulePayload {
215
212
  interface GenerateOptions {
216
213
  /**
217
214
  * The path to the OpenAPI/Swagger schema file.
215
+ * @default './schema.json'
218
216
  */
219
217
  input?: string;
220
218
  /**
221
219
  * The path to the output directory.
220
+ * @default './src/apis/generated'
222
221
  */
223
222
  output?: string;
224
223
  /**
@@ -227,37 +226,49 @@ interface GenerateOptions {
227
226
  base?: string;
228
227
  /**
229
228
  * The filename of the generated openapi types file.
229
+ * @default '_types.ts'
230
230
  */
231
231
  typesFilename?: string;
232
- /**
233
- * The transformer api options, used to override the default transformation rules.
234
- */
235
- transformer?: Partial<Transformer>;
236
232
  /**
237
233
  * Whether to generate TypeScript code.
234
+ * @default true
238
235
  */
239
236
  ts?: boolean;
240
237
  /**
241
238
  * Whether to generate only types.
239
+ * @default false
242
240
  */
243
241
  typesOnly?: boolean;
244
242
  /**
245
243
  * Whether to override the existing files, or an array of filenames to override.
244
+ * @default true
246
245
  */
247
246
  overrides?: boolean | string[];
248
247
  /**
249
248
  * The preset ejs template to use.
249
+ * @default 'axle'
250
250
  */
251
251
  preset?: Preset;
252
+ /**
253
+ * Defines which return status codes will be typed
254
+ * @default (status) => status >= 200 && status < 300
255
+ */
256
+ validateStatus?: (status: number) => boolean;
257
+ /**
258
+ * The transformer api options, used to override the default transformation rules.
259
+ */
260
+ transformer?: Partial<Transformer>;
252
261
  }
253
262
  declare function transformPayloads(pathItems: Record<string, OperationObject>, options: {
254
263
  path: string;
255
264
  transformer: Transformer;
256
265
  base: string | undefined;
266
+ validateStatus: (status: number) => boolean;
257
267
  }): ApiModulePayload[];
258
268
  declare function partitionApiModules(schema: OpenAPI3, options: {
259
269
  transformer: Transformer;
260
270
  base: string | undefined;
271
+ validateStatus: (status: number) => boolean;
261
272
  }): ApiModule[];
262
273
  declare function renderApiModules(apiModules: ApiModule[], options: {
263
274
  output: string;
@@ -274,4 +285,4 @@ type Config = GenerateOptions;
274
285
  declare function defineConfig(config: Config): GenerateOptions;
275
286
  declare function getConfig(): Promise<Config>;
276
287
 
277
- export { type ApiModule, type ApiModulePayload, type ApiModuleTemplateData, type Config, type GenerateOptions, type Preset, type StatusCodeStrategy, type StatusCodes, type Transformer, type TransformerBaseArgs, createStatusCodesByStrategy, createTransformer, defineConfig, generate, generateTypes, getCliVersion, getConfig, getSuccessfulResponseMeme, hasQueryParameter, isRequiredRequestBody, partitionApiModules, readSchema, readTemplateFile, renderApiModules, transformEntity, transformFn, transformModuleName, transformPayloads, transformType, transformTypeQuery, transformTypeQueryValue, transformTypeRequestBody, transformTypeRequestBodyValue, transformTypeResponseBody, transformTypeResponseBodyValue, transformTypeValue, transformUrl, transformVerb };
288
+ export { type ApiModule, type ApiModulePayload, type ApiModuleTemplateData, type Config, type GenerateOptions, type Preset, type ResponseMetadataItem, type StatusCodeStrategy, type StatusCodes, type Transformer, type TransformerBaseArgs, createStatusCodesByStrategy, createTransformer, defineConfig, generate, generateTypes, getCliVersion, getConfig, getValidResponseMetadataItems, hasQueryParameter, isRequiredRequestBody, partitionApiModules, readSchema, readTemplateFile, renderApiModules, transformEntity, transformFn, transformModuleName, transformPayloads, transformType, transformTypeQuery, transformTypeQueryValue, transformTypeRequestBody, transformTypeRequestBodyValue, transformTypeResponseBody, transformTypeResponseBodyValue, transformTypeValue, transformUrl, transformVerb };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,53 @@
1
- import { OperationObject, OpenAPI3, RequestBodyObject, ReferenceObject } from 'openapi-typescript';
1
+ import { OpenAPI3, OperationObject, RequestBodyObject, ReferenceObject } from 'openapi-typescript';
2
2
  export { default as pluralize } from 'pluralize';
3
3
 
4
+ type Preset = 'axle' | 'axios';
5
+ type StatusCodeStrategy = 'strict' | 'loose' | 'smart';
6
+ interface StatusCodes {
7
+ get?: number;
8
+ post?: number;
9
+ put?: number;
10
+ delete?: number;
11
+ patch?: number;
12
+ options?: number;
13
+ head?: number;
14
+ }
15
+ declare function createStatusCodesByStrategy(strategy: StatusCodeStrategy): {
16
+ get: number;
17
+ post: number;
18
+ put: number;
19
+ delete: number;
20
+ patch: number;
21
+ options: number;
22
+ head: number;
23
+ } | {
24
+ get: number;
25
+ post: number;
26
+ put: number;
27
+ delete: number;
28
+ patch: number;
29
+ options: number;
30
+ head: number;
31
+ } | {
32
+ get: number;
33
+ post: number;
34
+ put: number;
35
+ delete: number;
36
+ patch: number;
37
+ options: number;
38
+ head: number;
39
+ };
40
+ declare function readSchema(input: string): Promise<OpenAPI3>;
41
+ declare function readTemplateFile(preset?: Preset): string;
42
+ declare function hasQueryParameter(operation: OperationObject): boolean;
43
+ declare function getCliVersion(): any;
44
+ declare function isRequiredRequestBody(value: RequestBodyObject | ReferenceObject): boolean;
45
+ type ResponseMetadataItem = {
46
+ status: number;
47
+ mime: string;
48
+ };
49
+ declare function getValidResponseMetadataItems(operation: OperationObject, validateStatus: (status: number) => boolean): ResponseMetadataItem[];
50
+
4
51
  type TransformerBaseArgs = {
5
52
  path: string;
6
53
  base: string | undefined;
@@ -57,12 +104,11 @@ declare function transformTypeResponseBody({ type, }: {
57
104
  verb: string;
58
105
  entity: string;
59
106
  } & TransformerBaseArgs): string;
60
- declare function transformTypeResponseBodyValue({ type, statusCode, mime, }: {
107
+ declare function transformTypeResponseBodyValue({ type, responseMetadataItems, }: {
61
108
  type: string;
62
109
  verb: string;
63
110
  entity: string;
64
- statusCode: number;
65
- mime: string;
111
+ responseMetadataItems: ResponseMetadataItem[];
66
112
  } & TransformerBaseArgs): string;
67
113
  interface Transformer {
68
114
  moduleName: typeof transformModuleName;
@@ -81,55 +127,6 @@ interface Transformer {
81
127
  }
82
128
  declare function createTransformer(): Transformer;
83
129
 
84
- type Preset = 'axle' | 'axios';
85
- type StatusCodeStrategy = 'strict' | 'loose' | 'smart';
86
- interface StatusCodes {
87
- get?: number;
88
- post?: number;
89
- put?: number;
90
- delete?: number;
91
- patch?: number;
92
- options?: number;
93
- head?: number;
94
- }
95
- declare function createStatusCodesByStrategy(strategy: StatusCodeStrategy): {
96
- get: number;
97
- post: number;
98
- put: number;
99
- delete: number;
100
- patch: number;
101
- options: number;
102
- head: number;
103
- } | {
104
- get: number;
105
- post: number;
106
- put: number;
107
- delete: number;
108
- patch: number;
109
- options: number;
110
- head: number;
111
- } | {
112
- get: number;
113
- post: number;
114
- put: number;
115
- delete: number;
116
- patch: number;
117
- options: number;
118
- head: number;
119
- };
120
- declare function readSchema(input: string): Promise<OpenAPI3>;
121
- declare function readTemplateFile(preset?: Preset): string;
122
- declare function hasQueryParameter(operation: OperationObject): boolean;
123
- declare function getCliVersion(): any;
124
- declare function isRequiredRequestBody(value: RequestBodyObject | ReferenceObject): boolean;
125
- declare function getSuccessfulResponseMeme(operation: OperationObject): {
126
- statusCode: undefined;
127
- mime: undefined;
128
- } | {
129
- statusCode: number;
130
- mime: string | undefined;
131
- };
132
-
133
130
  interface ApiModuleTemplateData {
134
131
  /**
135
132
  * API module metadata
@@ -215,10 +212,12 @@ interface ApiModulePayload {
215
212
  interface GenerateOptions {
216
213
  /**
217
214
  * The path to the OpenAPI/Swagger schema file.
215
+ * @default './schema.json'
218
216
  */
219
217
  input?: string;
220
218
  /**
221
219
  * The path to the output directory.
220
+ * @default './src/apis/generated'
222
221
  */
223
222
  output?: string;
224
223
  /**
@@ -227,37 +226,49 @@ interface GenerateOptions {
227
226
  base?: string;
228
227
  /**
229
228
  * The filename of the generated openapi types file.
229
+ * @default '_types.ts'
230
230
  */
231
231
  typesFilename?: string;
232
- /**
233
- * The transformer api options, used to override the default transformation rules.
234
- */
235
- transformer?: Partial<Transformer>;
236
232
  /**
237
233
  * Whether to generate TypeScript code.
234
+ * @default true
238
235
  */
239
236
  ts?: boolean;
240
237
  /**
241
238
  * Whether to generate only types.
239
+ * @default false
242
240
  */
243
241
  typesOnly?: boolean;
244
242
  /**
245
243
  * Whether to override the existing files, or an array of filenames to override.
244
+ * @default true
246
245
  */
247
246
  overrides?: boolean | string[];
248
247
  /**
249
248
  * The preset ejs template to use.
249
+ * @default 'axle'
250
250
  */
251
251
  preset?: Preset;
252
+ /**
253
+ * Defines which return status codes will be typed
254
+ * @default (status) => status >= 200 && status < 300
255
+ */
256
+ validateStatus?: (status: number) => boolean;
257
+ /**
258
+ * The transformer api options, used to override the default transformation rules.
259
+ */
260
+ transformer?: Partial<Transformer>;
252
261
  }
253
262
  declare function transformPayloads(pathItems: Record<string, OperationObject>, options: {
254
263
  path: string;
255
264
  transformer: Transformer;
256
265
  base: string | undefined;
266
+ validateStatus: (status: number) => boolean;
257
267
  }): ApiModulePayload[];
258
268
  declare function partitionApiModules(schema: OpenAPI3, options: {
259
269
  transformer: Transformer;
260
270
  base: string | undefined;
271
+ validateStatus: (status: number) => boolean;
261
272
  }): ApiModule[];
262
273
  declare function renderApiModules(apiModules: ApiModule[], options: {
263
274
  output: string;
@@ -274,4 +285,4 @@ type Config = GenerateOptions;
274
285
  declare function defineConfig(config: Config): GenerateOptions;
275
286
  declare function getConfig(): Promise<Config>;
276
287
 
277
- export { type ApiModule, type ApiModulePayload, type ApiModuleTemplateData, type Config, type GenerateOptions, type Preset, type StatusCodeStrategy, type StatusCodes, type Transformer, type TransformerBaseArgs, createStatusCodesByStrategy, createTransformer, defineConfig, generate, generateTypes, getCliVersion, getConfig, getSuccessfulResponseMeme, hasQueryParameter, isRequiredRequestBody, partitionApiModules, readSchema, readTemplateFile, renderApiModules, transformEntity, transformFn, transformModuleName, transformPayloads, transformType, transformTypeQuery, transformTypeQueryValue, transformTypeRequestBody, transformTypeRequestBodyValue, transformTypeResponseBody, transformTypeResponseBodyValue, transformTypeValue, transformUrl, transformVerb };
288
+ export { type ApiModule, type ApiModulePayload, type ApiModuleTemplateData, type Config, type GenerateOptions, type Preset, type ResponseMetadataItem, type StatusCodeStrategy, type StatusCodes, type Transformer, type TransformerBaseArgs, createStatusCodesByStrategy, createTransformer, defineConfig, generate, generateTypes, getCliVersion, getConfig, getValidResponseMetadataItems, hasQueryParameter, isRequiredRequestBody, partitionApiModules, readSchema, readTemplateFile, renderApiModules, transformEntity, transformFn, transformModuleName, transformPayloads, transformType, transformTypeQuery, transformTypeQueryValue, transformTypeRequestBody, transformTypeRequestBodyValue, transformTypeResponseBody, transformTypeResponseBodyValue, transformTypeValue, transformUrl, transformVerb };
package/dist/index.js CHANGED
@@ -20,16 +20,16 @@ import {
20
20
  transformTypeValue,
21
21
  transformUrl,
22
22
  transformVerb
23
- } from "./chunk-J2G2MBMU.js";
23
+ } from "./chunk-K46PCBCF.js";
24
24
  import {
25
25
  createStatusCodesByStrategy,
26
26
  getCliVersion,
27
- getSuccessfulResponseMeme,
27
+ getValidResponseMetadataItems,
28
28
  hasQueryParameter,
29
29
  isRequiredRequestBody,
30
30
  readSchema,
31
31
  readTemplateFile
32
- } from "./chunk-MLHGCJ6R.js";
32
+ } from "./chunk-SKKHIIUE.js";
33
33
  import "./chunk-6OIOYGN7.js";
34
34
 
35
35
  // src/index.ts
@@ -42,7 +42,7 @@ export {
42
42
  generateTypes,
43
43
  getCliVersion,
44
44
  getConfig,
45
- getSuccessfulResponseMeme,
45
+ getValidResponseMetadataItems,
46
46
  hasQueryParameter,
47
47
  isRequiredRequestBody,
48
48
  partitionApiModules,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "api-farmer",
3
- "version": "0.0.17",
3
+ "version": "0.0.19",
4
4
  "description": "API module generation tool based on Openapi3/Swagger2.",
5
5
  "keywords": [
6
6
  "cli",
@@ -89,6 +89,7 @@
89
89
  "dev": "tsup src/index.ts src/cli.ts --format esm,cjs --watch --dts --shims",
90
90
  "format": "prettier --write .",
91
91
  "lint": "eslint . --fix",
92
- "release": "pnpm build && vr release"
92
+ "release": "pnpm build && vr release",
93
+ "gen": "pnpm --dir ./fixtures/axios gen & pnpm --dir ./fixtures/axle gen"
93
94
  }
94
95
  }
@@ -1,10 +1,10 @@
1
- <% if (ts && !typesOnly) { %> import { type AxiosRequestConfig } from 'axios' <% } %>
1
+ <% if (ts && !typesOnly) { %> import type { RequestConfig } from '@/request' <% } %>
2
2
  <% if (!typesOnly) { %> import { request } from '@/request' <% } %>
3
3
  <% if (ts) { %> import { type paths } from './<%- typesFilename %>' <% } %>
4
4
 
5
5
  <% if (!typesOnly) { %>
6
6
  <% apiModule.payloads.forEach(payload => { %> -%>
7
- export const <%- payload.fn %> = (config<% if (ts) { %>: AxiosRequestConfig<<%- payload.typeRequestBody %>> <% } %>)
7
+ export const <%- payload.fn %> = (config<% if (ts) { %>: RequestConfig<<%- payload.typeRequestBody %>> <% } %> = {})
8
8
  => request<% if (ts) { %><any, <%- payload.typeResponseBody %>><% } %>({
9
9
  url: '<%- payload.url %>',
10
10
  method: '<%- payload.method %>',