@paulpugovkin/api-docs-axios-ts-generator 1.0.6 → 1.0.7
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/package.json +3 -3
- package/src/index.js +129 -0
- package/src/index.min.js +0 -2
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@paulpugovkin/api-docs-axios-ts-generator",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.7",
|
|
4
4
|
"description": "Generate TypeScript interfaces and axios classes from OpenAPI documentation",
|
|
5
|
-
"main": "src/index.
|
|
5
|
+
"main": "src/index.js",
|
|
6
6
|
"bin": {
|
|
7
|
-
"api-docs-generator": "./
|
|
7
|
+
"api-docs-generator": "./bin/cli.js"
|
|
8
8
|
},
|
|
9
9
|
"types": "src/types/index.d.ts",
|
|
10
10
|
"scripts": {
|
package/src/index.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
const {program} = require("commander");
|
|
2
|
+
const path = require("path");
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
|
|
5
|
+
// Модули генератора
|
|
6
|
+
const {
|
|
7
|
+
cleanGeneratedFolder,
|
|
8
|
+
} = require("./clean-generated-folder/cleanGeneratedFolder");
|
|
9
|
+
const {
|
|
10
|
+
updateApiDocsJson,
|
|
11
|
+
} = require("./update-api-docs-json/updateApiDocsJson");
|
|
12
|
+
const {parseAndGenerate} = require("./parse-and-generate/parseAndGenerate");
|
|
13
|
+
const {
|
|
14
|
+
generateIndexFileWithOpenApi,
|
|
15
|
+
} = require("./generate-index-file-with-public-api/generateIndexFileWithPublicApi");
|
|
16
|
+
const {
|
|
17
|
+
generateMainIndexFile,
|
|
18
|
+
} = require("./generate-main-index-file/generateMainIndexFile");
|
|
19
|
+
const {generateAxiosConfig} = require("./generators/axiosConfigGenerator");
|
|
20
|
+
|
|
21
|
+
// Модуль загрузки конфигурации (компилированный TypeScript)
|
|
22
|
+
let loadConfig;
|
|
23
|
+
try {
|
|
24
|
+
loadConfig = require("./config/loadConfig").loadConfig;
|
|
25
|
+
} catch (e) {
|
|
26
|
+
// Если скомпилированный файл не существует, используем простой режим
|
|
27
|
+
console.warn("Config module not found, using CLI mode only");
|
|
28
|
+
loadConfig = null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Основной инструмент CLI
|
|
32
|
+
program
|
|
33
|
+
.version("1.0.0")
|
|
34
|
+
.description("Generate TypeScript API client from OpenAPI documentation")
|
|
35
|
+
.option("-c, --config <path>", "Path to configuration file")
|
|
36
|
+
.option("--api-docs-url <url>", "URL to fetch the OpenAPI documentation")
|
|
37
|
+
.option("--api-docs-path <path>", "Local path to OpenAPI documentation file")
|
|
38
|
+
.option("--output-dir <dir>", "Output directory for generated files")
|
|
39
|
+
.option("--clean", "Clean output directory before generation")
|
|
40
|
+
.parse(process.argv);
|
|
41
|
+
|
|
42
|
+
// Основной вызов
|
|
43
|
+
async function main() {
|
|
44
|
+
const options = program.opts();
|
|
45
|
+
const configPath = options.config;
|
|
46
|
+
|
|
47
|
+
let config = null;
|
|
48
|
+
|
|
49
|
+
// Загрузка конфигурации из файла или использование CLI аргументов
|
|
50
|
+
if (configPath && loadConfig) {
|
|
51
|
+
try {
|
|
52
|
+
config = await loadConfig(configPath, {
|
|
53
|
+
apiDocsUrl: options.apiDocsUrl,
|
|
54
|
+
apiDocsPath: options.apiDocsPath,
|
|
55
|
+
outputDir: options.outputDir,
|
|
56
|
+
});
|
|
57
|
+
} catch (error) {
|
|
58
|
+
console.error(`Failed to load configuration: ${error.message}`);
|
|
59
|
+
process.exit(1);
|
|
60
|
+
}
|
|
61
|
+
} else {
|
|
62
|
+
// Режим обратной совместимости - использование CLI аргументов
|
|
63
|
+
const apiDocsUrl = options.apiDocsUrl;
|
|
64
|
+
const outputDir = options.outputDir || path.resolve(__dirname, "../generated");
|
|
65
|
+
|
|
66
|
+
// Проверяем, указан ли URL для API документации
|
|
67
|
+
if (!apiDocsUrl) {
|
|
68
|
+
console.error('Error: API documentation URL is required.');
|
|
69
|
+
console.error('Please specify --api-docs-url or --api-docs-path, or create a configuration file.');
|
|
70
|
+
console.error('Run "api-docs-generator --help" for more information.');
|
|
71
|
+
process.exit(1);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
config = {
|
|
75
|
+
apiDocsUrl: apiDocsUrl,
|
|
76
|
+
outputDir: outputDir,
|
|
77
|
+
interfacesDir: path.join(outputDir, "interfaces"),
|
|
78
|
+
classesDir: path.join(outputDir, "classes"),
|
|
79
|
+
groupBy: "tag",
|
|
80
|
+
classMode: "multiple",
|
|
81
|
+
options: {
|
|
82
|
+
cleanOutputDir: options.clean !== undefined ? options.clean : true,
|
|
83
|
+
generateAxiosConfig: false,
|
|
84
|
+
generateIndexFiles: true,
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
console.log(`Using API Docs URL: ${config.apiDocsUrl}`);
|
|
90
|
+
console.log(`Output directory: ${config.outputDir}`);
|
|
91
|
+
|
|
92
|
+
// Определяем пути
|
|
93
|
+
const outputDir = config.outputDir;
|
|
94
|
+
const interfacesDir = config.interfacesDir || path.join(outputDir, "interfaces");
|
|
95
|
+
const classesDir = config.classesDir || path.join(outputDir, "classes");
|
|
96
|
+
const interfacesOpenApi = path.join(interfacesDir, "index.ts");
|
|
97
|
+
const classesOpenApi = path.join(classesDir, "index.ts");
|
|
98
|
+
|
|
99
|
+
// Очищаем папку, если нужно
|
|
100
|
+
if (config.options?.cleanOutputDir !== false) {
|
|
101
|
+
cleanGeneratedFolder(outputDir);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Обновляем API-документацию
|
|
105
|
+
if (config.apiDocsUrl) {
|
|
106
|
+
await updateApiDocsJson(config.apiDocsUrl, "api-docs.json");
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Генерация кода на основе спецификаций OpenAPI
|
|
110
|
+
const apiDocsPath = config.apiDocsPath || "api-docs.json";
|
|
111
|
+
await parseAndGenerate(apiDocsPath, config);
|
|
112
|
+
|
|
113
|
+
// Генерация конфигурации axios, если нужно
|
|
114
|
+
if (config.options?.generateAxiosConfig) {
|
|
115
|
+
generateAxiosConfig(config, outputDir);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Генерация файлов index.ts для интерфейсов
|
|
119
|
+
if (config.options?.generateIndexFiles !== false) {
|
|
120
|
+
await generateIndexFileWithOpenApi(interfacesDir, interfacesOpenApi);
|
|
121
|
+
await generateIndexFileWithOpenApi(classesDir, classesOpenApi);
|
|
122
|
+
await generateMainIndexFile(outputDir);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
console.log("Generation completed successfully.");
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Вызов
|
|
129
|
+
main().catch((err) => console.error("Error during generation:", err));
|
package/src/index.min.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
const fs=require('fs'),path=require('path'),{program}=require('commander'),{parseAndGenerate}=require('./parse-and-generate/parseAndGenerate'),{cleanGeneratedFolder}=require('./clean-generated-folder/cleanGeneratedFolder'),{collectGeneratedFiles}=require('./collect-genereted-files/collectGeneratedFiles'),{generateInterface}=require('./generate-interface/generateInterface'),{generateClass}=require('./generate-class/generateClass'),{generateMethod}=require('./generate-method/generateMethod'),{generateJSDoc}=require('./generate-js-doc/generateJSDoc'),{generateIndexFileWithPublicApi}=require('./generate-index-file-with-public-api/generateIndexFileWithPublicApi'),{generateMainIndexFile}=require('./generate-main-index-file/generateMainIndexFile'),{generateAxiosConfig}=require('./generators/axiosConfigGenerator'),{mapType}=require('./map-type/mapType'),{resolveType}=require('./resolve-type/resolveType'),{updateApiDocsJson}=require('./update-api-docs-json/updateApiDocsJson');program.name('api-docs-generator').description('Generate TypeScript interfaces and axios classes from OpenAPI documentation').version('1.0.5').option('-c, --config <path>','Path to configuration file').option('--api-docs-url <url>','URL to fetch OpenAPI documentation').option('--api-docs-path <path>','Local path to OpenAPI documentation file').option('--output-dir <dir>','Output directory for generated files').option('--clean','Clean output directory before generation');program.parse(process.argv);async function main(){let config;const options=program.opts();if(options.config){try{const configPath=path.resolve(options.config);if(!fs.existsSync(configPath)){console.error(`Configuration file not found: ${configPath}`);process.exit(1);}const configContent=fs.readFileSync(configPath,'utf8');const ext=path.extname(configPath);if(ext==='.js'){const modulePath=path.resolve(configPath);config=eval(`require('${modulePath.replace(/\\/g,'\\\\')}')`);}else if(ext==='.json'){config=JSON.parse(configContent);}else if(ext==='.ts'){const ts=require('typescript');const result=ts.transpileModule(configContent,{compilerOptions:{module:1,target:99,esModuleInterop:!0}});const modulePath=path.resolve(configPath.replace('.ts','.js'));fs.writeFileSync(modulePath,result);config=eval(`require('${modulePath.replace(/\\/g,'\\\\')}')`);}else{console.error('Unsupported configuration file format. Use .js, .json, or .ts');process.exit(1);}}catch(error){console.error(`Failed to load configuration: ${error.message}`);process.exit(1);}}else{const apiDocsUrl=options.apiDocsUrl;if(!apiDocsUrl){console.error('Error: API documentation URL is required.');console.error('Please specify --api-docs-url or --api-docs-path, or create a configuration file.');console.error('Run "api-docs-generator --help" for more information.');process.exit(1);}const outputDir=options.outputDir||path.resolve(__dirname,"../generated");config={apiDocsUrl:apiDocsUrl,outputDir:outputDir,interfacesDir:path.join(outputDir,"interfaces"),classesDir:path.join(outputDir,"classes"),groupBy:"tag",classMode:"multiple",options:{cleanOutputDir:options.clean!==undefined?options.clean:!0,generateAxiosConfig:!1,allowAxiosConfigSpread:!0}};}await cleanGeneratedFolder(config);const apiDocs=await updateApiDocsJson(config);const schemaData=apiDocs.paths?apiDocs.paths:apiDocs.components?.schemas||{};const generatedFiles=await collectGeneratedFiles(config);const interfaces=generatedFiles.filter(f=>f.endsWith('.ts')&&!f.includes('index'));const classes=generatedFiles.filter(f=>f.endsWith('.ts')&&!f.includes('index'));await generateInterface(schemaData,interfaces,config);await generateClass(schemaData,classes,config);await generateJSDoc(schemaData,classes,config);await generateMethod(schemaData,classes,config);await generateIndexFileWithPublicApi(config);await generateMainIndexFile(config);await generateAxiosConfig(config);console.log('✓ API client generated successfully!');console.log(` Output directory: ${config.outputDir}`);}main().catch(error=>{console.error('Error:',error.message);process.exit(1);});
|