metadatafy 1.0.2 → 1.0.3

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.
@@ -1,1382 +0,0 @@
1
- 'use strict';
2
-
3
- var ts3 = require('typescript');
4
- var path2 = require('path');
5
- var fs = require('fs');
6
- var crypto = require('crypto');
7
- var glob = require('glob');
8
- var fs3 = require('fs/promises');
9
-
10
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
-
12
- function _interopNamespace(e) {
13
- if (e && e.__esModule) return e;
14
- var n = Object.create(null);
15
- if (e) {
16
- Object.keys(e).forEach(function (k) {
17
- if (k !== 'default') {
18
- var d = Object.getOwnPropertyDescriptor(e, k);
19
- Object.defineProperty(n, k, d.get ? d : {
20
- enumerable: true,
21
- get: function () { return e[k]; }
22
- });
23
- }
24
- });
25
- }
26
- n.default = e;
27
- return Object.freeze(n);
28
- }
29
-
30
- var ts3__default = /*#__PURE__*/_interopDefault(ts3);
31
- var path2__namespace = /*#__PURE__*/_interopNamespace(path2);
32
- var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
33
- var crypto__namespace = /*#__PURE__*/_interopNamespace(crypto);
34
- var fs3__namespace = /*#__PURE__*/_interopNamespace(fs3);
35
-
36
- // src/core/config.ts
37
- var DEFAULT_FILE_TYPE_MAPPING = {
38
- // Next.js App Router
39
- "app/**/page.tsx": "route",
40
- "app/**/page.ts": "route",
41
- "app/**/layout.tsx": "route",
42
- "app/**/layout.ts": "route",
43
- "app/**/route.tsx": "api",
44
- "app/**/route.ts": "api",
45
- "app/api/**/*.ts": "api",
46
- "app/api/**/*.tsx": "api",
47
- // Pages Router (레거시)
48
- "pages/**/*.tsx": "route",
49
- "pages/**/*.ts": "route",
50
- "pages/api/**/*.ts": "api",
51
- // Components
52
- "components/**/*.tsx": "component",
53
- "components/**/*.ts": "component",
54
- "src/components/**/*.tsx": "component",
55
- "src/components/**/*.ts": "component",
56
- // Hooks
57
- "hooks/**/*.ts": "hook",
58
- "hooks/**/*.tsx": "hook",
59
- "src/hooks/**/*.ts": "hook",
60
- "src/hooks/**/*.tsx": "hook",
61
- // Services
62
- "services/**/*.ts": "service",
63
- "src/services/**/*.ts": "service",
64
- // Utilities
65
- "lib/**/*.ts": "utility",
66
- "src/lib/**/*.ts": "utility",
67
- "utils/**/*.ts": "utility",
68
- "src/utils/**/*.ts": "utility",
69
- // Database
70
- "supabase/migrations/*.sql": "table",
71
- "prisma/migrations/**/*.sql": "table"
72
- };
73
- var DEFAULT_INCLUDE_PATTERNS = [
74
- "app/**/*.{ts,tsx}",
75
- "pages/**/*.{ts,tsx}",
76
- "components/**/*.{ts,tsx}",
77
- "hooks/**/*.{ts,tsx}",
78
- "services/**/*.ts",
79
- "lib/**/*.ts",
80
- "utils/**/*.ts",
81
- "src/**/*.{ts,tsx}",
82
- "supabase/migrations/*.sql"
83
- ];
84
- var DEFAULT_EXCLUDE_PATTERNS = [
85
- "**/node_modules/**",
86
- "**/.next/**",
87
- "**/dist/**",
88
- "**/*.test.{ts,tsx}",
89
- "**/*.spec.{ts,tsx}",
90
- "**/__tests__/**",
91
- "**/*.d.ts",
92
- "**/coverage/**"
93
- ];
94
- function createDefaultConfig(overrides = {}) {
95
- return {
96
- projectId: overrides.projectId || "default",
97
- include: overrides.include || DEFAULT_INCLUDE_PATTERNS,
98
- exclude: overrides.exclude || DEFAULT_EXCLUDE_PATTERNS,
99
- fileTypeMapping: {
100
- ...DEFAULT_FILE_TYPE_MAPPING,
101
- ...overrides.fileTypeMapping
102
- },
103
- output: {
104
- file: {
105
- enabled: true,
106
- path: "project-metadata.json",
107
- ...overrides.output?.file
108
- },
109
- api: {
110
- enabled: false,
111
- endpoint: "",
112
- ...overrides.output?.api
113
- }
114
- },
115
- koreanKeywords: overrides.koreanKeywords,
116
- mode: overrides.mode || "production",
117
- verbose: overrides.verbose || false
118
- };
119
- }
120
- function validateConfig(config) {
121
- const errors = [];
122
- if (!config.projectId) {
123
- errors.push("projectId is required");
124
- }
125
- if (config.output.api?.enabled && !config.output.api.endpoint) {
126
- errors.push("API endpoint is required when api output is enabled");
127
- }
128
- if (config.include.length === 0) {
129
- errors.push("At least one include pattern is required");
130
- }
131
- return errors;
132
- }
133
- function globToRegex(pattern) {
134
- const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/{{GLOBSTAR}}/g, ".*").replace(/\{([^}]+)\}/g, (_, group) => {
135
- const alternatives = group.split(",").map((s) => s.trim());
136
- return `(${alternatives.join("|")})`;
137
- });
138
- return new RegExp(`^${escaped}$`);
139
- }
140
- var TypeScriptParser = class {
141
- constructor() {
142
- this.compilerOptions = {
143
- target: ts3__default.default.ScriptTarget.ESNext,
144
- module: ts3__default.default.ModuleKind.ESNext,
145
- jsx: ts3__default.default.JsxEmit.React,
146
- esModuleInterop: true,
147
- allowSyntheticDefaultImports: true,
148
- strict: false
149
- };
150
- }
151
- /**
152
- * 소스 코드를 AST로 파싱
153
- */
154
- parse(content, filePath) {
155
- return ts3__default.default.createSourceFile(
156
- filePath,
157
- content,
158
- this.compilerOptions.target,
159
- true,
160
- this.getScriptKind(filePath)
161
- );
162
- }
163
- /**
164
- * 파일 확장자에 따른 ScriptKind 결정
165
- */
166
- getScriptKind(filePath) {
167
- const ext = filePath.toLowerCase();
168
- if (ext.endsWith(".tsx")) return ts3__default.default.ScriptKind.TSX;
169
- if (ext.endsWith(".ts")) return ts3__default.default.ScriptKind.TS;
170
- if (ext.endsWith(".jsx")) return ts3__default.default.ScriptKind.JSX;
171
- if (ext.endsWith(".js")) return ts3__default.default.ScriptKind.JS;
172
- return ts3__default.default.ScriptKind.Unknown;
173
- }
174
- /**
175
- * AST 노드 순회
176
- */
177
- traverse(node, visitor) {
178
- const shouldContinue = visitor(node);
179
- if (shouldContinue === false) return;
180
- ts3__default.default.forEachChild(node, (child) => this.traverse(child, visitor));
181
- }
182
- /**
183
- * 특정 조건을 만족하는 노드 수집
184
- */
185
- findNodes(sourceFile, predicate) {
186
- const results = [];
187
- this.traverse(sourceFile, (node) => {
188
- if (predicate(node)) {
189
- results.push(node);
190
- }
191
- });
192
- return results;
193
- }
194
- /**
195
- * 노드의 텍스트 추출
196
- */
197
- getNodeText(node, sourceFile) {
198
- return node.getText(sourceFile);
199
- }
200
- /**
201
- * JSDoc 코멘트 추출
202
- */
203
- getJSDocComment(node) {
204
- const jsDocNodes = ts3__default.default.getJSDocCommentsAndTags(node);
205
- if (jsDocNodes.length === 0) return void 0;
206
- return jsDocNodes.filter(ts3__default.default.isJSDoc).map((doc) => doc.comment).filter(Boolean).join("\n");
207
- }
208
- };
209
- new TypeScriptParser();
210
- var SQLParser = class {
211
- /**
212
- * SQL 파일 파싱
213
- */
214
- parse(content, relativePath) {
215
- const tables = this.extractTables(content);
216
- const tableName = tables[0]?.name || this.extractNameFromPath(relativePath);
217
- return {
218
- path: relativePath,
219
- type: "table",
220
- name: tableName,
221
- imports: [],
222
- exports: tables.map((t) => ({
223
- name: t.name,
224
- isDefault: false,
225
- isTypeOnly: false,
226
- kind: "variable"
227
- })),
228
- metadata: {
229
- tableName,
230
- columns: tables[0]?.columns || []
231
- }
232
- };
233
- }
234
- /**
235
- * CREATE TABLE 문에서 테이블 정보 추출
236
- */
237
- extractTables(content) {
238
- const tables = [];
239
- const createTableRegex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["']?(\w+)["']?\s*\(([\s\S]*?)\);/gi;
240
- let match;
241
- while ((match = createTableRegex.exec(content)) !== null) {
242
- const tableName = match[1];
243
- const columnsBlock = match[2];
244
- const columns = this.parseColumns(columnsBlock);
245
- tables.push({ name: tableName, columns });
246
- }
247
- const alterTableRegex = /ALTER\s+TABLE\s+["']?(\w+)["']?\s+ADD\s+(?:COLUMN\s+)?["']?(\w+)["']?\s+(\w+)/gi;
248
- while ((match = alterTableRegex.exec(content)) !== null) {
249
- const tableName = match[1];
250
- const columnName = match[2];
251
- const columnType = match[3];
252
- let table = tables.find((t) => t.name === tableName);
253
- if (!table) {
254
- table = { name: tableName, columns: [] };
255
- tables.push(table);
256
- }
257
- table.columns.push({
258
- name: columnName,
259
- type: columnType,
260
- nullable: true,
261
- isPrimaryKey: false,
262
- isForeignKey: false
263
- });
264
- }
265
- return tables;
266
- }
267
- /**
268
- * 컬럼 정의 파싱
269
- */
270
- parseColumns(columnsBlock) {
271
- const columns = [];
272
- const lines = columnsBlock.split(",").map((line) => line.trim()).filter(
273
- (line) => line && !line.toUpperCase().startsWith("CONSTRAINT") && !line.toUpperCase().startsWith("PRIMARY KEY") && !line.toUpperCase().startsWith("FOREIGN KEY") && !line.toUpperCase().startsWith("UNIQUE") && !line.toUpperCase().startsWith("CHECK")
274
- );
275
- for (const line of lines) {
276
- const column = this.parseColumnDefinition(line);
277
- if (column) {
278
- columns.push(column);
279
- }
280
- }
281
- return columns;
282
- }
283
- /**
284
- * 단일 컬럼 정의 파싱
285
- */
286
- parseColumnDefinition(line) {
287
- const match = line.match(/^["']?(\w+)["']?\s+(\w+(?:\([^)]+\))?)/i);
288
- if (!match) return null;
289
- const [, name, type] = match;
290
- const upperLine = line.toUpperCase();
291
- return {
292
- name,
293
- type: type.toUpperCase(),
294
- nullable: !upperLine.includes("NOT NULL"),
295
- isPrimaryKey: upperLine.includes("PRIMARY KEY"),
296
- isForeignKey: upperLine.includes("REFERENCES"),
297
- references: this.extractReference(line)
298
- };
299
- }
300
- /**
301
- * REFERENCES 절에서 참조 정보 추출
302
- */
303
- extractReference(line) {
304
- const match = line.match(
305
- /REFERENCES\s+["']?(\w+)["']?\s*\(["']?(\w+)["']?\)/i
306
- );
307
- if (!match) return void 0;
308
- return {
309
- table: match[1],
310
- column: match[2]
311
- };
312
- }
313
- /**
314
- * 파일 경로에서 테이블 이름 추출
315
- */
316
- extractNameFromPath(filePath) {
317
- const filename = path2__namespace.basename(filePath);
318
- const match = filename.match(/create_(\w+)_table/i);
319
- return match ? match[1] : filename.replace(".sql", "");
320
- }
321
- };
322
- var ImportExtractor = class {
323
- /**
324
- * SourceFile에서 모든 import 정보 추출
325
- */
326
- extract(sourceFile) {
327
- const imports = [];
328
- ts3__default.default.forEachChild(sourceFile, (node) => {
329
- if (ts3__default.default.isImportDeclaration(node)) {
330
- const importInfo = this.parseImportDeclaration(node);
331
- if (importInfo) {
332
- imports.push(importInfo);
333
- }
334
- }
335
- });
336
- return imports;
337
- }
338
- /**
339
- * ImportDeclaration 노드를 ImportInfo로 변환
340
- */
341
- parseImportDeclaration(node) {
342
- const moduleSpecifier = node.moduleSpecifier;
343
- if (!ts3__default.default.isStringLiteral(moduleSpecifier)) {
344
- return null;
345
- }
346
- const source = moduleSpecifier.text;
347
- const specifiers = [];
348
- let isDefault = false;
349
- const isTypeOnly = node.importClause?.isTypeOnly || false;
350
- const importClause = node.importClause;
351
- if (!importClause) {
352
- return {
353
- source,
354
- specifiers: [],
355
- isDefault: false,
356
- isTypeOnly: false
357
- };
358
- }
359
- if (importClause.name) {
360
- specifiers.push(importClause.name.text);
361
- isDefault = true;
362
- }
363
- const namedBindings = importClause.namedBindings;
364
- if (namedBindings) {
365
- if (ts3__default.default.isNamespaceImport(namedBindings)) {
366
- specifiers.push(`* as ${namedBindings.name.text}`);
367
- } else if (ts3__default.default.isNamedImports(namedBindings)) {
368
- for (const element of namedBindings.elements) {
369
- const name = element.name.text;
370
- const propertyName = element.propertyName?.text;
371
- if (propertyName) {
372
- specifiers.push(`${propertyName} as ${name}`);
373
- } else {
374
- specifiers.push(name);
375
- }
376
- }
377
- }
378
- }
379
- return {
380
- source,
381
- specifiers,
382
- isDefault,
383
- isTypeOnly
384
- };
385
- }
386
- };
387
- var ExportExtractor = class {
388
- /**
389
- * SourceFile에서 모든 export 정보 추출
390
- */
391
- extract(sourceFile) {
392
- const exports$1 = [];
393
- ts3__default.default.forEachChild(sourceFile, (node) => {
394
- const exportInfos = this.extractFromNode(node, sourceFile);
395
- exports$1.push(...exportInfos);
396
- });
397
- return exports$1;
398
- }
399
- /**
400
- * 노드에서 export 정보 추출
401
- */
402
- extractFromNode(node, sourceFile) {
403
- const results = [];
404
- if (ts3__default.default.isFunctionDeclaration(node) && this.hasExportModifier(node)) {
405
- results.push({
406
- name: node.name?.text || "anonymous",
407
- isDefault: this.hasDefaultModifier(node),
408
- isTypeOnly: false,
409
- kind: "function"
410
- });
411
- }
412
- if (ts3__default.default.isClassDeclaration(node) && this.hasExportModifier(node)) {
413
- results.push({
414
- name: node.name?.text || "anonymous",
415
- isDefault: this.hasDefaultModifier(node),
416
- isTypeOnly: false,
417
- kind: "class"
418
- });
419
- }
420
- if (ts3__default.default.isVariableStatement(node) && this.hasExportModifier(node)) {
421
- for (const declaration of node.declarationList.declarations) {
422
- if (ts3__default.default.isIdentifier(declaration.name)) {
423
- results.push({
424
- name: declaration.name.text,
425
- isDefault: false,
426
- isTypeOnly: false,
427
- kind: "variable"
428
- });
429
- }
430
- }
431
- }
432
- if (ts3__default.default.isTypeAliasDeclaration(node) && this.hasExportModifier(node)) {
433
- results.push({
434
- name: node.name.text,
435
- isDefault: false,
436
- isTypeOnly: true,
437
- kind: "type"
438
- });
439
- }
440
- if (ts3__default.default.isInterfaceDeclaration(node) && this.hasExportModifier(node)) {
441
- results.push({
442
- name: node.name.text,
443
- isDefault: false,
444
- isTypeOnly: true,
445
- kind: "interface"
446
- });
447
- }
448
- if (ts3__default.default.isExportAssignment(node) && !node.isExportEquals) {
449
- const name = this.getExportDefaultName(node, sourceFile);
450
- results.push({
451
- name,
452
- isDefault: true,
453
- isTypeOnly: false,
454
- kind: "variable"
455
- });
456
- }
457
- if (ts3__default.default.isExportDeclaration(node)) {
458
- const exportClause = node.exportClause;
459
- if (exportClause && ts3__default.default.isNamedExports(exportClause)) {
460
- for (const element of exportClause.elements) {
461
- results.push({
462
- name: element.name.text,
463
- isDefault: false,
464
- isTypeOnly: node.isTypeOnly,
465
- kind: "variable"
466
- });
467
- }
468
- }
469
- }
470
- return results;
471
- }
472
- /**
473
- * export 키워드가 있는지 확인
474
- */
475
- hasExportModifier(node) {
476
- const modifiers = ts3__default.default.canHaveModifiers(node) ? ts3__default.default.getModifiers(node) : void 0;
477
- return modifiers?.some((m) => m.kind === ts3__default.default.SyntaxKind.ExportKeyword) || false;
478
- }
479
- /**
480
- * default 키워드가 있는지 확인
481
- */
482
- hasDefaultModifier(node) {
483
- const modifiers = ts3__default.default.canHaveModifiers(node) ? ts3__default.default.getModifiers(node) : void 0;
484
- return modifiers?.some((m) => m.kind === ts3__default.default.SyntaxKind.DefaultKeyword) || false;
485
- }
486
- /**
487
- * export default의 이름 추출
488
- */
489
- getExportDefaultName(node, _sourceFile) {
490
- const expr = node.expression;
491
- if (ts3__default.default.isIdentifier(expr)) {
492
- return expr.text;
493
- }
494
- if (ts3__default.default.isArrowFunction(expr) || ts3__default.default.isFunctionExpression(expr)) {
495
- return "default";
496
- }
497
- if (ts3__default.default.isCallExpression(expr) && ts3__default.default.isIdentifier(expr.expression)) {
498
- const firstArg = expr.arguments[0];
499
- if (firstArg && ts3__default.default.isIdentifier(firstArg)) {
500
- return firstArg.text;
501
- }
502
- }
503
- return "default";
504
- }
505
- };
506
- var PropsExtractor = class {
507
- /**
508
- * SourceFile에서 Props 정보 추출
509
- */
510
- extract(sourceFile) {
511
- const props = [];
512
- const propsType = this.findPropsType(sourceFile);
513
- if (propsType) {
514
- props.push(...this.extractFromTypeNode(propsType, sourceFile));
515
- }
516
- const componentFunction = this.findComponentFunction(sourceFile);
517
- if (componentFunction) {
518
- props.push(
519
- ...this.extractFromFunctionParams(componentFunction, sourceFile)
520
- );
521
- }
522
- return this.deduplicateProps(props);
523
- }
524
- /**
525
- * Props 타입 정의 찾기
526
- */
527
- findPropsType(sourceFile) {
528
- let propsType;
529
- ts3__default.default.forEachChild(sourceFile, (node) => {
530
- if (ts3__default.default.isInterfaceDeclaration(node) && node.name.text.endsWith("Props")) {
531
- propsType = node;
532
- }
533
- if (ts3__default.default.isTypeAliasDeclaration(node) && node.name.text.endsWith("Props")) {
534
- propsType = node.type;
535
- }
536
- });
537
- return propsType;
538
- }
539
- /**
540
- * 컴포넌트 함수 찾기
541
- */
542
- findComponentFunction(sourceFile) {
543
- let component;
544
- ts3__default.default.forEachChild(sourceFile, (node) => {
545
- if (ts3__default.default.isFunctionDeclaration(node) && this.isExported(node)) {
546
- component = node;
547
- }
548
- if (ts3__default.default.isVariableStatement(node) && this.isExported(node)) {
549
- for (const decl of node.declarationList.declarations) {
550
- if (decl.initializer && (ts3__default.default.isArrowFunction(decl.initializer) || ts3__default.default.isFunctionExpression(decl.initializer))) {
551
- component = decl.initializer;
552
- }
553
- }
554
- }
555
- });
556
- return component;
557
- }
558
- /**
559
- * 타입 노드에서 Props 추출
560
- */
561
- extractFromTypeNode(typeNode, sourceFile) {
562
- const props = [];
563
- if (ts3__default.default.isInterfaceDeclaration(typeNode)) {
564
- for (const member of typeNode.members) {
565
- const propInfo = this.extractMemberProp(member, sourceFile);
566
- if (propInfo) {
567
- props.push(propInfo);
568
- }
569
- }
570
- return props;
571
- }
572
- if (ts3__default.default.isTypeLiteralNode(typeNode)) {
573
- for (const member of typeNode.members) {
574
- const propInfo = this.extractMemberProp(member, sourceFile);
575
- if (propInfo) {
576
- props.push(propInfo);
577
- }
578
- }
579
- }
580
- if (ts3__default.default.isIntersectionTypeNode(typeNode)) {
581
- for (const type of typeNode.types) {
582
- props.push(...this.extractFromTypeNode(type, sourceFile));
583
- }
584
- }
585
- return props;
586
- }
587
- /**
588
- * 타입 멤버에서 PropInfo 추출
589
- */
590
- extractMemberProp(member, sourceFile) {
591
- if (!ts3__default.default.isPropertySignature(member)) {
592
- return null;
593
- }
594
- const name = member.name;
595
- if (!ts3__default.default.isIdentifier(name) && !ts3__default.default.isStringLiteral(name)) {
596
- return null;
597
- }
598
- const propName = ts3__default.default.isIdentifier(name) ? name.text : name.text;
599
- const required = !member.questionToken;
600
- const type = member.type ? member.type.getText(sourceFile) : "any";
601
- return {
602
- name: propName,
603
- type,
604
- required
605
- };
606
- }
607
- /**
608
- * 함수 매개변수에서 Props 추출
609
- */
610
- extractFromFunctionParams(func, sourceFile) {
611
- const props = [];
612
- const firstParam = func.parameters[0];
613
- if (!firstParam) return props;
614
- if (ts3__default.default.isObjectBindingPattern(firstParam.name)) {
615
- for (const element of firstParam.name.elements) {
616
- if (ts3__default.default.isBindingElement(element) && ts3__default.default.isIdentifier(element.name)) {
617
- props.push({
618
- name: element.name.text,
619
- type: "unknown",
620
- required: !element.initializer,
621
- defaultValue: element.initializer?.getText(sourceFile)
622
- });
623
- }
624
- }
625
- }
626
- return props;
627
- }
628
- /**
629
- * export 키워드가 있는지 확인
630
- */
631
- isExported(node) {
632
- const modifiers = ts3__default.default.canHaveModifiers(node) ? ts3__default.default.getModifiers(node) : void 0;
633
- return modifiers?.some((m) => m.kind === ts3__default.default.SyntaxKind.ExportKeyword) || false;
634
- }
635
- /**
636
- * 중복 Props 제거
637
- */
638
- deduplicateProps(props) {
639
- const seen = /* @__PURE__ */ new Set();
640
- return props.filter((prop) => {
641
- if (seen.has(prop.name)) return false;
642
- seen.add(prop.name);
643
- return true;
644
- });
645
- }
646
- };
647
-
648
- // src/utils/naming-utils.ts
649
- function splitCamelCase(str) {
650
- return str.replace(/([a-z])([A-Z])/g, "$1 $2").split(" ").filter(Boolean);
651
- }
652
- function splitPascalCase(str) {
653
- return str.replace(/([A-Z])([A-Z][a-z])/g, "$1 $2").replace(/([a-z])([A-Z])/g, "$1 $2").split(" ").filter(Boolean);
654
- }
655
- function splitSnakeCase(str) {
656
- return str.split("_").filter(Boolean);
657
- }
658
- function splitKebabCase(str) {
659
- return str.split("-").filter(Boolean);
660
- }
661
- function splitIntoWords(str) {
662
- const words = /* @__PURE__ */ new Set();
663
- const parts = str.split(/[-_]/);
664
- for (const part of parts) {
665
- const camelSplit = splitCamelCase(part);
666
- camelSplit.forEach((w) => words.add(w.toLowerCase()));
667
- }
668
- return [...words];
669
- }
670
- function extractAcronyms(str) {
671
- const acronyms = [];
672
- const matches = str.match(/[A-Z]{2,}/g);
673
- if (matches) {
674
- acronyms.push(...matches);
675
- }
676
- return acronyms;
677
- }
678
- function toAllCases(str) {
679
- const words = splitIntoWords(str);
680
- return {
681
- camel: words.map(
682
- (w, i) => i === 0 ? w.toLowerCase() : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()
683
- ).join(""),
684
- pascal: words.map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(""),
685
- snake: words.map((w) => w.toLowerCase()).join("_"),
686
- kebab: words.map((w) => w.toLowerCase()).join("-")
687
- };
688
- }
689
-
690
- // src/utils/korean-mapper.ts
691
- var KOREAN_KEYWORD_MAP = {
692
- // 공통 동작
693
- create: ["\uC0DD\uC131", "\uB9CC\uB4E4\uAE30", "\uCD94\uAC00"],
694
- read: ["\uC77D\uAE30", "\uC870\uD68C"],
695
- update: ["\uC218\uC815", "\uC5C5\uB370\uC774\uD2B8", "\uBCC0\uACBD"],
696
- delete: ["\uC0AD\uC81C", "\uC81C\uAC70"],
697
- list: ["\uBAA9\uB85D", "\uB9AC\uC2A4\uD2B8"],
698
- search: ["\uAC80\uC0C9", "\uCC3E\uAE30"],
699
- filter: ["\uD544\uD130", "\uD544\uD130\uB9C1"],
700
- sort: ["\uC815\uB82C"],
701
- submit: ["\uC81C\uCD9C", "\uC804\uC1A1"],
702
- cancel: ["\uCDE8\uC18C"],
703
- confirm: ["\uD655\uC778"],
704
- save: ["\uC800\uC7A5"],
705
- load: ["\uB85C\uB4DC", "\uBD88\uB7EC\uC624\uAE30"],
706
- fetch: ["\uAC00\uC838\uC624\uAE30", "\uBD88\uB7EC\uC624\uAE30"],
707
- // UI 요소
708
- button: ["\uBC84\uD2BC"],
709
- modal: ["\uBAA8\uB2EC", "\uD31D\uC5C5"],
710
- dialog: ["\uB2E4\uC774\uC5BC\uB85C\uADF8", "\uB300\uD654\uC0C1\uC790"],
711
- form: ["\uD3FC", "\uC591\uC2DD"],
712
- input: ["\uC785\uB825", "\uC778\uD48B"],
713
- select: ["\uC120\uD0DD", "\uC140\uB809\uD2B8", "\uB4DC\uB86D\uB2E4\uC6B4"],
714
- checkbox: ["\uCCB4\uD06C\uBC15\uC2A4", "\uCCB4\uD06C"],
715
- table: ["\uD14C\uC774\uBE14", "\uD45C"],
716
- card: ["\uCE74\uB4DC"],
717
- tab: ["\uD0ED"],
718
- menu: ["\uBA54\uB274"],
719
- header: ["\uD5E4\uB354", "\uBA38\uB9AC\uAE00"],
720
- footer: ["\uD478\uD130", "\uBC14\uB2E5\uAE00"],
721
- sidebar: ["\uC0AC\uC774\uB4DC\uBC14"],
722
- navbar: ["\uB124\uBE44\uAC8C\uC774\uC158", "\uB124\uBE44\uBC14"],
723
- // 인증/사용자
724
- auth: ["\uC778\uC99D", "\uB85C\uADF8\uC778"],
725
- login: ["\uB85C\uADF8\uC778"],
726
- logout: ["\uB85C\uADF8\uC544\uC6C3"],
727
- register: ["\uD68C\uC6D0\uAC00\uC785", "\uAC00\uC785"],
728
- signup: ["\uD68C\uC6D0\uAC00\uC785", "\uAC00\uC785"],
729
- user: ["\uC0AC\uC6A9\uC790", "\uC720\uC800", "\uD68C\uC6D0"],
730
- profile: ["\uD504\uB85C\uD544"],
731
- password: ["\uBE44\uBC00\uBC88\uD638", "\uC554\uD638"],
732
- permission: ["\uAD8C\uD55C"],
733
- // 비즈니스
734
- attendance: ["\uCD9C\uC11D", "\uCD9C\uACB0"],
735
- check: ["\uCCB4\uD06C", "\uD655\uC778"],
736
- schedule: ["\uC2A4\uCF00\uC904", "\uC77C\uC815"],
737
- calendar: ["\uCE98\uB9B0\uB354", "\uB2EC\uB825"],
738
- notification: ["\uC54C\uB9BC", "\uD1B5\uC9C0"],
739
- message: ["\uBA54\uC2DC\uC9C0", "\uC54C\uB9BC"],
740
- setting: ["\uC124\uC815"],
741
- settings: ["\uC124\uC815"],
742
- payment: ["\uACB0\uC81C", "\uC9C0\uBD88"],
743
- order: ["\uC8FC\uBB38"],
744
- product: ["\uC0C1\uD488", "\uC81C\uD488"],
745
- cart: ["\uC7A5\uBC14\uAD6C\uB2C8"],
746
- checkout: ["\uACB0\uC81C", "\uCCB4\uD06C\uC544\uC6C3"],
747
- invoice: ["\uC1A1\uC7A5", "\uCCAD\uAD6C\uC11C"],
748
- report: ["\uB9AC\uD3EC\uD2B8", "\uBCF4\uACE0\uC11C"],
749
- dashboard: ["\uB300\uC2DC\uBCF4\uB4DC"],
750
- analytics: ["\uBD84\uC11D", "\uD1B5\uACC4"],
751
- statistics: ["\uD1B5\uACC4"],
752
- // 상태
753
- status: ["\uC0C1\uD0DC"],
754
- pending: ["\uB300\uAE30\uC911", "\uB300\uAE30"],
755
- active: ["\uD65C\uC131", "\uD65C\uC131\uD654"],
756
- inactive: ["\uBE44\uD65C\uC131", "\uBE44\uD65C\uC131\uD654"],
757
- completed: ["\uC644\uB8CC"],
758
- error: ["\uC5D0\uB7EC", "\uC624\uB958"],
759
- success: ["\uC131\uACF5"],
760
- loading: ["\uB85C\uB529", "\uB85C\uB4DC\uC911"],
761
- // 기타
762
- date: ["\uB0A0\uC9DC"],
763
- time: ["\uC2DC\uAC04"],
764
- image: ["\uC774\uBBF8\uC9C0", "\uC0AC\uC9C4"],
765
- file: ["\uD30C\uC77C"],
766
- upload: ["\uC5C5\uB85C\uB4DC", "\uC62C\uB9AC\uAE30"],
767
- download: ["\uB2E4\uC6B4\uB85C\uB4DC", "\uB0B4\uB824\uBC1B\uAE30"],
768
- export: ["\uB0B4\uBCF4\uB0B4\uAE30", "\uC775\uC2A4\uD3EC\uD2B8"],
769
- import: ["\uAC00\uC838\uC624\uAE30", "\uC784\uD3EC\uD2B8"],
770
- api: ["API", "\uC5D0\uC774\uD53C\uC544\uC774"],
771
- service: ["\uC11C\uBE44\uC2A4"],
772
- hook: ["\uD6C5"],
773
- component: ["\uCEF4\uD3EC\uB10C\uD2B8"],
774
- page: ["\uD398\uC774\uC9C0"],
775
- route: ["\uB77C\uC6B0\uD2B8", "\uACBD\uB85C"]
776
- };
777
- function findKoreanKeywords(englishKeyword) {
778
- const lower = englishKeyword.toLowerCase();
779
- if (KOREAN_KEYWORD_MAP[lower]) {
780
- return KOREAN_KEYWORD_MAP[lower];
781
- }
782
- const results = [];
783
- for (const [key, values] of Object.entries(KOREAN_KEYWORD_MAP)) {
784
- if (lower.includes(key) || key.includes(lower)) {
785
- results.push(...values);
786
- }
787
- }
788
- return [...new Set(results)];
789
- }
790
- function extendKoreanMap(customMap) {
791
- return {
792
- ...KOREAN_KEYWORD_MAP,
793
- ...customMap
794
- };
795
- }
796
-
797
- // src/core/extractors/keyword-extractor.ts
798
- var KeywordExtractor = class {
799
- constructor(customKoreanMap) {
800
- this.customKoreanMap = customKoreanMap || {};
801
- }
802
- /**
803
- * 다양한 소스에서 키워드 추출
804
- */
805
- extract(name, path5, exports$1 = [], props = []) {
806
- const keywords = /* @__PURE__ */ new Set();
807
- this.extractFromName(name, keywords);
808
- this.extractFromPath(path5, keywords);
809
- for (const exportName of exports$1) {
810
- this.extractFromName(exportName, keywords);
811
- }
812
- for (const propName of props) {
813
- this.extractFromName(propName, keywords);
814
- }
815
- const allEnglishKeywords = [...keywords];
816
- for (const keyword of allEnglishKeywords) {
817
- const koreanKeywords = this.findKorean(keyword);
818
- koreanKeywords.forEach((k) => keywords.add(k));
819
- }
820
- return [...keywords].filter((k) => k.length > 1);
821
- }
822
- /**
823
- * 이름에서 키워드 추출
824
- */
825
- extractFromName(name, keywords) {
826
- keywords.add(name.toLowerCase());
827
- const camelParts = splitCamelCase(name);
828
- camelParts.forEach((part) => keywords.add(part.toLowerCase()));
829
- const pascalParts = splitPascalCase(name);
830
- pascalParts.forEach((part) => keywords.add(part.toLowerCase()));
831
- const snakeParts = splitSnakeCase(name);
832
- snakeParts.forEach((part) => keywords.add(part.toLowerCase()));
833
- const acronyms = extractAcronyms(name);
834
- acronyms.forEach((acr) => keywords.add(acr.toLowerCase()));
835
- }
836
- /**
837
- * 경로에서 키워드 추출
838
- */
839
- extractFromPath(path5, keywords) {
840
- const excludeNames = /* @__PURE__ */ new Set([
841
- "src",
842
- "app",
843
- "components",
844
- "hooks",
845
- "services",
846
- "lib",
847
- "utils",
848
- "pages",
849
- "api"
850
- ]);
851
- const segments = path5.replace(/\.[^/.]+$/, "").split("/").filter((s) => !excludeNames.has(s));
852
- for (const segment of segments) {
853
- this.extractFromName(segment, keywords);
854
- }
855
- }
856
- /**
857
- * 영어 키워드에 대응하는 한글 키워드 찾기
858
- */
859
- findKorean(englishKeyword) {
860
- const customMatch = this.customKoreanMap[englishKeyword.toLowerCase()];
861
- if (customMatch) {
862
- return customMatch;
863
- }
864
- return findKoreanKeywords(englishKeyword);
865
- }
866
- };
867
- var DependencyResolver = class {
868
- constructor(aliasMap = {}, extensions = [".ts", ".tsx", ".js", ".jsx"]) {
869
- this.aliasMap = new Map(Object.entries(aliasMap));
870
- this.extensions = extensions;
871
- }
872
- /**
873
- * import 경로를 실제 파일 경로로 해석
874
- */
875
- resolve(importSource, importerPath, rootDir) {
876
- if (this.isExternalPackage(importSource)) {
877
- return null;
878
- }
879
- const aliasResolved = this.resolveAlias(importSource);
880
- let targetPath;
881
- if (aliasResolved.startsWith("./") || aliasResolved.startsWith("../")) {
882
- const importerDir = path2__namespace.dirname(path2__namespace.resolve(rootDir, importerPath));
883
- targetPath = path2__namespace.resolve(importerDir, aliasResolved);
884
- } else if (aliasResolved !== importSource) {
885
- targetPath = path2__namespace.resolve(rootDir, aliasResolved);
886
- } else {
887
- return null;
888
- }
889
- const resolvedPath = this.resolveWithExtensions(targetPath);
890
- if (resolvedPath) {
891
- return path2__namespace.relative(rootDir, resolvedPath);
892
- }
893
- return null;
894
- }
895
- /**
896
- * 외부 패키지인지 확인
897
- */
898
- isExternalPackage(source) {
899
- if (source.startsWith("./") || source.startsWith("../")) {
900
- return false;
901
- }
902
- for (const alias of this.aliasMap.keys()) {
903
- if (source.startsWith(alias)) {
904
- return false;
905
- }
906
- }
907
- return true;
908
- }
909
- /**
910
- * alias 해석
911
- */
912
- resolveAlias(source) {
913
- for (const [alias, target] of this.aliasMap.entries()) {
914
- if (source === alias) {
915
- return target;
916
- }
917
- if (source.startsWith(alias + "/")) {
918
- return source.replace(alias, target);
919
- }
920
- }
921
- return source;
922
- }
923
- /**
924
- * 확장자를 추가하여 파일 경로 해석
925
- */
926
- resolveWithExtensions(targetPath) {
927
- if (fs__namespace.existsSync(targetPath)) {
928
- try {
929
- const stat = fs__namespace.statSync(targetPath);
930
- if (stat.isFile()) {
931
- return targetPath;
932
- }
933
- if (stat.isDirectory()) {
934
- return this.findIndexFile(targetPath);
935
- }
936
- } catch {
937
- }
938
- }
939
- for (const ext of this.extensions) {
940
- const withExt = targetPath + ext;
941
- if (fs__namespace.existsSync(withExt)) {
942
- return withExt;
943
- }
944
- }
945
- return this.findIndexFile(targetPath);
946
- }
947
- /**
948
- * 디렉토리에서 index 파일 찾기
949
- */
950
- findIndexFile(dirPath) {
951
- for (const ext of this.extensions) {
952
- const indexPath = path2__namespace.join(dirPath, `index${ext}`);
953
- if (fs__namespace.existsSync(indexPath)) {
954
- return indexPath;
955
- }
956
- }
957
- return null;
958
- }
959
- };
960
-
961
- // src/core/resolvers/call-graph-builder.ts
962
- var CallGraphBuilder = class {
963
- constructor(aliasMap) {
964
- const defaultAliases = {
965
- "@": "src",
966
- "@/": "src/",
967
- "~": "src",
968
- "~/": "src/"
969
- };
970
- this.resolver = new DependencyResolver({
971
- ...defaultAliases,
972
- ...aliasMap
973
- });
974
- }
975
- /**
976
- * 파싱된 파일들로부터 호출 그래프 구축
977
- */
978
- build(parsedFiles, rootDir) {
979
- const graph = /* @__PURE__ */ new Map();
980
- const filePathSet = new Set(parsedFiles.map((f) => f.path));
981
- for (const file of parsedFiles) {
982
- const calls = this.resolveCalls(file, rootDir, filePathSet);
983
- graph.set(file.path, {
984
- calls,
985
- calledBy: []
986
- });
987
- }
988
- for (const [filePath, entry] of graph.entries()) {
989
- for (const calledPath of entry.calls) {
990
- const calledEntry = graph.get(calledPath);
991
- if (calledEntry) {
992
- calledEntry.calledBy.push(filePath);
993
- }
994
- }
995
- }
996
- return graph;
997
- }
998
- /**
999
- * 파일이 호출하는 다른 파일들을 해석
1000
- */
1001
- resolveCalls(file, rootDir, validPaths) {
1002
- const calls = [];
1003
- for (const imp of file.imports) {
1004
- if (imp.isTypeOnly) continue;
1005
- const resolvedPath = this.resolver.resolve(
1006
- imp.source,
1007
- file.path,
1008
- rootDir
1009
- );
1010
- if (resolvedPath && validPaths.has(resolvedPath)) {
1011
- calls.push(resolvedPath);
1012
- }
1013
- }
1014
- return [...new Set(calls)];
1015
- }
1016
- };
1017
- function generateId(projectId, filePath) {
1018
- const input = `${projectId}:${filePath}`;
1019
- return crypto__namespace.createHash("sha256").update(input).digest("hex").slice(0, 16);
1020
- }
1021
- var ProjectAnalyzer = class {
1022
- constructor(config) {
1023
- this.config = config;
1024
- this.tsParser = new TypeScriptParser();
1025
- this.sqlParser = new SQLParser();
1026
- this.importExtractor = new ImportExtractor();
1027
- this.exportExtractor = new ExportExtractor();
1028
- this.propsExtractor = new PropsExtractor();
1029
- this.keywordExtractor = new KeywordExtractor(config.koreanKeywords);
1030
- this.callGraphBuilder = new CallGraphBuilder();
1031
- }
1032
- /**
1033
- * 프로젝트 분석 실행
1034
- */
1035
- async analyze(rootDir) {
1036
- const startTime = Date.now();
1037
- const parseErrors = [];
1038
- const files = await this.collectFiles(rootDir);
1039
- if (this.config.verbose) {
1040
- console.log(`[metadata-plugin] Found ${files.length} files to analyze`);
1041
- }
1042
- const parsedFiles = [];
1043
- for (const filePath of files) {
1044
- try {
1045
- const parsed = await this.parseFile(filePath, rootDir);
1046
- if (parsed) {
1047
- parsedFiles.push(parsed);
1048
- }
1049
- } catch (error) {
1050
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
1051
- parseErrors.push(`${filePath}: ${errorMessage}`);
1052
- }
1053
- }
1054
- const callGraph = this.callGraphBuilder.build(parsedFiles, rootDir);
1055
- const items = parsedFiles.map(
1056
- (parsed) => this.createIndexItem(parsed, callGraph)
1057
- );
1058
- const stats = this.calculateStats(items, parseErrors);
1059
- if (this.config.verbose) {
1060
- console.log(
1061
- `[metadata-plugin] Analysis completed in ${Date.now() - startTime}ms`
1062
- );
1063
- console.log(`[metadata-plugin] Processed ${items.length} items`);
1064
- }
1065
- return {
1066
- items,
1067
- stats,
1068
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1069
- };
1070
- }
1071
- /**
1072
- * 대상 파일 수집
1073
- */
1074
- async collectFiles(rootDir) {
1075
- const allFiles = [];
1076
- for (const pattern of this.config.include) {
1077
- const matches = await glob.glob(pattern, {
1078
- cwd: rootDir,
1079
- ignore: this.config.exclude,
1080
- absolute: true
1081
- });
1082
- allFiles.push(...matches);
1083
- }
1084
- return [...new Set(allFiles)];
1085
- }
1086
- /**
1087
- * 단일 파일 파싱
1088
- */
1089
- async parseFile(filePath, rootDir) {
1090
- const relativePath = path2__namespace.relative(rootDir, filePath);
1091
- const fileType = this.determineFileType(relativePath);
1092
- if (!fileType) {
1093
- return null;
1094
- }
1095
- const content = await fs3__namespace.readFile(filePath, "utf-8");
1096
- const ext = path2__namespace.extname(filePath);
1097
- if (ext === ".sql") {
1098
- return this.sqlParser.parse(content, relativePath);
1099
- }
1100
- const sourceFile = this.tsParser.parse(content, filePath);
1101
- const imports = this.importExtractor.extract(sourceFile);
1102
- const exports$1 = this.exportExtractor.extract(sourceFile);
1103
- const props = fileType === "component" ? this.propsExtractor.extract(sourceFile) : void 0;
1104
- return {
1105
- path: relativePath,
1106
- type: fileType,
1107
- name: this.extractName(relativePath, exports$1),
1108
- imports,
1109
- exports: exports$1,
1110
- props
1111
- };
1112
- }
1113
- /**
1114
- * 파일 타입 결정
1115
- */
1116
- determineFileType(relativePath) {
1117
- const sortedPatterns = Object.entries(this.config.fileTypeMapping).sort(
1118
- ([a], [b]) => b.length - a.length
1119
- );
1120
- for (const [pattern, type] of sortedPatterns) {
1121
- const regex = globToRegex(pattern);
1122
- if (regex.test(relativePath)) {
1123
- return type;
1124
- }
1125
- }
1126
- return null;
1127
- }
1128
- /**
1129
- * 파일/컴포넌트 이름 추출
1130
- */
1131
- extractName(relativePath, exports$1) {
1132
- const defaultExport = exports$1.find((e) => e.isDefault);
1133
- if (defaultExport && defaultExport.name !== "default") {
1134
- return defaultExport.name;
1135
- }
1136
- const basename3 = path2__namespace.basename(relativePath, path2__namespace.extname(relativePath));
1137
- if (["index", "page", "layout", "route"].includes(basename3)) {
1138
- const dirname4 = path2__namespace.dirname(relativePath);
1139
- const parentName = path2__namespace.basename(dirname4);
1140
- return parentName !== "." ? parentName : basename3;
1141
- }
1142
- return basename3;
1143
- }
1144
- /**
1145
- * CodeIndexItem 생성
1146
- */
1147
- createIndexItem(parsed, callGraph) {
1148
- const graphEntry = callGraph.get(parsed.path) || {
1149
- calls: [],
1150
- calledBy: []
1151
- };
1152
- const keywords = this.keywordExtractor.extract(
1153
- parsed.name,
1154
- parsed.path,
1155
- parsed.exports.map((e) => e.name),
1156
- parsed.props?.map((p) => p.name)
1157
- );
1158
- const searchText = this.buildSearchText(parsed, keywords);
1159
- return {
1160
- id: generateId(this.config.projectId, parsed.path),
1161
- projectId: this.config.projectId,
1162
- type: parsed.type,
1163
- name: parsed.name,
1164
- path: parsed.path,
1165
- keywords,
1166
- searchText,
1167
- calls: graphEntry.calls,
1168
- calledBy: graphEntry.calledBy,
1169
- metadata: {
1170
- exports: parsed.exports.map((e) => e.name),
1171
- props: parsed.props?.map((p) => p.name),
1172
- ...parsed.metadata
1173
- }
1174
- };
1175
- }
1176
- /**
1177
- * 검색용 텍스트 생성
1178
- */
1179
- buildSearchText(parsed, keywords) {
1180
- const parts = [
1181
- parsed.name,
1182
- parsed.path,
1183
- ...keywords,
1184
- ...parsed.exports.map((e) => e.name),
1185
- ...parsed.props?.map((p) => p.name) || []
1186
- ];
1187
- return parts.join(" ").toLowerCase();
1188
- }
1189
- /**
1190
- * 분석 통계 계산
1191
- */
1192
- calculateStats(items, parseErrors) {
1193
- const byType = {
1194
- route: 0,
1195
- component: 0,
1196
- hook: 0,
1197
- service: 0,
1198
- api: 0,
1199
- table: 0,
1200
- utility: 0
1201
- };
1202
- for (const item of items) {
1203
- byType[item.type]++;
1204
- }
1205
- return {
1206
- totalFiles: items.length,
1207
- byType,
1208
- parseErrors
1209
- };
1210
- }
1211
- };
1212
- var FileWriter = class {
1213
- constructor(config) {
1214
- this.config = config;
1215
- }
1216
- /**
1217
- * 분석 결과를 파일로 저장
1218
- */
1219
- async write(result, outputPath) {
1220
- const dir = path2__namespace.dirname(outputPath);
1221
- await fs3__namespace.mkdir(dir, { recursive: true });
1222
- const output = this.formatOutput(result);
1223
- await fs3__namespace.writeFile(outputPath, output, "utf-8");
1224
- }
1225
- /**
1226
- * 출력 형식 생성
1227
- */
1228
- formatOutput(result) {
1229
- const output = {
1230
- version: "1.0.0",
1231
- projectId: this.config.projectId,
1232
- generatedAt: result.timestamp,
1233
- stats: result.stats,
1234
- items: result.items
1235
- };
1236
- if (this.config.mode === "production") {
1237
- return JSON.stringify(output);
1238
- }
1239
- return JSON.stringify(output, null, 2);
1240
- }
1241
- };
1242
-
1243
- // src/core/output/api-sender.ts
1244
- var ApiSender = class {
1245
- constructor(config, options = {}) {
1246
- this.config = config;
1247
- this.maxRetries = options.maxRetries ?? 3;
1248
- this.retryDelay = options.retryDelay ?? 1e3;
1249
- }
1250
- /**
1251
- * 분석 결과를 API로 전송
1252
- */
1253
- async send(result) {
1254
- const apiConfig = this.config.output.api;
1255
- if (!apiConfig?.enabled || !apiConfig.endpoint) {
1256
- return;
1257
- }
1258
- const payload = {
1259
- projectId: this.config.projectId,
1260
- timestamp: result.timestamp,
1261
- items: result.items,
1262
- stats: result.stats
1263
- };
1264
- let lastError = null;
1265
- for (let attempt = 0; attempt < this.maxRetries; attempt++) {
1266
- try {
1267
- await this.sendRequest(
1268
- apiConfig.endpoint,
1269
- payload,
1270
- apiConfig.headers
1271
- );
1272
- return;
1273
- } catch (error) {
1274
- lastError = error instanceof Error ? error : new Error(String(error));
1275
- if (this.config.verbose) {
1276
- console.warn(
1277
- `[metadata-plugin] API send attempt ${attempt + 1} failed:`,
1278
- lastError.message
1279
- );
1280
- }
1281
- if (attempt < this.maxRetries - 1) {
1282
- await this.delay(this.retryDelay * (attempt + 1));
1283
- }
1284
- }
1285
- }
1286
- throw new Error(
1287
- `Failed to send metadata after ${this.maxRetries} attempts: ${lastError?.message}`
1288
- );
1289
- }
1290
- /**
1291
- * HTTP POST 요청
1292
- */
1293
- async sendRequest(endpoint, payload, headers) {
1294
- const response = await fetch(endpoint, {
1295
- method: "POST",
1296
- headers: {
1297
- "Content-Type": "application/json",
1298
- ...headers
1299
- },
1300
- body: JSON.stringify(payload)
1301
- });
1302
- if (!response.ok) {
1303
- const errorText = await response.text();
1304
- throw new Error(`API request failed: ${response.status} ${errorText}`);
1305
- }
1306
- }
1307
- /**
1308
- * 지연 함수
1309
- */
1310
- delay(ms) {
1311
- return new Promise((resolve2) => setTimeout(resolve2, ms));
1312
- }
1313
- };
1314
- var SupabaseApiSender = class extends ApiSender {
1315
- /**
1316
- * Supabase upsert 형식으로 전송
1317
- */
1318
- async send(result) {
1319
- const apiConfig = this.config.output.api;
1320
- if (!apiConfig?.enabled || !apiConfig.endpoint) {
1321
- return;
1322
- }
1323
- const records = result.items.map((item) => ({
1324
- id: item.id,
1325
- project_id: item.projectId,
1326
- type: item.type,
1327
- name: item.name,
1328
- path: item.path,
1329
- keywords: item.keywords,
1330
- search_text: item.searchText,
1331
- calls: item.calls,
1332
- called_by: item.calledBy,
1333
- metadata: item.metadata,
1334
- updated_at: result.timestamp
1335
- }));
1336
- const batchSize = 500;
1337
- for (let i = 0; i < records.length; i += batchSize) {
1338
- const batch = records.slice(i, i + batchSize);
1339
- const response = await fetch(apiConfig.endpoint, {
1340
- method: "POST",
1341
- headers: {
1342
- "Content-Type": "application/json",
1343
- Prefer: "resolution=merge-duplicates",
1344
- ...apiConfig.headers
1345
- },
1346
- body: JSON.stringify(batch)
1347
- });
1348
- if (!response.ok) {
1349
- throw new Error(`Supabase upsert failed: ${response.status}`);
1350
- }
1351
- }
1352
- }
1353
- };
1354
-
1355
- exports.ApiSender = ApiSender;
1356
- exports.CallGraphBuilder = CallGraphBuilder;
1357
- exports.DEFAULT_EXCLUDE_PATTERNS = DEFAULT_EXCLUDE_PATTERNS;
1358
- exports.DEFAULT_FILE_TYPE_MAPPING = DEFAULT_FILE_TYPE_MAPPING;
1359
- exports.DEFAULT_INCLUDE_PATTERNS = DEFAULT_INCLUDE_PATTERNS;
1360
- exports.DependencyResolver = DependencyResolver;
1361
- exports.ExportExtractor = ExportExtractor;
1362
- exports.FileWriter = FileWriter;
1363
- exports.ImportExtractor = ImportExtractor;
1364
- exports.KOREAN_KEYWORD_MAP = KOREAN_KEYWORD_MAP;
1365
- exports.KeywordExtractor = KeywordExtractor;
1366
- exports.ProjectAnalyzer = ProjectAnalyzer;
1367
- exports.PropsExtractor = PropsExtractor;
1368
- exports.SQLParser = SQLParser;
1369
- exports.SupabaseApiSender = SupabaseApiSender;
1370
- exports.TypeScriptParser = TypeScriptParser;
1371
- exports.createDefaultConfig = createDefaultConfig;
1372
- exports.extendKoreanMap = extendKoreanMap;
1373
- exports.extractAcronyms = extractAcronyms;
1374
- exports.findKoreanKeywords = findKoreanKeywords;
1375
- exports.generateId = generateId;
1376
- exports.splitCamelCase = splitCamelCase;
1377
- exports.splitIntoWords = splitIntoWords;
1378
- exports.splitKebabCase = splitKebabCase;
1379
- exports.splitPascalCase = splitPascalCase;
1380
- exports.splitSnakeCase = splitSnakeCase;
1381
- exports.toAllCases = toAllCases;
1382
- exports.validateConfig = validateConfig;