@toktokhan-dev/cli-plugin-gen-api-react-query 0.1.4 → 0.1.5
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/dist/index.d.ts +13 -4
- package/dist/index.js +159 -21
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -31,11 +31,19 @@ interface PaginationConfig {
|
|
|
31
31
|
/**
|
|
32
32
|
* @category Types
|
|
33
33
|
*/
|
|
34
|
-
|
|
34
|
+
type SwaggerSchemaOption = {
|
|
35
|
+
swaggerSchemaUrl: string;
|
|
36
|
+
swaggerSchemaUrls?: never;
|
|
37
|
+
} | {
|
|
38
|
+
swaggerSchemaUrl?: never;
|
|
39
|
+
swaggerSchemaUrls: string[];
|
|
40
|
+
};
|
|
41
|
+
type GenerateSwaggerApiConfig = SwaggerSchemaOption & {
|
|
35
42
|
/** 조회할 스웨거의 url 혹은 file(yaml, json) 경로 입니다. 통상적으로
|
|
36
43
|
* 백앤드 개발자에게 공유받은 api-swagger-url 의 '/openapi.json' 경로에 해당합니다.
|
|
37
44
|
*/
|
|
38
|
-
|
|
45
|
+
/** 단일 스웨거 URL 또는 다중 스웨거 URL 중 하나만 입력할 수 있습니다 */
|
|
46
|
+
/** 다중 URL 지원: 여러 스웨거 URL을 배열로 받아서 처리합니다. */
|
|
39
47
|
/** 생성될 파일들이 위치할 경로입니다. */
|
|
40
48
|
output: string;
|
|
41
49
|
/** 생성되는 코드의 useQuery, useInfiniteQuery 포함 여부 입니다. */
|
|
@@ -50,11 +58,12 @@ interface GenerateSwaggerApiConfig {
|
|
|
50
58
|
* infiniteQuery 를 생성할 함수 필터 목록 입니다.
|
|
51
59
|
* */
|
|
52
60
|
paginationSets: PaginationConfig[];
|
|
53
|
-
}
|
|
61
|
+
};
|
|
54
62
|
/**
|
|
55
63
|
* @category Commands
|
|
56
64
|
*/
|
|
57
65
|
declare const genApi: _toktokhan_dev_cli.MyCommand<GenerateSwaggerApiConfig, "gen:api">;
|
|
66
|
+
declare function mergeTypeScriptContent(existing: string, newContent: string): string;
|
|
58
67
|
|
|
59
|
-
export { genApi };
|
|
68
|
+
export { genApi, mergeTypeScriptContent };
|
|
60
69
|
export type { GenerateFn, GenerateSwaggerApiConfig, PaginationConfig };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { defineCommand } from '@toktokhan-dev/cli';
|
|
2
2
|
import { createPackageRoot, prettierString, withLoading, cwd } from '@toktokhan-dev/node';
|
|
3
|
+
import omit from 'lodash/omit.js';
|
|
3
4
|
import path from 'path';
|
|
4
5
|
import { generateApi } from 'swagger-typescript-api';
|
|
5
6
|
import fs from 'fs';
|
|
@@ -131,7 +132,28 @@ async function generatePretty(path, contents) {
|
|
|
131
132
|
generate(path, formatted);
|
|
132
133
|
}
|
|
133
134
|
function generate(path, contents) {
|
|
134
|
-
|
|
135
|
+
// 기존 파일이 있으면 읽어서 병합
|
|
136
|
+
let existingContent = '';
|
|
137
|
+
try {
|
|
138
|
+
if (fs.existsSync(path)) {
|
|
139
|
+
existingContent = fs.readFileSync(path, 'utf8');
|
|
140
|
+
console.log('🔧 [SMART-MERGE] Found existing file, merging:', path);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
catch (err) {
|
|
144
|
+
console.log('🔧 [SMART-MERGE] No existing file found:', path);
|
|
145
|
+
}
|
|
146
|
+
// 기존 내용이 있으면 병합
|
|
147
|
+
if (existingContent) {
|
|
148
|
+
// 스마트 병합: 중복 타입 제거
|
|
149
|
+
const mergedContent = mergeTypeScriptContent(existingContent, contents);
|
|
150
|
+
fs.writeFileSync(path, mergedContent);
|
|
151
|
+
console.log('🔧 [SMART-MERGE] Smart merged content for:', path);
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
fs.writeFileSync(path, contents);
|
|
155
|
+
console.log('🔧 [SMART-MERGE] Created new file:', path);
|
|
156
|
+
}
|
|
135
157
|
}
|
|
136
158
|
function splitHookContents(filename, content) {
|
|
137
159
|
const [_apiContent, _hookContent] = content.split(QUERY_HOOK_INDICATOR);
|
|
@@ -178,8 +200,19 @@ const genApi = defineCommand({
|
|
|
178
200
|
},
|
|
179
201
|
run: async (config) => {
|
|
180
202
|
const isWebUrl = (string) => string.startsWith('http://') || string.startsWith('https://');
|
|
181
|
-
|
|
182
|
-
|
|
203
|
+
// 다중 URL 처리 로직 추가
|
|
204
|
+
const urls = (() => {
|
|
205
|
+
if ('swaggerSchemaUrls' in config) {
|
|
206
|
+
return config.swaggerSchemaUrls;
|
|
207
|
+
}
|
|
208
|
+
if ('swaggerSchemaUrl' in config) {
|
|
209
|
+
return [config.swaggerSchemaUrl];
|
|
210
|
+
}
|
|
211
|
+
return [];
|
|
212
|
+
})();
|
|
213
|
+
console.log('🔧 [MULTI-URL] Processing URLs:', urls);
|
|
214
|
+
const coverPath = (config, url) => {
|
|
215
|
+
const { httpClientType, output } = config;
|
|
183
216
|
const { AXIOS_DEFAULT_INSTANCE_PATH, FETCH_DEFAULT_INSTANCE_PATH } = GENERATE_SWAGGER_DATA;
|
|
184
217
|
const instancePath = config.instancePath ||
|
|
185
218
|
(httpClientType === 'axios' ?
|
|
@@ -188,28 +221,133 @@ const genApi = defineCommand({
|
|
|
188
221
|
return {
|
|
189
222
|
...config,
|
|
190
223
|
instancePath,
|
|
191
|
-
swaggerSchemaUrl: isWebUrl(
|
|
224
|
+
swaggerSchemaUrl: isWebUrl(url) ? url : cwd(url),
|
|
192
225
|
output: cwd(output),
|
|
193
226
|
};
|
|
194
227
|
};
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
}
|
|
203
|
-
withLoading('Write Swagger API', //
|
|
204
|
-
covered.output, (spinner) => {
|
|
205
|
-
writeSwaggerApiFile({
|
|
206
|
-
input: parsed,
|
|
207
|
-
output: covered.output,
|
|
208
|
-
spinner,
|
|
209
|
-
config,
|
|
228
|
+
// 각 URL별로 순차 처리
|
|
229
|
+
for (let i = 0; i < urls.length; i++) {
|
|
230
|
+
const url = urls[i];
|
|
231
|
+
console.log(`🔧 [MULTI-URL] Processing URL ${i + 1}/${urls.length}: ${url}`);
|
|
232
|
+
const covered = coverPath(config, url);
|
|
233
|
+
const parsed = await withLoading(`Parse Swagger ${i + 1}/${urls.length}`, 'swaggerSchemaUrl' in covered ? covered.swaggerSchemaUrl : '', () => {
|
|
234
|
+
return parseSwagger(omit(covered, 'swaggerSchemaUrls'));
|
|
210
235
|
});
|
|
211
|
-
|
|
236
|
+
if (!parsed) {
|
|
237
|
+
console.error(`Failed to generate api for URL ${i + 1}: swagger parse error.`);
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
withLoading('Write Swagger API', //
|
|
241
|
+
covered.output, (spinner) => {
|
|
242
|
+
writeSwaggerApiFile({
|
|
243
|
+
input: parsed,
|
|
244
|
+
output: covered.output,
|
|
245
|
+
spinner,
|
|
246
|
+
config,
|
|
247
|
+
});
|
|
248
|
+
});
|
|
249
|
+
}
|
|
212
250
|
},
|
|
213
251
|
});
|
|
252
|
+
/**
|
|
253
|
+
* 스마트 타입 병합 함수들
|
|
254
|
+
*/
|
|
255
|
+
// 타입 정의 파싱 함수
|
|
256
|
+
function parseTypeDefinitions(content) {
|
|
257
|
+
const types = {};
|
|
258
|
+
// export type, interface, enum, const 패턴 매칭
|
|
259
|
+
const typeRegex = /(export\s+(?:type|interface|enum|const)\s+(\w+)[\s\S]*?)(?=export\s+(?:type|interface|enum|const)\s+\w+|$)/g;
|
|
260
|
+
let match;
|
|
261
|
+
while ((match = typeRegex.exec(content)) !== null) {
|
|
262
|
+
const typeName = match[2];
|
|
263
|
+
const typeContent = match[1].trim();
|
|
264
|
+
types[typeName] = typeContent;
|
|
265
|
+
}
|
|
266
|
+
return types;
|
|
267
|
+
}
|
|
268
|
+
// (deprecated) 타입 문자열 변환 로직은 병합 로직 내에서 직접 조립합니다.
|
|
269
|
+
// 스마트 타입 병합 함수
|
|
270
|
+
function mergeTypeScriptContent(existing, newContent) {
|
|
271
|
+
// 1) import 구문 보존 및 병합 (양쪽 모두에서 수집)
|
|
272
|
+
const importRegex = /^\s*import\s+[^;]*;\s*$/gm;
|
|
273
|
+
const sideEffectImportRegex = /^\s*import\s+['"][^'"]+['"];\s*$/gm;
|
|
274
|
+
const collectImports = (content) => {
|
|
275
|
+
const imports = new Set();
|
|
276
|
+
const matchedA = content.match(importRegex) ?? [];
|
|
277
|
+
const matchedB = content.match(sideEffectImportRegex) ?? [];
|
|
278
|
+
[...matchedA, ...matchedB].forEach((line) => imports.add(line.trim()));
|
|
279
|
+
const contentWithoutImports = content
|
|
280
|
+
.replace(importRegex, '')
|
|
281
|
+
.replace(sideEffectImportRegex, '');
|
|
282
|
+
return { imports: Array.from(imports), body: contentWithoutImports };
|
|
283
|
+
};
|
|
284
|
+
const { imports: existingImports, body: existingBody } = collectImports(existing);
|
|
285
|
+
const { imports: newImports, body: newBody } = collectImports(newContent);
|
|
286
|
+
// import 병합: 새 파일 기준 우선 순서 + 기존에만 있는 import 추가
|
|
287
|
+
const mergedImportSet = new Set(newImports);
|
|
288
|
+
existingImports.forEach((imp) => mergedImportSet.add(imp));
|
|
289
|
+
const mergedImports = Array.from(mergedImportSet);
|
|
290
|
+
// 2) 타입 선언 병합 (중복 제거)
|
|
291
|
+
const typeBlockRegex = /(export\s+(?:type|interface|enum|const)\s+\w+[\s\S]*?)(?=export\s+(?:type|interface|enum|const)\s+\w+|$)/g;
|
|
292
|
+
const existingTypes = parseTypeDefinitions(existingBody);
|
|
293
|
+
const newTypes = parseTypeDefinitions(newBody);
|
|
294
|
+
console.log('🔧 [SMART-MERGE] Existing types count:', Object.keys(existingTypes).length);
|
|
295
|
+
console.log('🔧 [SMART-MERGE] New types count:', Object.keys(newTypes).length);
|
|
296
|
+
const mergedTypes = { ...existingTypes };
|
|
297
|
+
let addedCount = 0;
|
|
298
|
+
let skippedCount = 0;
|
|
299
|
+
for (const [typeName, typeContent] of Object.entries(newTypes)) {
|
|
300
|
+
if (mergedTypes[typeName]) {
|
|
301
|
+
console.log('🔧 [SMART-MERGE] Skipping duplicate type:', typeName);
|
|
302
|
+
skippedCount++;
|
|
303
|
+
}
|
|
304
|
+
else {
|
|
305
|
+
mergedTypes[typeName] = typeContent;
|
|
306
|
+
addedCount++;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
console.log('🔧 [SMART-MERGE] Added types:', addedCount, 'Skipped duplicates:', skippedCount);
|
|
310
|
+
const mergedTypesString = Object.values(mergedTypes).join('\n\n');
|
|
311
|
+
// 3) 기타 코드(타입/임포트 외)는 "새로운 내용"을 기준으로 유지
|
|
312
|
+
const removeHeaderComment = (content) => {
|
|
313
|
+
// 파일 상단의 블록 코멘트 혹은 연속된 라인 코멘트 제거
|
|
314
|
+
const blockCommentAtTop = content.match(/^\s*\/\*[\s\S]*?\*\/\s*/);
|
|
315
|
+
if (blockCommentAtTop) {
|
|
316
|
+
return content.slice(blockCommentAtTop[0].length);
|
|
317
|
+
}
|
|
318
|
+
const lineCommentsAtTop = content.match(/^(?:\s*\/\/.*\n)+/);
|
|
319
|
+
if (lineCommentsAtTop) {
|
|
320
|
+
return content.slice(lineCommentsAtTop[0].length);
|
|
321
|
+
}
|
|
322
|
+
return content;
|
|
323
|
+
};
|
|
324
|
+
// 새 본문에서 타입 블록 제거 후 남은 코드
|
|
325
|
+
const newBodyWithoutTypes = (newBody || '').replace(typeBlockRegex, '');
|
|
326
|
+
const otherCodeFromNew = removeHeaderComment(newBodyWithoutTypes).trim();
|
|
327
|
+
// 4) 헤더 주석은 새 컨텐츠 상단의 헤더가 있으면 우선 사용, 없으면 기존의 것을 사용
|
|
328
|
+
const pickHeader = (content) => {
|
|
329
|
+
const block = content.match(/^\s*(\/\*[\s\S]*?\*\/)\s*/);
|
|
330
|
+
if (block)
|
|
331
|
+
return block[1];
|
|
332
|
+
const lines = content.match(/^(?:\s*\/\/.*\n)+/);
|
|
333
|
+
if (lines)
|
|
334
|
+
return lines[0].trimEnd();
|
|
335
|
+
return '';
|
|
336
|
+
};
|
|
337
|
+
const headerFromNew = pickHeader(newContent);
|
|
338
|
+
const headerFromExisting = pickHeader(existing);
|
|
339
|
+
const header = headerFromNew || headerFromExisting;
|
|
340
|
+
// 5) 최종 조립
|
|
341
|
+
const parts = [];
|
|
342
|
+
if (header)
|
|
343
|
+
parts.push(header);
|
|
344
|
+
if (mergedImports.length > 0)
|
|
345
|
+
parts.push(mergedImports.join('\n'));
|
|
346
|
+
if (mergedTypesString.trim().length > 0)
|
|
347
|
+
parts.push(mergedTypesString);
|
|
348
|
+
if (otherCodeFromNew.length > 0)
|
|
349
|
+
parts.push(otherCodeFromNew);
|
|
350
|
+
return parts.join('\n\n') + '\n';
|
|
351
|
+
}
|
|
214
352
|
|
|
215
|
-
export { genApi };
|
|
353
|
+
export { genApi, mergeTypeScriptContent };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@toktokhan-dev/cli-plugin-gen-api-react-query",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"description": "A CLI plugin for generating API hooks with React Query built by TOKTOKHAN.DEV",
|
|
5
5
|
"author": "TOKTOKHAN.DEV <fe-system@toktokhan.dev>",
|
|
6
6
|
"license": "ISC",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"eta": "^3.4.0",
|
|
38
38
|
"lodash": "^4.17.21",
|
|
39
39
|
"prettier-plugin-organize-imports": "^3.2.4",
|
|
40
|
-
"swagger-typescript-api": "
|
|
40
|
+
"swagger-typescript-api": "13.0.22",
|
|
41
41
|
"@toktokhan-dev/cli": "0.0.11",
|
|
42
42
|
"@toktokhan-dev/node": "0.0.10"
|
|
43
43
|
},
|