@spfn/core 0.1.0-alpha.8 → 0.1.0-alpha.81
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/README.md +169 -195
- package/dist/auto-loader-JFaZ9gON.d.ts +80 -0
- package/dist/cache/index.d.ts +211 -0
- package/dist/cache/index.js +992 -0
- package/dist/cache/index.js.map +1 -0
- package/dist/client/index.d.ts +131 -92
- package/dist/client/index.js +93 -85
- package/dist/client/index.js.map +1 -1
- package/dist/codegen/generators/index.d.ts +19 -0
- package/dist/codegen/generators/index.js +1500 -0
- package/dist/codegen/generators/index.js.map +1 -0
- package/dist/codegen/index.d.ts +76 -60
- package/dist/codegen/index.js +1486 -736
- package/dist/codegen/index.js.map +1 -1
- package/dist/database-errors-BNNmLTJE.d.ts +86 -0
- package/dist/db/index.d.ts +844 -44
- package/dist/db/index.js +1262 -1309
- package/dist/db/index.js.map +1 -1
- package/dist/env/index.d.ts +508 -0
- package/dist/env/index.js +1106 -0
- package/dist/env/index.js.map +1 -0
- package/dist/error-handler-wjLL3v-a.d.ts +44 -0
- package/dist/errors/index.d.ts +136 -0
- package/dist/errors/index.js +172 -0
- package/dist/errors/index.js.map +1 -0
- package/dist/index-DHiAqhKv.d.ts +101 -0
- package/dist/index.d.ts +3 -374
- package/dist/index.js +2404 -2179
- package/dist/index.js.map +1 -1
- package/dist/logger/index.d.ts +94 -0
- package/dist/logger/index.js +774 -0
- package/dist/logger/index.js.map +1 -0
- package/dist/middleware/index.d.ts +33 -0
- package/dist/middleware/index.js +897 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/route/index.d.ts +21 -53
- package/dist/route/index.js +1238 -219
- package/dist/route/index.js.map +1 -1
- package/dist/server/index.d.ts +18 -0
- package/dist/server/index.js +2400 -2061
- package/dist/server/index.js.map +1 -1
- package/dist/types-DYueuoD6.d.ts +162 -0
- package/package.json +59 -15
- package/dist/auto-loader-C44TcLmM.d.ts +0 -125
- package/dist/bind-pssq1NRT.d.ts +0 -34
- package/dist/postgres-errors-CY_Es8EJ.d.ts +0 -1703
- package/dist/scripts/index.d.ts +0 -24
- package/dist/scripts/index.js +0 -1201
- package/dist/scripts/index.js.map +0 -1
- package/dist/scripts/templates/api-index.template.txt +0 -10
- package/dist/scripts/templates/api-tag.template.txt +0 -11
- package/dist/scripts/templates/contract.template.txt +0 -87
- package/dist/scripts/templates/entity-type.template.txt +0 -31
- package/dist/scripts/templates/entity.template.txt +0 -19
- package/dist/scripts/templates/index.template.txt +0 -10
- package/dist/scripts/templates/repository.template.txt +0 -37
- package/dist/scripts/templates/routes-id.template.txt +0 -59
- package/dist/scripts/templates/routes-index.template.txt +0 -44
- package/dist/types-SlzTr8ZO.d.ts +0 -143
package/dist/codegen/index.js
CHANGED
|
@@ -1,508 +1,256 @@
|
|
|
1
|
-
import { mkdir, writeFile, readdir, stat } from 'fs/promises';
|
|
2
|
-
import { join, dirname } from 'path';
|
|
3
|
-
import * as ts from 'typescript';
|
|
4
|
-
import { existsSync, mkdirSync, createWriteStream, readFileSync } from 'fs';
|
|
5
1
|
import { watch } from 'chokidar';
|
|
2
|
+
import { join, relative } from 'path';
|
|
3
|
+
import mm from 'micromatch';
|
|
6
4
|
import pino from 'pino';
|
|
5
|
+
import { existsSync, mkdirSync, accessSync, constants, writeFileSync, unlinkSync, createWriteStream, statSync, readdirSync, renameSync, readFileSync } from 'fs';
|
|
6
|
+
import { readdir, stat, mkdir, writeFile } from 'fs/promises';
|
|
7
|
+
import * as ts from 'typescript';
|
|
8
|
+
import { createJiti } from 'jiti';
|
|
7
9
|
|
|
8
|
-
// src/codegen/
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
10
|
+
// src/codegen/core/orchestrator.ts
|
|
11
|
+
var PinoAdapter = class _PinoAdapter {
|
|
12
|
+
logger;
|
|
13
|
+
constructor(config) {
|
|
14
|
+
this.logger = pino({
|
|
15
|
+
level: config.level,
|
|
16
|
+
// 기본 필드
|
|
17
|
+
base: config.module ? { module: config.module } : void 0
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
child(module) {
|
|
21
|
+
const childLogger = new _PinoAdapter({ level: this.logger.level, module });
|
|
22
|
+
childLogger.logger = this.logger.child({ module });
|
|
23
|
+
return childLogger;
|
|
24
|
+
}
|
|
25
|
+
debug(message, context) {
|
|
26
|
+
this.logger.debug(context || {}, message);
|
|
27
|
+
}
|
|
28
|
+
info(message, context) {
|
|
29
|
+
this.logger.info(context || {}, message);
|
|
30
|
+
}
|
|
31
|
+
warn(message, errorOrContext, context) {
|
|
32
|
+
if (errorOrContext instanceof Error) {
|
|
33
|
+
this.logger.warn({ err: errorOrContext, ...context }, message);
|
|
34
|
+
} else {
|
|
35
|
+
this.logger.warn(errorOrContext || {}, message);
|
|
28
36
|
}
|
|
29
37
|
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
for (let i = 0; i < entries.length; i++) {
|
|
36
|
-
const entry = entries[i];
|
|
37
|
-
const fullPath = join(dir, entry);
|
|
38
|
-
const fileStat = await stat(fullPath);
|
|
39
|
-
if (fileStat.isDirectory()) {
|
|
40
|
-
await scanContractFiles(fullPath, files);
|
|
41
|
-
} else if (entry === "contract.ts") {
|
|
42
|
-
files.push(fullPath);
|
|
43
|
-
}
|
|
38
|
+
error(message, errorOrContext, context) {
|
|
39
|
+
if (errorOrContext instanceof Error) {
|
|
40
|
+
this.logger.error({ err: errorOrContext, ...context }, message);
|
|
41
|
+
} else {
|
|
42
|
+
this.logger.error(errorOrContext || {}, message);
|
|
44
43
|
}
|
|
45
|
-
} catch (error) {
|
|
46
44
|
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
filePath,
|
|
53
|
-
sourceCode,
|
|
54
|
-
ts.ScriptTarget.Latest,
|
|
55
|
-
true
|
|
56
|
-
);
|
|
57
|
-
const exports = [];
|
|
58
|
-
function visit(node) {
|
|
59
|
-
if (ts.isVariableStatement(node)) {
|
|
60
|
-
const hasExport = node.modifiers?.some(
|
|
61
|
-
(m) => m.kind === ts.SyntaxKind.ExportKeyword
|
|
62
|
-
);
|
|
63
|
-
if (hasExport && node.declarationList.declarations.length > 0) {
|
|
64
|
-
const declaration = node.declarationList.declarations[0];
|
|
65
|
-
if (ts.isVariableDeclaration(declaration) && ts.isIdentifier(declaration.name) && declaration.initializer && ts.isObjectLiteralExpression(declaration.initializer)) {
|
|
66
|
-
const name = declaration.name.text;
|
|
67
|
-
if (isContractName(name)) {
|
|
68
|
-
const contractData = extractContractData(declaration.initializer);
|
|
69
|
-
if (contractData.method && contractData.path) {
|
|
70
|
-
exports.push({
|
|
71
|
-
name,
|
|
72
|
-
method: contractData.method,
|
|
73
|
-
path: contractData.path
|
|
74
|
-
});
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
}
|
|
45
|
+
fatal(message, errorOrContext, context) {
|
|
46
|
+
if (errorOrContext instanceof Error) {
|
|
47
|
+
this.logger.fatal({ err: errorOrContext, ...context }, message);
|
|
48
|
+
} else {
|
|
49
|
+
this.logger.fatal(errorOrContext || {}, message);
|
|
79
50
|
}
|
|
80
|
-
ts.forEachChild(node, visit);
|
|
81
51
|
}
|
|
82
|
-
|
|
83
|
-
|
|
52
|
+
async close() {
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// src/logger/types.ts
|
|
57
|
+
var LOG_LEVEL_PRIORITY = {
|
|
58
|
+
debug: 0,
|
|
59
|
+
info: 1,
|
|
60
|
+
warn: 2,
|
|
61
|
+
error: 3,
|
|
62
|
+
fatal: 4
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// src/logger/formatters.ts
|
|
66
|
+
var SENSITIVE_KEYS = [
|
|
67
|
+
"password",
|
|
68
|
+
"passwd",
|
|
69
|
+
"pwd",
|
|
70
|
+
"secret",
|
|
71
|
+
"token",
|
|
72
|
+
"apikey",
|
|
73
|
+
"api_key",
|
|
74
|
+
"accesstoken",
|
|
75
|
+
"access_token",
|
|
76
|
+
"refreshtoken",
|
|
77
|
+
"refresh_token",
|
|
78
|
+
"authorization",
|
|
79
|
+
"auth",
|
|
80
|
+
"cookie",
|
|
81
|
+
"session",
|
|
82
|
+
"sessionid",
|
|
83
|
+
"session_id",
|
|
84
|
+
"privatekey",
|
|
85
|
+
"private_key",
|
|
86
|
+
"creditcard",
|
|
87
|
+
"credit_card",
|
|
88
|
+
"cardnumber",
|
|
89
|
+
"card_number",
|
|
90
|
+
"cvv",
|
|
91
|
+
"ssn",
|
|
92
|
+
"pin"
|
|
93
|
+
];
|
|
94
|
+
var MASKED_VALUE = "***MASKED***";
|
|
95
|
+
function isSensitiveKey(key) {
|
|
96
|
+
const lowerKey = key.toLowerCase();
|
|
97
|
+
return SENSITIVE_KEYS.some((sensitive) => lowerKey.includes(sensitive));
|
|
84
98
|
}
|
|
85
|
-
function
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
} else
|
|
100
|
-
|
|
101
|
-
if (ts.isStringLiteral(prop.initializer)) {
|
|
102
|
-
value = prop.initializer.text;
|
|
103
|
-
} else if (ts.isAsExpression(prop.initializer) && ts.isStringLiteral(prop.initializer.expression)) {
|
|
104
|
-
value = prop.initializer.expression.text;
|
|
105
|
-
}
|
|
106
|
-
if (value) result.path = value;
|
|
99
|
+
function maskSensitiveData(data) {
|
|
100
|
+
if (data === null || data === void 0) {
|
|
101
|
+
return data;
|
|
102
|
+
}
|
|
103
|
+
if (Array.isArray(data)) {
|
|
104
|
+
return data.map((item) => maskSensitiveData(item));
|
|
105
|
+
}
|
|
106
|
+
if (typeof data === "object") {
|
|
107
|
+
const masked = {};
|
|
108
|
+
for (const [key, value] of Object.entries(data)) {
|
|
109
|
+
if (isSensitiveKey(key)) {
|
|
110
|
+
masked[key] = MASKED_VALUE;
|
|
111
|
+
} else if (typeof value === "object" && value !== null) {
|
|
112
|
+
masked[key] = maskSensitiveData(value);
|
|
113
|
+
} else {
|
|
114
|
+
masked[key] = value;
|
|
107
115
|
}
|
|
108
116
|
}
|
|
117
|
+
return masked;
|
|
109
118
|
}
|
|
110
|
-
return
|
|
119
|
+
return data;
|
|
111
120
|
}
|
|
112
|
-
|
|
113
|
-
|
|
121
|
+
var COLORS = {
|
|
122
|
+
reset: "\x1B[0m",
|
|
123
|
+
bright: "\x1B[1m",
|
|
124
|
+
dim: "\x1B[2m",
|
|
125
|
+
// 로그 레벨 컬러
|
|
126
|
+
debug: "\x1B[36m",
|
|
127
|
+
// cyan
|
|
128
|
+
info: "\x1B[32m",
|
|
129
|
+
// green
|
|
130
|
+
warn: "\x1B[33m",
|
|
131
|
+
// yellow
|
|
132
|
+
error: "\x1B[31m",
|
|
133
|
+
// red
|
|
134
|
+
fatal: "\x1B[35m",
|
|
135
|
+
// magenta
|
|
136
|
+
// 추가 컬러
|
|
137
|
+
gray: "\x1B[90m"
|
|
138
|
+
};
|
|
139
|
+
function formatTimestamp(date) {
|
|
140
|
+
return date.toISOString();
|
|
141
|
+
}
|
|
142
|
+
function formatTimestampHuman(date) {
|
|
143
|
+
const year = date.getFullYear();
|
|
144
|
+
const month = String(date.getMonth() + 1).padStart(2, "0");
|
|
145
|
+
const day = String(date.getDate()).padStart(2, "0");
|
|
146
|
+
const hours = String(date.getHours()).padStart(2, "0");
|
|
147
|
+
const minutes = String(date.getMinutes()).padStart(2, "0");
|
|
148
|
+
const seconds = String(date.getSeconds()).padStart(2, "0");
|
|
149
|
+
const ms = String(date.getMilliseconds()).padStart(3, "0");
|
|
150
|
+
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${ms}`;
|
|
114
151
|
}
|
|
115
|
-
function
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
152
|
+
function formatError(error) {
|
|
153
|
+
const lines = [];
|
|
154
|
+
lines.push(`${error.name}: ${error.message}`);
|
|
155
|
+
if (error.stack) {
|
|
156
|
+
const stackLines = error.stack.split("\n").slice(1);
|
|
157
|
+
lines.push(...stackLines);
|
|
119
158
|
}
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
159
|
+
return lines.join("\n");
|
|
160
|
+
}
|
|
161
|
+
function formatConsole(metadata, colorize = true) {
|
|
162
|
+
const parts = [];
|
|
163
|
+
const timestamp = formatTimestampHuman(metadata.timestamp);
|
|
164
|
+
if (colorize) {
|
|
165
|
+
parts.push(`${COLORS.gray}[${timestamp}]${COLORS.reset}`);
|
|
166
|
+
} else {
|
|
167
|
+
parts.push(`[${timestamp}]`);
|
|
123
168
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
const seg = segments[i];
|
|
128
|
-
if (seg === "index") {
|
|
129
|
-
continue;
|
|
130
|
-
}
|
|
131
|
-
if (seg.startsWith("[") && seg.endsWith("]")) {
|
|
132
|
-
transformed.push(":" + seg.slice(1, -1));
|
|
169
|
+
if (metadata.module) {
|
|
170
|
+
if (colorize) {
|
|
171
|
+
parts.push(`${COLORS.dim}[module=${metadata.module}]${COLORS.reset}`);
|
|
133
172
|
} else {
|
|
134
|
-
|
|
173
|
+
parts.push(`[module=${metadata.module}]`);
|
|
135
174
|
}
|
|
136
175
|
}
|
|
137
|
-
if (
|
|
138
|
-
|
|
176
|
+
if (metadata.context && Object.keys(metadata.context).length > 0) {
|
|
177
|
+
Object.entries(metadata.context).forEach(([key, value]) => {
|
|
178
|
+
const valueStr = typeof value === "string" ? value : String(value);
|
|
179
|
+
if (colorize) {
|
|
180
|
+
parts.push(`${COLORS.dim}[${key}=${valueStr}]${COLORS.reset}`);
|
|
181
|
+
} else {
|
|
182
|
+
parts.push(`[${key}=${valueStr}]`);
|
|
183
|
+
}
|
|
184
|
+
});
|
|
139
185
|
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
basePath = basePath.slice(0, -1);
|
|
186
|
+
const levelStr = metadata.level.toUpperCase();
|
|
187
|
+
if (colorize) {
|
|
188
|
+
const color = COLORS[metadata.level];
|
|
189
|
+
parts.push(`${color}(${levelStr})${COLORS.reset}:`);
|
|
190
|
+
} else {
|
|
191
|
+
parts.push(`(${levelStr}):`);
|
|
147
192
|
}
|
|
148
|
-
if (
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
return basePath + contractPath;
|
|
193
|
+
if (colorize) {
|
|
194
|
+
parts.push(`${COLORS.bright}${metadata.message}${COLORS.reset}`);
|
|
195
|
+
} else {
|
|
196
|
+
parts.push(metadata.message);
|
|
153
197
|
}
|
|
154
|
-
|
|
155
|
-
|
|
198
|
+
let output = parts.join(" ");
|
|
199
|
+
if (metadata.error) {
|
|
200
|
+
output += "\n" + formatError(metadata.error);
|
|
156
201
|
}
|
|
157
|
-
return
|
|
202
|
+
return output;
|
|
158
203
|
}
|
|
159
|
-
function
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
204
|
+
function formatJSON(metadata) {
|
|
205
|
+
const obj = {
|
|
206
|
+
timestamp: formatTimestamp(metadata.timestamp),
|
|
207
|
+
level: metadata.level,
|
|
208
|
+
message: metadata.message
|
|
209
|
+
};
|
|
210
|
+
if (metadata.module) {
|
|
211
|
+
obj.module = metadata.module;
|
|
163
212
|
}
|
|
164
|
-
if (
|
|
165
|
-
|
|
213
|
+
if (metadata.context) {
|
|
214
|
+
obj.context = metadata.context;
|
|
166
215
|
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
for (let i = 0; i < mappings.length; i++) {
|
|
174
|
-
const mapping = mappings[i];
|
|
175
|
-
const resource = extractResourceName(mapping.path);
|
|
176
|
-
if (!grouped[resource]) {
|
|
177
|
-
grouped[resource] = [];
|
|
178
|
-
}
|
|
179
|
-
grouped[resource].push(mapping);
|
|
216
|
+
if (metadata.error) {
|
|
217
|
+
obj.error = {
|
|
218
|
+
name: metadata.error.name,
|
|
219
|
+
message: metadata.error.message,
|
|
220
|
+
stack: metadata.error.stack
|
|
221
|
+
};
|
|
180
222
|
}
|
|
181
|
-
return
|
|
223
|
+
return JSON.stringify(obj);
|
|
182
224
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
225
|
+
|
|
226
|
+
// src/logger/logger.ts
|
|
227
|
+
var Logger = class _Logger {
|
|
228
|
+
config;
|
|
229
|
+
module;
|
|
230
|
+
constructor(config) {
|
|
231
|
+
this.config = config;
|
|
232
|
+
this.module = config.module;
|
|
191
233
|
}
|
|
192
|
-
|
|
193
|
-
|
|
234
|
+
/**
|
|
235
|
+
* Get current log level
|
|
236
|
+
*/
|
|
237
|
+
get level() {
|
|
238
|
+
return this.config.level;
|
|
194
239
|
}
|
|
195
|
-
|
|
196
|
-
|
|
240
|
+
/**
|
|
241
|
+
* Create child logger (per module)
|
|
242
|
+
*/
|
|
243
|
+
child(module) {
|
|
244
|
+
return new _Logger({
|
|
245
|
+
...this.config,
|
|
246
|
+
module
|
|
247
|
+
});
|
|
197
248
|
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
return result.join("");
|
|
204
|
-
}
|
|
205
|
-
async function generateClient(mappings, options) {
|
|
206
|
-
const startTime = Date.now();
|
|
207
|
-
const grouped = groupByResource(mappings);
|
|
208
|
-
const resourceNames = Object.keys(grouped);
|
|
209
|
-
const code = generateClientCode(mappings, grouped, options);
|
|
210
|
-
await mkdir(dirname(options.outputPath), { recursive: true });
|
|
211
|
-
await writeFile(options.outputPath, code, "utf-8");
|
|
212
|
-
const stats = {
|
|
213
|
-
routesScanned: mappings.length,
|
|
214
|
-
contractsFound: mappings.length,
|
|
215
|
-
contractFiles: countUniqueContractFiles(mappings),
|
|
216
|
-
resourcesGenerated: resourceNames.length,
|
|
217
|
-
methodsGenerated: mappings.length,
|
|
218
|
-
duration: Date.now() - startTime
|
|
219
|
-
};
|
|
220
|
-
return stats;
|
|
221
|
-
}
|
|
222
|
-
function generateClientCode(mappings, grouped, options) {
|
|
223
|
-
let code = "";
|
|
224
|
-
code += generateHeader();
|
|
225
|
-
code += generateImports(mappings, options);
|
|
226
|
-
code += generateApiObject(grouped, options);
|
|
227
|
-
code += generateFooter();
|
|
228
|
-
return code;
|
|
229
|
-
}
|
|
230
|
-
function generateHeader() {
|
|
231
|
-
return `/**
|
|
232
|
-
* Auto-generated API Client
|
|
233
|
-
*
|
|
234
|
-
* Generated by @spfn/core codegen
|
|
235
|
-
* DO NOT EDIT MANUALLY
|
|
236
|
-
*
|
|
237
|
-
* @generated ${(/* @__PURE__ */ new Date()).toISOString()}
|
|
238
|
-
*/
|
|
239
|
-
|
|
240
|
-
`;
|
|
241
|
-
}
|
|
242
|
-
function generateImports(mappings, options) {
|
|
243
|
-
let code = "";
|
|
244
|
-
code += `import { client } from '@spfn/core/client';
|
|
245
|
-
`;
|
|
246
|
-
if (options.includeTypes !== false) {
|
|
247
|
-
code += `import type { InferContract } from '@spfn/core';
|
|
248
|
-
`;
|
|
249
|
-
}
|
|
250
|
-
code += `
|
|
251
|
-
`;
|
|
252
|
-
const importGroups = groupContractsByImportPath(mappings);
|
|
253
|
-
const importPaths = Object.keys(importGroups);
|
|
254
|
-
for (let i = 0; i < importPaths.length; i++) {
|
|
255
|
-
const importPath = importPaths[i];
|
|
256
|
-
const contracts = importGroups[importPath];
|
|
257
|
-
code += `import { ${contracts.join(", ")} } from '${importPath}';
|
|
258
|
-
`;
|
|
259
|
-
}
|
|
260
|
-
code += `
|
|
261
|
-
`;
|
|
262
|
-
return code;
|
|
263
|
-
}
|
|
264
|
-
function groupContractsByImportPath(mappings) {
|
|
265
|
-
const groups = {};
|
|
266
|
-
for (let i = 0; i < mappings.length; i++) {
|
|
267
|
-
const mapping = mappings[i];
|
|
268
|
-
const path = mapping.contractImportPath;
|
|
269
|
-
if (!groups[path]) {
|
|
270
|
-
groups[path] = /* @__PURE__ */ new Set();
|
|
271
|
-
}
|
|
272
|
-
groups[path].add(mapping.contractName);
|
|
273
|
-
}
|
|
274
|
-
const result = {};
|
|
275
|
-
const keys = Object.keys(groups);
|
|
276
|
-
for (let i = 0; i < keys.length; i++) {
|
|
277
|
-
const key = keys[i];
|
|
278
|
-
result[key] = Array.from(groups[key]);
|
|
279
|
-
}
|
|
280
|
-
return result;
|
|
281
|
-
}
|
|
282
|
-
function generateApiObject(grouped, options) {
|
|
283
|
-
let code = "";
|
|
284
|
-
code += `/**
|
|
285
|
-
* Type-safe API client
|
|
286
|
-
*/
|
|
287
|
-
export const api = {
|
|
288
|
-
`;
|
|
289
|
-
const resourceNames = Object.keys(grouped);
|
|
290
|
-
for (let i = 0; i < resourceNames.length; i++) {
|
|
291
|
-
const resourceName = resourceNames[i];
|
|
292
|
-
const routes = grouped[resourceName];
|
|
293
|
-
code += ` ${resourceName}: {
|
|
294
|
-
`;
|
|
295
|
-
for (let j = 0; j < routes.length; j++) {
|
|
296
|
-
const route = routes[j];
|
|
297
|
-
code += generateMethodCode(route, options);
|
|
298
|
-
}
|
|
299
|
-
code += ` }`;
|
|
300
|
-
if (i < resourceNames.length - 1) {
|
|
301
|
-
code += `,`;
|
|
302
|
-
}
|
|
303
|
-
code += `
|
|
304
|
-
`;
|
|
305
|
-
}
|
|
306
|
-
code += `} as const;
|
|
307
|
-
|
|
308
|
-
`;
|
|
309
|
-
return code;
|
|
310
|
-
}
|
|
311
|
-
function generateMethodCode(mapping, options) {
|
|
312
|
-
const methodName = generateMethodName(mapping);
|
|
313
|
-
const contractType = `typeof ${mapping.contractName}`;
|
|
314
|
-
const hasParams = mapping.path.includes(":");
|
|
315
|
-
const hasBody = ["POST", "PUT", "PATCH"].indexOf(mapping.method) !== -1;
|
|
316
|
-
let code = "";
|
|
317
|
-
if (options.includeJsDoc !== false) {
|
|
318
|
-
code += ` /**
|
|
319
|
-
`;
|
|
320
|
-
code += ` * ${mapping.method} ${mapping.path}
|
|
321
|
-
`;
|
|
322
|
-
code += ` */
|
|
323
|
-
`;
|
|
324
|
-
}
|
|
325
|
-
code += ` ${methodName}: (`;
|
|
326
|
-
const params = [];
|
|
327
|
-
if (hasParams) {
|
|
328
|
-
params.push(`params: InferContract<${contractType}>['params']`);
|
|
329
|
-
}
|
|
330
|
-
if (hasBody) {
|
|
331
|
-
params.push(`body: InferContract<${contractType}>['body']`);
|
|
332
|
-
}
|
|
333
|
-
if (params.length > 0) {
|
|
334
|
-
code += `options: { ${params.join(", ")} }`;
|
|
335
|
-
}
|
|
336
|
-
code += `) => `;
|
|
337
|
-
code += `client.call('${mapping.path}', ${mapping.contractName}, `;
|
|
338
|
-
if (params.length > 0) {
|
|
339
|
-
code += `options`;
|
|
340
|
-
} else {
|
|
341
|
-
code += `{}`;
|
|
342
|
-
}
|
|
343
|
-
code += `),
|
|
344
|
-
`;
|
|
345
|
-
return code;
|
|
346
|
-
}
|
|
347
|
-
function generateMethodName(mapping) {
|
|
348
|
-
const method = mapping.method.toLowerCase();
|
|
349
|
-
if (mapping.path === "/" || mapping.path.match(/^\/[\w-]+$/)) {
|
|
350
|
-
if (method === "get") {
|
|
351
|
-
return "list";
|
|
352
|
-
}
|
|
353
|
-
if (method === "post") {
|
|
354
|
-
return "create";
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
if (mapping.path.includes(":")) {
|
|
358
|
-
if (method === "get") {
|
|
359
|
-
return "getById";
|
|
360
|
-
}
|
|
361
|
-
if (method === "put" || method === "patch") {
|
|
362
|
-
return "update";
|
|
363
|
-
}
|
|
364
|
-
if (method === "delete") {
|
|
365
|
-
return "delete";
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
return method;
|
|
369
|
-
}
|
|
370
|
-
function generateFooter() {
|
|
371
|
-
return `/**
|
|
372
|
-
* Export client instance for advanced usage
|
|
373
|
-
*
|
|
374
|
-
* Use this to add interceptors or customize the client:
|
|
375
|
-
*
|
|
376
|
-
* @example
|
|
377
|
-
* \`\`\`ts
|
|
378
|
-
* import { client } from './api';
|
|
379
|
-
* import { createAuthInterceptor } from '@spfn/auth/nextjs';
|
|
380
|
-
* import { NextJSCookieProvider } from '@spfn/auth/nextjs';
|
|
381
|
-
*
|
|
382
|
-
* client.use(createAuthInterceptor({
|
|
383
|
-
* cookieProvider: new NextJSCookieProvider(),
|
|
384
|
-
* encryptionKey: process.env.ENCRYPTION_KEY!
|
|
385
|
-
* }));
|
|
386
|
-
* \`\`\`
|
|
387
|
-
*/
|
|
388
|
-
export { client };
|
|
389
|
-
`;
|
|
390
|
-
}
|
|
391
|
-
function countUniqueContractFiles(mappings) {
|
|
392
|
-
const files = /* @__PURE__ */ new Set();
|
|
393
|
-
for (let i = 0; i < mappings.length; i++) {
|
|
394
|
-
if (mappings[i].contractFile) {
|
|
395
|
-
files.add(mappings[i].contractFile);
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
return files.size;
|
|
399
|
-
}
|
|
400
|
-
var PinoAdapter = class _PinoAdapter {
|
|
401
|
-
logger;
|
|
402
|
-
constructor(config) {
|
|
403
|
-
const isProduction = process.env.NODE_ENV === "production";
|
|
404
|
-
const isDevelopment = process.env.NODE_ENV === "development";
|
|
405
|
-
const fileLoggingEnabled = process.env.LOGGER_FILE_ENABLED === "true";
|
|
406
|
-
const targets = [];
|
|
407
|
-
if (!isProduction && isDevelopment) {
|
|
408
|
-
targets.push({
|
|
409
|
-
target: "pino-pretty",
|
|
410
|
-
level: "debug",
|
|
411
|
-
options: {
|
|
412
|
-
colorize: true,
|
|
413
|
-
translateTime: "SYS:yyyy-mm-dd HH:MM:ss.l",
|
|
414
|
-
ignore: "pid,hostname"
|
|
415
|
-
}
|
|
416
|
-
});
|
|
417
|
-
}
|
|
418
|
-
if (fileLoggingEnabled && isProduction) {
|
|
419
|
-
const logDir = process.env.LOG_DIR || "./logs";
|
|
420
|
-
const maxFileSize = process.env.LOG_MAX_FILE_SIZE || "10M";
|
|
421
|
-
const maxFiles = parseInt(process.env.LOG_MAX_FILES || "10", 10);
|
|
422
|
-
targets.push({
|
|
423
|
-
target: "pino-roll",
|
|
424
|
-
level: "info",
|
|
425
|
-
options: {
|
|
426
|
-
file: `${logDir}/app.log`,
|
|
427
|
-
frequency: "daily",
|
|
428
|
-
size: maxFileSize,
|
|
429
|
-
limit: { count: maxFiles },
|
|
430
|
-
mkdir: true
|
|
431
|
-
}
|
|
432
|
-
});
|
|
433
|
-
}
|
|
434
|
-
this.logger = pino({
|
|
435
|
-
level: config.level,
|
|
436
|
-
// Transport 설정 (targets가 있으면 사용, 없으면 기본 stdout)
|
|
437
|
-
transport: targets.length > 0 ? { targets } : void 0,
|
|
438
|
-
// 기본 필드
|
|
439
|
-
base: config.module ? { module: config.module } : void 0
|
|
440
|
-
});
|
|
441
|
-
}
|
|
442
|
-
child(module) {
|
|
443
|
-
const childLogger = new _PinoAdapter({ level: this.logger.level, module });
|
|
444
|
-
childLogger.logger = this.logger.child({ module });
|
|
445
|
-
return childLogger;
|
|
446
|
-
}
|
|
447
|
-
debug(message, context) {
|
|
448
|
-
this.logger.debug(context || {}, message);
|
|
449
|
-
}
|
|
450
|
-
info(message, context) {
|
|
451
|
-
this.logger.info(context || {}, message);
|
|
452
|
-
}
|
|
453
|
-
warn(message, errorOrContext, context) {
|
|
454
|
-
if (errorOrContext instanceof Error) {
|
|
455
|
-
this.logger.warn({ err: errorOrContext, ...context }, message);
|
|
456
|
-
} else {
|
|
457
|
-
this.logger.warn(errorOrContext || {}, message);
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
error(message, errorOrContext, context) {
|
|
461
|
-
if (errorOrContext instanceof Error) {
|
|
462
|
-
this.logger.error({ err: errorOrContext, ...context }, message);
|
|
463
|
-
} else {
|
|
464
|
-
this.logger.error(errorOrContext || {}, message);
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
fatal(message, errorOrContext, context) {
|
|
468
|
-
if (errorOrContext instanceof Error) {
|
|
469
|
-
this.logger.fatal({ err: errorOrContext, ...context }, message);
|
|
470
|
-
} else {
|
|
471
|
-
this.logger.fatal(errorOrContext || {}, message);
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
async close() {
|
|
475
|
-
}
|
|
476
|
-
};
|
|
477
|
-
|
|
478
|
-
// src/logger/logger.ts
|
|
479
|
-
var Logger = class _Logger {
|
|
480
|
-
config;
|
|
481
|
-
module;
|
|
482
|
-
constructor(config) {
|
|
483
|
-
this.config = config;
|
|
484
|
-
this.module = config.module;
|
|
485
|
-
}
|
|
486
|
-
/**
|
|
487
|
-
* Get current log level
|
|
488
|
-
*/
|
|
489
|
-
get level() {
|
|
490
|
-
return this.config.level;
|
|
491
|
-
}
|
|
492
|
-
/**
|
|
493
|
-
* Create child logger (per module)
|
|
494
|
-
*/
|
|
495
|
-
child(module) {
|
|
496
|
-
return new _Logger({
|
|
497
|
-
...this.config,
|
|
498
|
-
module
|
|
499
|
-
});
|
|
500
|
-
}
|
|
501
|
-
/**
|
|
502
|
-
* Debug log
|
|
503
|
-
*/
|
|
504
|
-
debug(message, context) {
|
|
505
|
-
this.log("debug", message, void 0, context);
|
|
249
|
+
/**
|
|
250
|
+
* Debug log
|
|
251
|
+
*/
|
|
252
|
+
debug(message, context) {
|
|
253
|
+
this.log("debug", message, void 0, context);
|
|
506
254
|
}
|
|
507
255
|
/**
|
|
508
256
|
* Info log
|
|
@@ -535,13 +283,17 @@ var Logger = class _Logger {
|
|
|
535
283
|
* Log processing (internal)
|
|
536
284
|
*/
|
|
537
285
|
log(level, message, error, context) {
|
|
286
|
+
if (LOG_LEVEL_PRIORITY[level] < LOG_LEVEL_PRIORITY[this.config.level]) {
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
538
289
|
const metadata = {
|
|
539
290
|
timestamp: /* @__PURE__ */ new Date(),
|
|
540
291
|
level,
|
|
541
292
|
message,
|
|
542
293
|
module: this.module,
|
|
543
294
|
error,
|
|
544
|
-
context
|
|
295
|
+
// Mask sensitive information in context to prevent credential leaks
|
|
296
|
+
context: context ? maskSensitiveData(context) : void 0
|
|
545
297
|
};
|
|
546
298
|
this.processTransports(metadata);
|
|
547
299
|
}
|
|
@@ -577,157 +329,47 @@ var Logger = class _Logger {
|
|
|
577
329
|
}
|
|
578
330
|
};
|
|
579
331
|
|
|
580
|
-
// src/logger/
|
|
581
|
-
var
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
// 추가 컬러
|
|
606
|
-
gray: "\x1B[90m"
|
|
607
|
-
};
|
|
608
|
-
function colorizeLevel(level) {
|
|
609
|
-
const color = COLORS[level];
|
|
610
|
-
const levelStr = level.toUpperCase().padEnd(5);
|
|
611
|
-
return `${color}${levelStr}${COLORS.reset}`;
|
|
612
|
-
}
|
|
613
|
-
function formatTimestamp(date) {
|
|
614
|
-
return date.toISOString();
|
|
615
|
-
}
|
|
616
|
-
function formatTimestampHuman(date) {
|
|
617
|
-
const year = date.getFullYear();
|
|
618
|
-
const month = String(date.getMonth() + 1).padStart(2, "0");
|
|
619
|
-
const day = String(date.getDate()).padStart(2, "0");
|
|
620
|
-
const hours = String(date.getHours()).padStart(2, "0");
|
|
621
|
-
const minutes = String(date.getMinutes()).padStart(2, "0");
|
|
622
|
-
const seconds = String(date.getSeconds()).padStart(2, "0");
|
|
623
|
-
const ms = String(date.getMilliseconds()).padStart(3, "0");
|
|
624
|
-
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${ms}`;
|
|
625
|
-
}
|
|
626
|
-
function formatError(error) {
|
|
627
|
-
const lines = [];
|
|
628
|
-
lines.push(`${error.name}: ${error.message}`);
|
|
629
|
-
if (error.stack) {
|
|
630
|
-
const stackLines = error.stack.split("\n").slice(1);
|
|
631
|
-
lines.push(...stackLines);
|
|
632
|
-
}
|
|
633
|
-
return lines.join("\n");
|
|
634
|
-
}
|
|
635
|
-
function formatContext(context) {
|
|
636
|
-
try {
|
|
637
|
-
return JSON.stringify(context, null, 2);
|
|
638
|
-
} catch (error) {
|
|
639
|
-
return "[Context serialization failed]";
|
|
640
|
-
}
|
|
641
|
-
}
|
|
642
|
-
function formatConsole(metadata, colorize = true) {
|
|
643
|
-
const parts = [];
|
|
644
|
-
const timestamp = formatTimestampHuman(metadata.timestamp);
|
|
645
|
-
if (colorize) {
|
|
646
|
-
parts.push(`${COLORS.gray}${timestamp}${COLORS.reset}`);
|
|
647
|
-
} else {
|
|
648
|
-
parts.push(timestamp);
|
|
649
|
-
}
|
|
650
|
-
if (colorize) {
|
|
651
|
-
parts.push(colorizeLevel(metadata.level));
|
|
652
|
-
} else {
|
|
653
|
-
parts.push(metadata.level.toUpperCase().padEnd(5));
|
|
654
|
-
}
|
|
655
|
-
if (metadata.module) {
|
|
656
|
-
if (colorize) {
|
|
657
|
-
parts.push(`${COLORS.dim}[${metadata.module}]${COLORS.reset}`);
|
|
658
|
-
} else {
|
|
659
|
-
parts.push(`[${metadata.module}]`);
|
|
660
|
-
}
|
|
661
|
-
}
|
|
662
|
-
parts.push(metadata.message);
|
|
663
|
-
let output = parts.join(" ");
|
|
664
|
-
if (metadata.context && Object.keys(metadata.context).length > 0) {
|
|
665
|
-
output += "\n" + formatContext(metadata.context);
|
|
666
|
-
}
|
|
667
|
-
if (metadata.error) {
|
|
668
|
-
output += "\n" + formatError(metadata.error);
|
|
669
|
-
}
|
|
670
|
-
return output;
|
|
671
|
-
}
|
|
672
|
-
function formatJSON(metadata) {
|
|
673
|
-
const obj = {
|
|
674
|
-
timestamp: formatTimestamp(metadata.timestamp),
|
|
675
|
-
level: metadata.level,
|
|
676
|
-
message: metadata.message
|
|
677
|
-
};
|
|
678
|
-
if (metadata.module) {
|
|
679
|
-
obj.module = metadata.module;
|
|
680
|
-
}
|
|
681
|
-
if (metadata.context) {
|
|
682
|
-
obj.context = metadata.context;
|
|
683
|
-
}
|
|
684
|
-
if (metadata.error) {
|
|
685
|
-
obj.error = {
|
|
686
|
-
name: metadata.error.name,
|
|
687
|
-
message: metadata.error.message,
|
|
688
|
-
stack: metadata.error.stack
|
|
689
|
-
};
|
|
690
|
-
}
|
|
691
|
-
return JSON.stringify(obj);
|
|
692
|
-
}
|
|
693
|
-
|
|
694
|
-
// src/logger/transports/console.ts
|
|
695
|
-
var ConsoleTransport = class {
|
|
696
|
-
name = "console";
|
|
697
|
-
level;
|
|
698
|
-
enabled;
|
|
699
|
-
colorize;
|
|
700
|
-
constructor(config) {
|
|
701
|
-
this.level = config.level;
|
|
702
|
-
this.enabled = config.enabled;
|
|
703
|
-
this.colorize = config.colorize ?? true;
|
|
704
|
-
}
|
|
705
|
-
async log(metadata) {
|
|
706
|
-
if (!this.enabled) {
|
|
707
|
-
return;
|
|
708
|
-
}
|
|
709
|
-
if (LOG_LEVEL_PRIORITY[metadata.level] < LOG_LEVEL_PRIORITY[this.level]) {
|
|
710
|
-
return;
|
|
711
|
-
}
|
|
712
|
-
const message = formatConsole(metadata, this.colorize);
|
|
713
|
-
if (metadata.level === "warn" || metadata.level === "error" || metadata.level === "fatal") {
|
|
714
|
-
console.error(message);
|
|
715
|
-
} else {
|
|
716
|
-
console.log(message);
|
|
717
|
-
}
|
|
718
|
-
}
|
|
332
|
+
// src/logger/transports/console.ts
|
|
333
|
+
var ConsoleTransport = class {
|
|
334
|
+
name = "console";
|
|
335
|
+
level;
|
|
336
|
+
enabled;
|
|
337
|
+
colorize;
|
|
338
|
+
constructor(config) {
|
|
339
|
+
this.level = config.level;
|
|
340
|
+
this.enabled = config.enabled;
|
|
341
|
+
this.colorize = config.colorize ?? true;
|
|
342
|
+
}
|
|
343
|
+
async log(metadata) {
|
|
344
|
+
if (!this.enabled) {
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
if (LOG_LEVEL_PRIORITY[metadata.level] < LOG_LEVEL_PRIORITY[this.level]) {
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
const message = formatConsole(metadata, this.colorize);
|
|
351
|
+
if (metadata.level === "warn" || metadata.level === "error" || metadata.level === "fatal") {
|
|
352
|
+
console.error(message);
|
|
353
|
+
} else {
|
|
354
|
+
console.log(message);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
719
357
|
};
|
|
720
358
|
var FileTransport = class {
|
|
721
359
|
name = "file";
|
|
722
360
|
level;
|
|
723
361
|
enabled;
|
|
724
362
|
logDir;
|
|
363
|
+
maxFileSize;
|
|
364
|
+
maxFiles;
|
|
725
365
|
currentStream = null;
|
|
726
366
|
currentFilename = null;
|
|
727
367
|
constructor(config) {
|
|
728
368
|
this.level = config.level;
|
|
729
369
|
this.enabled = config.enabled;
|
|
730
370
|
this.logDir = config.logDir;
|
|
371
|
+
this.maxFileSize = config.maxFileSize ?? 10 * 1024 * 1024;
|
|
372
|
+
this.maxFiles = config.maxFiles ?? 10;
|
|
731
373
|
if (!existsSync(this.logDir)) {
|
|
732
374
|
mkdirSync(this.logDir, { recursive: true });
|
|
733
375
|
}
|
|
@@ -743,6 +385,9 @@ var FileTransport = class {
|
|
|
743
385
|
const filename = this.getLogFilename(metadata.timestamp);
|
|
744
386
|
if (this.currentFilename !== filename) {
|
|
745
387
|
await this.rotateStream(filename);
|
|
388
|
+
await this.cleanOldFiles();
|
|
389
|
+
} else if (this.currentFilename) {
|
|
390
|
+
await this.checkAndRotateBySize();
|
|
746
391
|
}
|
|
747
392
|
if (this.currentStream) {
|
|
748
393
|
return new Promise((resolve, reject) => {
|
|
@@ -798,6 +443,103 @@ var FileTransport = class {
|
|
|
798
443
|
});
|
|
799
444
|
});
|
|
800
445
|
}
|
|
446
|
+
/**
|
|
447
|
+
* 파일 크기 체크 및 크기 기반 로테이션
|
|
448
|
+
*/
|
|
449
|
+
async checkAndRotateBySize() {
|
|
450
|
+
if (!this.currentFilename) {
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
const filepath = join(this.logDir, this.currentFilename);
|
|
454
|
+
if (!existsSync(filepath)) {
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
try {
|
|
458
|
+
const stats = statSync(filepath);
|
|
459
|
+
if (stats.size >= this.maxFileSize) {
|
|
460
|
+
await this.rotateBySize();
|
|
461
|
+
}
|
|
462
|
+
} catch (error) {
|
|
463
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
464
|
+
process.stderr.write(`[FileTransport] Failed to check file size: ${errorMessage}
|
|
465
|
+
`);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* 크기 기반 로테이션 수행
|
|
470
|
+
* 예: 2025-01-01.log -> 2025-01-01.1.log, 2025-01-01.1.log -> 2025-01-01.2.log
|
|
471
|
+
*/
|
|
472
|
+
async rotateBySize() {
|
|
473
|
+
if (!this.currentFilename) {
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
await this.closeStream();
|
|
477
|
+
const baseName = this.currentFilename.replace(/\.log$/, "");
|
|
478
|
+
const files = readdirSync(this.logDir);
|
|
479
|
+
const relatedFiles = files.filter((file) => file.startsWith(baseName) && file.endsWith(".log")).sort().reverse();
|
|
480
|
+
for (const file of relatedFiles) {
|
|
481
|
+
const match = file.match(/\.(\d+)\.log$/);
|
|
482
|
+
if (match) {
|
|
483
|
+
const oldNum = parseInt(match[1], 10);
|
|
484
|
+
const newNum = oldNum + 1;
|
|
485
|
+
const oldPath = join(this.logDir, file);
|
|
486
|
+
const newPath2 = join(this.logDir, `${baseName}.${newNum}.log`);
|
|
487
|
+
try {
|
|
488
|
+
renameSync(oldPath, newPath2);
|
|
489
|
+
} catch (error) {
|
|
490
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
491
|
+
process.stderr.write(`[FileTransport] Failed to rotate file: ${errorMessage}
|
|
492
|
+
`);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
const currentPath = join(this.logDir, this.currentFilename);
|
|
497
|
+
const newPath = join(this.logDir, `${baseName}.1.log`);
|
|
498
|
+
try {
|
|
499
|
+
if (existsSync(currentPath)) {
|
|
500
|
+
renameSync(currentPath, newPath);
|
|
501
|
+
}
|
|
502
|
+
} catch (error) {
|
|
503
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
504
|
+
process.stderr.write(`[FileTransport] Failed to rotate current file: ${errorMessage}
|
|
505
|
+
`);
|
|
506
|
+
}
|
|
507
|
+
await this.rotateStream(this.currentFilename);
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* 오래된 로그 파일 정리
|
|
511
|
+
* maxFiles 개수를 초과하는 로그 파일 삭제
|
|
512
|
+
*/
|
|
513
|
+
async cleanOldFiles() {
|
|
514
|
+
try {
|
|
515
|
+
if (!existsSync(this.logDir)) {
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
const files = readdirSync(this.logDir);
|
|
519
|
+
const logFiles = files.filter((file) => file.endsWith(".log")).map((file) => {
|
|
520
|
+
const filepath = join(this.logDir, file);
|
|
521
|
+
const stats = statSync(filepath);
|
|
522
|
+
return { file, mtime: stats.mtime };
|
|
523
|
+
}).sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
|
|
524
|
+
if (logFiles.length > this.maxFiles) {
|
|
525
|
+
const filesToDelete = logFiles.slice(this.maxFiles);
|
|
526
|
+
for (const { file } of filesToDelete) {
|
|
527
|
+
const filepath = join(this.logDir, file);
|
|
528
|
+
try {
|
|
529
|
+
unlinkSync(filepath);
|
|
530
|
+
} catch (error) {
|
|
531
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
532
|
+
process.stderr.write(`[FileTransport] Failed to delete old file "${file}": ${errorMessage}
|
|
533
|
+
`);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
} catch (error) {
|
|
538
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
539
|
+
process.stderr.write(`[FileTransport] Failed to clean old files: ${errorMessage}
|
|
540
|
+
`);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
801
543
|
/**
|
|
802
544
|
* 날짜별 로그 파일명 생성
|
|
803
545
|
*/
|
|
@@ -811,8 +553,9 @@ var FileTransport = class {
|
|
|
811
553
|
await this.closeStream();
|
|
812
554
|
}
|
|
813
555
|
};
|
|
814
|
-
|
|
815
|
-
|
|
556
|
+
function isFileLoggingEnabled() {
|
|
557
|
+
return process.env.LOGGER_FILE_ENABLED === "true";
|
|
558
|
+
}
|
|
816
559
|
function getDefaultLogLevel() {
|
|
817
560
|
const isProduction = process.env.NODE_ENV === "production";
|
|
818
561
|
const isDevelopment = process.env.NODE_ENV === "development";
|
|
@@ -845,6 +588,109 @@ function getFileConfig() {
|
|
|
845
588
|
maxFiles: 10
|
|
846
589
|
};
|
|
847
590
|
}
|
|
591
|
+
function validateDirectoryWritable(dirPath) {
|
|
592
|
+
if (!existsSync(dirPath)) {
|
|
593
|
+
try {
|
|
594
|
+
mkdirSync(dirPath, { recursive: true });
|
|
595
|
+
} catch (error) {
|
|
596
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
597
|
+
throw new Error(`Failed to create log directory "${dirPath}": ${errorMessage}`);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
try {
|
|
601
|
+
accessSync(dirPath, constants.W_OK);
|
|
602
|
+
} catch {
|
|
603
|
+
throw new Error(`Log directory "${dirPath}" is not writable. Please check permissions.`);
|
|
604
|
+
}
|
|
605
|
+
const testFile = join(dirPath, ".logger-write-test");
|
|
606
|
+
try {
|
|
607
|
+
writeFileSync(testFile, "test", "utf-8");
|
|
608
|
+
unlinkSync(testFile);
|
|
609
|
+
} catch (error) {
|
|
610
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
611
|
+
throw new Error(`Cannot write to log directory "${dirPath}": ${errorMessage}`);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
function validateFileConfig() {
|
|
615
|
+
if (!isFileLoggingEnabled()) {
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
const logDir = process.env.LOG_DIR;
|
|
619
|
+
if (!logDir) {
|
|
620
|
+
throw new Error(
|
|
621
|
+
"LOG_DIR environment variable is required when LOGGER_FILE_ENABLED=true. Example: LOG_DIR=/var/log/myapp"
|
|
622
|
+
);
|
|
623
|
+
}
|
|
624
|
+
validateDirectoryWritable(logDir);
|
|
625
|
+
}
|
|
626
|
+
function validateSlackConfig() {
|
|
627
|
+
const webhookUrl = process.env.SLACK_WEBHOOK_URL;
|
|
628
|
+
if (!webhookUrl) {
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
if (!webhookUrl.startsWith("https://hooks.slack.com/")) {
|
|
632
|
+
throw new Error(
|
|
633
|
+
`Invalid SLACK_WEBHOOK_URL: "${webhookUrl}". Slack webhook URLs must start with "https://hooks.slack.com/"`
|
|
634
|
+
);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
function validateEmailConfig() {
|
|
638
|
+
const smtpHost = process.env.SMTP_HOST;
|
|
639
|
+
const smtpPort = process.env.SMTP_PORT;
|
|
640
|
+
const emailFrom = process.env.EMAIL_FROM;
|
|
641
|
+
const emailTo = process.env.EMAIL_TO;
|
|
642
|
+
const hasAnyEmailConfig = smtpHost || smtpPort || emailFrom || emailTo;
|
|
643
|
+
if (!hasAnyEmailConfig) {
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
const missingFields = [];
|
|
647
|
+
if (!smtpHost) missingFields.push("SMTP_HOST");
|
|
648
|
+
if (!smtpPort) missingFields.push("SMTP_PORT");
|
|
649
|
+
if (!emailFrom) missingFields.push("EMAIL_FROM");
|
|
650
|
+
if (!emailTo) missingFields.push("EMAIL_TO");
|
|
651
|
+
if (missingFields.length > 0) {
|
|
652
|
+
throw new Error(
|
|
653
|
+
`Email transport configuration incomplete. Missing: ${missingFields.join(", ")}. Either set all required fields or remove all email configuration.`
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
const port = parseInt(smtpPort, 10);
|
|
657
|
+
if (isNaN(port) || port < 1 || port > 65535) {
|
|
658
|
+
throw new Error(
|
|
659
|
+
`Invalid SMTP_PORT: "${smtpPort}". Must be a number between 1 and 65535.`
|
|
660
|
+
);
|
|
661
|
+
}
|
|
662
|
+
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
663
|
+
if (!emailRegex.test(emailFrom)) {
|
|
664
|
+
throw new Error(`Invalid EMAIL_FROM format: "${emailFrom}"`);
|
|
665
|
+
}
|
|
666
|
+
const recipients = emailTo.split(",").map((e) => e.trim());
|
|
667
|
+
for (const email of recipients) {
|
|
668
|
+
if (!emailRegex.test(email)) {
|
|
669
|
+
throw new Error(`Invalid email address in EMAIL_TO: "${email}"`);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
function validateEnvironment() {
|
|
674
|
+
const nodeEnv = process.env.NODE_ENV;
|
|
675
|
+
if (!nodeEnv) {
|
|
676
|
+
process.stderr.write(
|
|
677
|
+
"[Logger] Warning: NODE_ENV is not set. Defaulting to test environment.\n"
|
|
678
|
+
);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
function validateConfig() {
|
|
682
|
+
try {
|
|
683
|
+
validateEnvironment();
|
|
684
|
+
validateFileConfig();
|
|
685
|
+
validateSlackConfig();
|
|
686
|
+
validateEmailConfig();
|
|
687
|
+
} catch (error) {
|
|
688
|
+
if (error instanceof Error) {
|
|
689
|
+
throw new Error(`[Logger] Configuration validation failed: ${error.message}`);
|
|
690
|
+
}
|
|
691
|
+
throw error;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
848
694
|
|
|
849
695
|
// src/logger/adapters/custom.ts
|
|
850
696
|
function initializeTransports() {
|
|
@@ -855,161 +701,1065 @@ function initializeTransports() {
|
|
|
855
701
|
if (fileConfig.enabled) {
|
|
856
702
|
transports.push(new FileTransport(fileConfig));
|
|
857
703
|
}
|
|
858
|
-
return transports;
|
|
704
|
+
return transports;
|
|
705
|
+
}
|
|
706
|
+
var CustomAdapter = class _CustomAdapter {
|
|
707
|
+
logger;
|
|
708
|
+
constructor(config) {
|
|
709
|
+
this.logger = new Logger({
|
|
710
|
+
level: config.level,
|
|
711
|
+
module: config.module,
|
|
712
|
+
transports: initializeTransports()
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
child(module) {
|
|
716
|
+
const adapter = new _CustomAdapter({ level: this.logger.level, module });
|
|
717
|
+
adapter.logger = this.logger.child(module);
|
|
718
|
+
return adapter;
|
|
719
|
+
}
|
|
720
|
+
debug(message, context) {
|
|
721
|
+
this.logger.debug(message, context);
|
|
722
|
+
}
|
|
723
|
+
info(message, context) {
|
|
724
|
+
this.logger.info(message, context);
|
|
725
|
+
}
|
|
726
|
+
warn(message, errorOrContext, context) {
|
|
727
|
+
if (errorOrContext instanceof Error) {
|
|
728
|
+
this.logger.warn(message, errorOrContext, context);
|
|
729
|
+
} else {
|
|
730
|
+
this.logger.warn(message, errorOrContext);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
error(message, errorOrContext, context) {
|
|
734
|
+
if (errorOrContext instanceof Error) {
|
|
735
|
+
this.logger.error(message, errorOrContext, context);
|
|
736
|
+
} else {
|
|
737
|
+
this.logger.error(message, errorOrContext);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
fatal(message, errorOrContext, context) {
|
|
741
|
+
if (errorOrContext instanceof Error) {
|
|
742
|
+
this.logger.fatal(message, errorOrContext, context);
|
|
743
|
+
} else {
|
|
744
|
+
this.logger.fatal(message, errorOrContext);
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
async close() {
|
|
748
|
+
await this.logger.close();
|
|
749
|
+
}
|
|
750
|
+
};
|
|
751
|
+
|
|
752
|
+
// src/logger/adapter-factory.ts
|
|
753
|
+
function createAdapter(type) {
|
|
754
|
+
const level = getDefaultLogLevel();
|
|
755
|
+
switch (type) {
|
|
756
|
+
case "pino":
|
|
757
|
+
return new PinoAdapter({ level });
|
|
758
|
+
case "custom":
|
|
759
|
+
return new CustomAdapter({ level });
|
|
760
|
+
default:
|
|
761
|
+
return new PinoAdapter({ level });
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
function getAdapterType() {
|
|
765
|
+
const adapterEnv = process.env.LOGGER_ADAPTER;
|
|
766
|
+
if (adapterEnv === "custom" || adapterEnv === "pino") {
|
|
767
|
+
return adapterEnv;
|
|
768
|
+
}
|
|
769
|
+
return "pino";
|
|
770
|
+
}
|
|
771
|
+
function initializeLogger() {
|
|
772
|
+
validateConfig();
|
|
773
|
+
return createAdapter(getAdapterType());
|
|
774
|
+
}
|
|
775
|
+
var logger = initializeLogger();
|
|
776
|
+
|
|
777
|
+
// src/codegen/core/orchestrator.ts
|
|
778
|
+
var orchestratorLogger = logger.child("orchestrator");
|
|
779
|
+
var CodegenOrchestrator = class {
|
|
780
|
+
generators;
|
|
781
|
+
cwd;
|
|
782
|
+
debug;
|
|
783
|
+
isGenerating = false;
|
|
784
|
+
pendingRegenerations = /* @__PURE__ */ new Set();
|
|
785
|
+
constructor(options) {
|
|
786
|
+
this.generators = options.generators;
|
|
787
|
+
this.cwd = options.cwd ?? process.cwd();
|
|
788
|
+
this.debug = options.debug ?? false;
|
|
789
|
+
}
|
|
790
|
+
/**
|
|
791
|
+
* Check if generator should run for given trigger
|
|
792
|
+
*/
|
|
793
|
+
shouldRun(generator, trigger) {
|
|
794
|
+
const runOn = generator.runOn ?? ["watch", "manual", "build"];
|
|
795
|
+
return runOn.includes(trigger);
|
|
796
|
+
}
|
|
797
|
+
/**
|
|
798
|
+
* Run all generators once
|
|
799
|
+
*
|
|
800
|
+
* @param trigger - How the generators are being triggered
|
|
801
|
+
*/
|
|
802
|
+
async generateAll(trigger = "manual") {
|
|
803
|
+
if (this.debug) {
|
|
804
|
+
orchestratorLogger.info("Running all generators", {
|
|
805
|
+
count: this.generators.length,
|
|
806
|
+
names: this.generators.map((g) => g.name),
|
|
807
|
+
trigger
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
for (const generator of this.generators) {
|
|
811
|
+
if (!this.shouldRun(generator, trigger)) {
|
|
812
|
+
if (this.debug) {
|
|
813
|
+
orchestratorLogger.info(`[${generator.name}] Skipped (runOn: ${generator.runOn?.join(", ") ?? "default"})`);
|
|
814
|
+
}
|
|
815
|
+
continue;
|
|
816
|
+
}
|
|
817
|
+
try {
|
|
818
|
+
const genOptions = {
|
|
819
|
+
cwd: this.cwd,
|
|
820
|
+
debug: this.debug,
|
|
821
|
+
trigger: {
|
|
822
|
+
type: trigger
|
|
823
|
+
}
|
|
824
|
+
};
|
|
825
|
+
await generator.generate(genOptions);
|
|
826
|
+
if (this.debug) {
|
|
827
|
+
orchestratorLogger.info(`[${generator.name}] Generated successfully`);
|
|
828
|
+
}
|
|
829
|
+
} catch (error) {
|
|
830
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
831
|
+
orchestratorLogger.error(`[${generator.name}] Generation failed`, err);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Start watch mode
|
|
837
|
+
*/
|
|
838
|
+
async watch() {
|
|
839
|
+
await this.generateAll("watch");
|
|
840
|
+
const allPatterns = this.generators.flatMap((g) => g.watchPatterns);
|
|
841
|
+
if (allPatterns.length === 0) {
|
|
842
|
+
orchestratorLogger.warn("No watch patterns defined, exiting watch mode");
|
|
843
|
+
return;
|
|
844
|
+
}
|
|
845
|
+
const dirsToWatch = /* @__PURE__ */ new Set();
|
|
846
|
+
for (const pattern of allPatterns) {
|
|
847
|
+
const baseDir = pattern.split("**")[0].replace(/\/$/, "") || ".";
|
|
848
|
+
dirsToWatch.add(join(this.cwd, baseDir));
|
|
849
|
+
}
|
|
850
|
+
const watchDirs = Array.from(dirsToWatch);
|
|
851
|
+
if (this.debug) {
|
|
852
|
+
orchestratorLogger.info("Starting watch mode", {
|
|
853
|
+
patterns: allPatterns,
|
|
854
|
+
watchDirs,
|
|
855
|
+
cwd: this.cwd
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
const watcher = watch(watchDirs, {
|
|
859
|
+
ignored: /(^|[\/\\])\../,
|
|
860
|
+
// ignore dotfiles
|
|
861
|
+
persistent: true,
|
|
862
|
+
ignoreInitial: true,
|
|
863
|
+
awaitWriteFinish: {
|
|
864
|
+
stabilityThreshold: 100,
|
|
865
|
+
pollInterval: 50
|
|
866
|
+
}
|
|
867
|
+
});
|
|
868
|
+
const handleChange = async (absolutePath, event) => {
|
|
869
|
+
const filePath = relative(this.cwd, absolutePath);
|
|
870
|
+
if (this.isGenerating) {
|
|
871
|
+
this.pendingRegenerations.add(absolutePath);
|
|
872
|
+
return;
|
|
873
|
+
}
|
|
874
|
+
this.isGenerating = true;
|
|
875
|
+
this.pendingRegenerations.clear();
|
|
876
|
+
if (this.debug) {
|
|
877
|
+
orchestratorLogger.info(`File ${event}`, { file: filePath });
|
|
878
|
+
}
|
|
879
|
+
for (const generator of this.generators) {
|
|
880
|
+
if (!this.shouldRun(generator, "watch")) {
|
|
881
|
+
continue;
|
|
882
|
+
}
|
|
883
|
+
const matches = generator.watchPatterns.some(
|
|
884
|
+
(pattern) => mm.isMatch(filePath, pattern)
|
|
885
|
+
);
|
|
886
|
+
if (matches) {
|
|
887
|
+
try {
|
|
888
|
+
const genOptions = {
|
|
889
|
+
cwd: this.cwd,
|
|
890
|
+
debug: this.debug,
|
|
891
|
+
trigger: {
|
|
892
|
+
type: "watch",
|
|
893
|
+
changedFile: {
|
|
894
|
+
path: filePath,
|
|
895
|
+
event
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
};
|
|
899
|
+
await generator.generate(genOptions);
|
|
900
|
+
if (this.debug) {
|
|
901
|
+
orchestratorLogger.info(`[${generator.name}] Regenerated`);
|
|
902
|
+
}
|
|
903
|
+
} catch (error) {
|
|
904
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
905
|
+
orchestratorLogger.error(`[${generator.name}] Regeneration failed`, err);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
this.isGenerating = false;
|
|
910
|
+
if (this.pendingRegenerations.size > 0) {
|
|
911
|
+
const next = Array.from(this.pendingRegenerations)[0];
|
|
912
|
+
await handleChange(next, "change");
|
|
913
|
+
}
|
|
914
|
+
};
|
|
915
|
+
watcher.on("add", (path) => handleChange(path, "add")).on("change", (path) => handleChange(path, "change")).on("unlink", (path) => handleChange(path, "unlink"));
|
|
916
|
+
process.on("SIGINT", () => {
|
|
917
|
+
if (this.debug) {
|
|
918
|
+
orchestratorLogger.info("Shutting down watch mode");
|
|
919
|
+
}
|
|
920
|
+
watcher.close();
|
|
921
|
+
process.exit(0);
|
|
922
|
+
});
|
|
923
|
+
await new Promise(() => {
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
var scannerLogger = logger.child("contract-scanner");
|
|
928
|
+
async function scanContracts(contractsDir, packagePrefix) {
|
|
929
|
+
scannerLogger.debug("Starting contract scan", { contractsDir, packagePrefix });
|
|
930
|
+
const contractFiles = await scanContractFiles(contractsDir);
|
|
931
|
+
scannerLogger.debug("Found contract files", { count: contractFiles.length, files: contractFiles });
|
|
932
|
+
const mappings = [];
|
|
933
|
+
for (let i = 0; i < contractFiles.length; i++) {
|
|
934
|
+
const filePath = contractFiles[i];
|
|
935
|
+
scannerLogger.debug("Extracting contracts from file", { filePath });
|
|
936
|
+
const exports = extractContractExports(filePath);
|
|
937
|
+
scannerLogger.debug("Extracted contracts", { filePath, count: exports.length, contracts: exports.map((e) => e.name) });
|
|
938
|
+
for (let j = 0; j < exports.length; j++) {
|
|
939
|
+
const contractExport = exports[j];
|
|
940
|
+
scannerLogger.debug("Processing contract", { name: contractExport.name, method: contractExport.method, path: contractExport.path });
|
|
941
|
+
if (!contractExport.path.startsWith("/")) {
|
|
942
|
+
throw new Error(
|
|
943
|
+
`Contract '${contractExport.name}' in ${filePath} must use absolute path. Found: '${contractExport.path}'. Use '/your-path' instead.`
|
|
944
|
+
);
|
|
945
|
+
}
|
|
946
|
+
if (packagePrefix && !contractExport.path.startsWith(packagePrefix)) {
|
|
947
|
+
throw new Error(
|
|
948
|
+
`Contract '${contractExport.name}' in ${filePath} must include package prefix. Expected path to start with '${packagePrefix}', but found: '${contractExport.path}'. Example: path: '${packagePrefix}/${contractExport.path}'`
|
|
949
|
+
);
|
|
950
|
+
}
|
|
951
|
+
mappings.push({
|
|
952
|
+
method: contractExport.method,
|
|
953
|
+
path: contractExport.path,
|
|
954
|
+
contractName: contractExport.name,
|
|
955
|
+
contractImportPath: getImportPath(filePath),
|
|
956
|
+
routeFile: "",
|
|
957
|
+
contractFile: filePath,
|
|
958
|
+
hasQuery: contractExport.hasQuery,
|
|
959
|
+
hasBody: contractExport.hasBody,
|
|
960
|
+
hasParams: contractExport.hasParams
|
|
961
|
+
});
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
scannerLogger.info("Contract scan completed", { totalMappings: mappings.length });
|
|
965
|
+
return mappings;
|
|
966
|
+
}
|
|
967
|
+
async function scanContractFiles(dir, files = []) {
|
|
968
|
+
try {
|
|
969
|
+
const entries = await readdir(dir);
|
|
970
|
+
for (let i = 0; i < entries.length; i++) {
|
|
971
|
+
const entry = entries[i];
|
|
972
|
+
const fullPath = join(dir, entry);
|
|
973
|
+
const fileStat = await stat(fullPath);
|
|
974
|
+
if (fileStat.isDirectory()) {
|
|
975
|
+
await scanContractFiles(fullPath, files);
|
|
976
|
+
} else {
|
|
977
|
+
if ((entry.endsWith(".ts") || entry.endsWith(".js") || entry.endsWith(".mjs")) && !entry.endsWith(".d.ts") && !entry.endsWith(".test.ts") && !entry.endsWith(".test.js") && !entry.endsWith(".test.mjs")) {
|
|
978
|
+
files.push(fullPath);
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
} catch (error) {
|
|
983
|
+
}
|
|
984
|
+
return files;
|
|
985
|
+
}
|
|
986
|
+
function extractContractExports(filePath) {
|
|
987
|
+
const sourceCode = readFileSync(filePath, "utf-8");
|
|
988
|
+
const sourceFile = ts.createSourceFile(
|
|
989
|
+
filePath,
|
|
990
|
+
sourceCode,
|
|
991
|
+
ts.ScriptTarget.Latest,
|
|
992
|
+
true
|
|
993
|
+
);
|
|
994
|
+
const exports = [];
|
|
995
|
+
function visit(node) {
|
|
996
|
+
if (ts.isVariableStatement(node)) {
|
|
997
|
+
const hasExport = node.modifiers?.some(
|
|
998
|
+
(m) => m.kind === ts.SyntaxKind.ExportKeyword
|
|
999
|
+
);
|
|
1000
|
+
if (hasExport && node.declarationList.declarations.length > 0) {
|
|
1001
|
+
const declaration = node.declarationList.declarations[0];
|
|
1002
|
+
if (ts.isVariableDeclaration(declaration) && ts.isIdentifier(declaration.name) && declaration.initializer) {
|
|
1003
|
+
const name = declaration.name.text;
|
|
1004
|
+
const hasSatisfiesRouteContract = checkSatisfiesRouteContract(declaration.initializer);
|
|
1005
|
+
if (hasSatisfiesRouteContract) {
|
|
1006
|
+
const objectLiteral = extractObjectLiteral(declaration.initializer);
|
|
1007
|
+
if (objectLiteral) {
|
|
1008
|
+
const contractData = extractContractData(objectLiteral);
|
|
1009
|
+
if (contractData.method && contractData.path) {
|
|
1010
|
+
exports.push({
|
|
1011
|
+
name,
|
|
1012
|
+
method: contractData.method,
|
|
1013
|
+
path: contractData.path,
|
|
1014
|
+
hasQuery: contractData.hasQuery,
|
|
1015
|
+
hasBody: contractData.hasBody,
|
|
1016
|
+
hasParams: contractData.hasParams
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
if (isContractName(name)) {
|
|
1023
|
+
const objectLiteral = extractObjectLiteral(declaration.initializer);
|
|
1024
|
+
if (objectLiteral) {
|
|
1025
|
+
const contractData = extractContractData(objectLiteral);
|
|
1026
|
+
if (contractData.method && contractData.path) {
|
|
1027
|
+
exports.push({
|
|
1028
|
+
name,
|
|
1029
|
+
method: contractData.method,
|
|
1030
|
+
path: contractData.path,
|
|
1031
|
+
hasQuery: contractData.hasQuery,
|
|
1032
|
+
hasBody: contractData.hasBody,
|
|
1033
|
+
hasParams: contractData.hasParams
|
|
1034
|
+
});
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
ts.forEachChild(node, visit);
|
|
1042
|
+
}
|
|
1043
|
+
visit(sourceFile);
|
|
1044
|
+
return exports;
|
|
1045
|
+
}
|
|
1046
|
+
function checkSatisfiesRouteContract(initializer) {
|
|
1047
|
+
if (!ts.isSatisfiesExpression(initializer)) {
|
|
1048
|
+
return false;
|
|
1049
|
+
}
|
|
1050
|
+
const typeNode = initializer.type;
|
|
1051
|
+
if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {
|
|
1052
|
+
return typeNode.typeName.text === "RouteContract";
|
|
1053
|
+
}
|
|
1054
|
+
return false;
|
|
1055
|
+
}
|
|
1056
|
+
function extractObjectLiteral(initializer) {
|
|
1057
|
+
if (ts.isObjectLiteralExpression(initializer)) {
|
|
1058
|
+
return initializer;
|
|
1059
|
+
}
|
|
1060
|
+
if (ts.isSatisfiesExpression(initializer)) {
|
|
1061
|
+
return extractObjectLiteral(initializer.expression);
|
|
1062
|
+
}
|
|
1063
|
+
if (ts.isAsExpression(initializer)) {
|
|
1064
|
+
return extractObjectLiteral(initializer.expression);
|
|
1065
|
+
}
|
|
1066
|
+
return void 0;
|
|
1067
|
+
}
|
|
1068
|
+
function extractContractData(objectLiteral) {
|
|
1069
|
+
const result = {};
|
|
1070
|
+
for (let i = 0; i < objectLiteral.properties.length; i++) {
|
|
1071
|
+
const prop = objectLiteral.properties[i];
|
|
1072
|
+
if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
|
|
1073
|
+
const propName = prop.name.text;
|
|
1074
|
+
if (propName === "method") {
|
|
1075
|
+
let value;
|
|
1076
|
+
if (ts.isStringLiteral(prop.initializer)) {
|
|
1077
|
+
value = prop.initializer.text;
|
|
1078
|
+
} else if (ts.isAsExpression(prop.initializer) && ts.isStringLiteral(prop.initializer.expression)) {
|
|
1079
|
+
value = prop.initializer.expression.text;
|
|
1080
|
+
}
|
|
1081
|
+
if (value) result.method = value;
|
|
1082
|
+
} else if (propName === "path") {
|
|
1083
|
+
let value;
|
|
1084
|
+
if (ts.isStringLiteral(prop.initializer)) {
|
|
1085
|
+
value = prop.initializer.text;
|
|
1086
|
+
} else if (ts.isAsExpression(prop.initializer) && ts.isStringLiteral(prop.initializer.expression)) {
|
|
1087
|
+
value = prop.initializer.expression.text;
|
|
1088
|
+
}
|
|
1089
|
+
if (value) result.path = value;
|
|
1090
|
+
} else if (propName === "query") {
|
|
1091
|
+
result.hasQuery = true;
|
|
1092
|
+
} else if (propName === "body") {
|
|
1093
|
+
result.hasBody = true;
|
|
1094
|
+
} else if (propName === "params") {
|
|
1095
|
+
result.hasParams = true;
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
return result;
|
|
1100
|
+
}
|
|
1101
|
+
function isContractName(name) {
|
|
1102
|
+
return name.indexOf("Contract") !== -1 || name.indexOf("contract") !== -1 || name.endsWith("Schema") || name.endsWith("schema");
|
|
1103
|
+
}
|
|
1104
|
+
function getImportPath(filePath) {
|
|
1105
|
+
const srcIndex = filePath.indexOf("/src/");
|
|
1106
|
+
if (srcIndex === -1) {
|
|
1107
|
+
throw new Error(`Cannot determine import path for ${filePath}: /src/ directory not found`);
|
|
1108
|
+
}
|
|
1109
|
+
let cleanPath = filePath.substring(srcIndex + 5);
|
|
1110
|
+
if (cleanPath.endsWith(".ts")) {
|
|
1111
|
+
cleanPath = cleanPath.slice(0, -3);
|
|
1112
|
+
} else if (cleanPath.endsWith(".js")) {
|
|
1113
|
+
cleanPath = cleanPath.slice(0, -3);
|
|
1114
|
+
} else if (cleanPath.endsWith(".mjs")) {
|
|
1115
|
+
cleanPath = cleanPath.slice(0, -4);
|
|
1116
|
+
}
|
|
1117
|
+
return "@/" + cleanPath;
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
// src/codegen/built-in/contract/helpers.ts
|
|
1121
|
+
function groupByResource(mappings) {
|
|
1122
|
+
const grouped = {};
|
|
1123
|
+
for (let i = 0; i < mappings.length; i++) {
|
|
1124
|
+
const mapping = mappings[i];
|
|
1125
|
+
const resource = extractResourceName(mapping.path);
|
|
1126
|
+
if (!grouped[resource]) {
|
|
1127
|
+
grouped[resource] = [];
|
|
1128
|
+
}
|
|
1129
|
+
grouped[resource].push(mapping);
|
|
1130
|
+
}
|
|
1131
|
+
return grouped;
|
|
1132
|
+
}
|
|
1133
|
+
function extractResourceName(path) {
|
|
1134
|
+
let processedPath = path;
|
|
1135
|
+
if (!processedPath.startsWith("/")) {
|
|
1136
|
+
processedPath = "/" + processedPath;
|
|
1137
|
+
}
|
|
1138
|
+
const segments = processedPath.slice(1).split("/").filter((s) => s && s !== "*");
|
|
1139
|
+
const staticSegments = [];
|
|
1140
|
+
for (let i = 0; i < segments.length; i++) {
|
|
1141
|
+
const seg = segments[i];
|
|
1142
|
+
if (!seg.startsWith(":")) {
|
|
1143
|
+
staticSegments.push(seg);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
if (staticSegments.length === 0) {
|
|
1147
|
+
return "root";
|
|
1148
|
+
}
|
|
1149
|
+
const first = toCamelCase(staticSegments[0], false);
|
|
1150
|
+
if (staticSegments.length === 1) {
|
|
1151
|
+
return first;
|
|
1152
|
+
}
|
|
1153
|
+
const result = [first];
|
|
1154
|
+
for (let i = 1; i < staticSegments.length; i++) {
|
|
1155
|
+
const seg = staticSegments[i];
|
|
1156
|
+
result.push(toCamelCase(seg, true));
|
|
1157
|
+
}
|
|
1158
|
+
return result.join("");
|
|
1159
|
+
}
|
|
1160
|
+
function toCamelCase(str, capitalize2) {
|
|
1161
|
+
const parts = str.split(/[-_]/);
|
|
1162
|
+
if (parts.length === 1) {
|
|
1163
|
+
return capitalize2 ? str.charAt(0).toUpperCase() + str.slice(1) : str;
|
|
1164
|
+
}
|
|
1165
|
+
const result = [];
|
|
1166
|
+
for (let i = 0; i < parts.length; i++) {
|
|
1167
|
+
const part = parts[i];
|
|
1168
|
+
if (i === 0 && !capitalize2) {
|
|
1169
|
+
result.push(part);
|
|
1170
|
+
} else {
|
|
1171
|
+
result.push(part.charAt(0).toUpperCase() + part.slice(1));
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
return result.join("");
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
// src/codegen/built-in/contract/emitter.ts
|
|
1178
|
+
async function generateClient(mappings, options) {
|
|
1179
|
+
const startTime = Date.now();
|
|
1180
|
+
const grouped = groupByResource(mappings);
|
|
1181
|
+
const resourceNames = Object.keys(grouped);
|
|
1182
|
+
await generateSplitClient(mappings, grouped, options);
|
|
1183
|
+
return {
|
|
1184
|
+
routesScanned: mappings.length,
|
|
1185
|
+
contractsFound: mappings.length,
|
|
1186
|
+
contractFiles: countUniqueContractFiles(mappings),
|
|
1187
|
+
resourcesGenerated: resourceNames.length,
|
|
1188
|
+
methodsGenerated: mappings.length,
|
|
1189
|
+
duration: Date.now() - startTime
|
|
1190
|
+
};
|
|
1191
|
+
}
|
|
1192
|
+
function generateHeader() {
|
|
1193
|
+
return `/**
|
|
1194
|
+
* Auto-generated API Client
|
|
1195
|
+
*
|
|
1196
|
+
* Generated by @spfn/core codegen
|
|
1197
|
+
* DO NOT EDIT MANUALLY
|
|
1198
|
+
*
|
|
1199
|
+
* @generated ${(/* @__PURE__ */ new Date()).toISOString()}
|
|
1200
|
+
*/
|
|
1201
|
+
|
|
1202
|
+
`;
|
|
1203
|
+
}
|
|
1204
|
+
function groupContractsByImportPath(mappings) {
|
|
1205
|
+
const groups = {};
|
|
1206
|
+
for (let i = 0; i < mappings.length; i++) {
|
|
1207
|
+
const mapping = mappings[i];
|
|
1208
|
+
const path = mapping.contractImportPath;
|
|
1209
|
+
if (!groups[path]) {
|
|
1210
|
+
groups[path] = /* @__PURE__ */ new Set();
|
|
1211
|
+
}
|
|
1212
|
+
groups[path].add(mapping.contractName);
|
|
1213
|
+
}
|
|
1214
|
+
const result = {};
|
|
1215
|
+
const keys = Object.keys(groups);
|
|
1216
|
+
for (let i = 0; i < keys.length; i++) {
|
|
1217
|
+
const key = keys[i];
|
|
1218
|
+
result[key] = Array.from(groups[key]);
|
|
1219
|
+
}
|
|
1220
|
+
return result;
|
|
859
1221
|
}
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
level: config.level,
|
|
865
|
-
module: config.module,
|
|
866
|
-
transports: initializeTransports()
|
|
867
|
-
});
|
|
1222
|
+
function generateTypeName(mapping) {
|
|
1223
|
+
let name = mapping.contractName;
|
|
1224
|
+
if (name.endsWith("Contract")) {
|
|
1225
|
+
name = name.slice(0, -8);
|
|
868
1226
|
}
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
adapter.logger = this.logger.child(module);
|
|
872
|
-
return adapter;
|
|
1227
|
+
if (name.length > 0) {
|
|
1228
|
+
name = name.charAt(0).toUpperCase() + name.slice(1);
|
|
873
1229
|
}
|
|
874
|
-
|
|
875
|
-
|
|
1230
|
+
return name;
|
|
1231
|
+
}
|
|
1232
|
+
function generateFunctionName(mapping) {
|
|
1233
|
+
let name = mapping.contractName;
|
|
1234
|
+
if (name.endsWith("Contract")) {
|
|
1235
|
+
name = name.slice(0, -8);
|
|
876
1236
|
}
|
|
877
|
-
|
|
878
|
-
|
|
1237
|
+
return name;
|
|
1238
|
+
}
|
|
1239
|
+
function generateFunctionCode(mapping, options) {
|
|
1240
|
+
const functionName = generateFunctionName(mapping);
|
|
1241
|
+
const hasParams = mapping.hasParams || mapping.path.includes(":");
|
|
1242
|
+
const hasQuery = mapping.hasQuery || false;
|
|
1243
|
+
const hasBody = mapping.hasBody || false;
|
|
1244
|
+
let code = "";
|
|
1245
|
+
if (options.includeJsDoc !== false) {
|
|
1246
|
+
code += `/**
|
|
1247
|
+
`;
|
|
1248
|
+
code += ` * ${mapping.method} ${mapping.path}
|
|
1249
|
+
`;
|
|
1250
|
+
code += ` */
|
|
1251
|
+
`;
|
|
879
1252
|
}
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
1253
|
+
code += `export const ${functionName} = (`;
|
|
1254
|
+
const params = [];
|
|
1255
|
+
const typeName = generateTypeName(mapping);
|
|
1256
|
+
if (hasParams) {
|
|
1257
|
+
params.push(`params: ${typeName}Params`);
|
|
1258
|
+
}
|
|
1259
|
+
if (hasQuery) {
|
|
1260
|
+
params.push(`query?: ${typeName}Query`);
|
|
1261
|
+
}
|
|
1262
|
+
if (hasBody) {
|
|
1263
|
+
params.push(`body: ${typeName}Body`);
|
|
1264
|
+
}
|
|
1265
|
+
if (params.length > 0) {
|
|
1266
|
+
code += `options: { ${params.join(", ")} }`;
|
|
1267
|
+
}
|
|
1268
|
+
code += `) => `;
|
|
1269
|
+
code += `client.call(${mapping.contractName}`;
|
|
1270
|
+
if (params.length > 0) {
|
|
1271
|
+
code += `, options`;
|
|
1272
|
+
}
|
|
1273
|
+
code += `);
|
|
1274
|
+
|
|
1275
|
+
`;
|
|
1276
|
+
return code;
|
|
1277
|
+
}
|
|
1278
|
+
function countUniqueContractFiles(mappings) {
|
|
1279
|
+
const files = /* @__PURE__ */ new Set();
|
|
1280
|
+
for (let i = 0; i < mappings.length; i++) {
|
|
1281
|
+
if (mappings[i].contractFile) {
|
|
1282
|
+
files.add(mappings[i].contractFile);
|
|
885
1283
|
}
|
|
886
1284
|
}
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
1285
|
+
return files.size;
|
|
1286
|
+
}
|
|
1287
|
+
function toKebabCase(str) {
|
|
1288
|
+
if (str.length === 0) {
|
|
1289
|
+
return str;
|
|
1290
|
+
}
|
|
1291
|
+
return str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
|
|
1292
|
+
}
|
|
1293
|
+
async function generateSplitClient(_mappings, grouped, options) {
|
|
1294
|
+
const outputPath = options.outputPath;
|
|
1295
|
+
const outputDir = outputPath.endsWith(".ts") || outputPath.endsWith(".js") ? outputPath.replace(/\.[jt]s$/, "") : outputPath;
|
|
1296
|
+
await mkdir(outputDir, { recursive: true });
|
|
1297
|
+
const resourceNames = Object.keys(grouped);
|
|
1298
|
+
for (let i = 0; i < resourceNames.length; i++) {
|
|
1299
|
+
const resourceName = resourceNames[i];
|
|
1300
|
+
const routes = grouped[resourceName];
|
|
1301
|
+
const code = generateResourceFile(resourceName, routes, options);
|
|
1302
|
+
const kebabName = toKebabCase(resourceName);
|
|
1303
|
+
const filePath = `${outputDir}/${kebabName}.ts`;
|
|
1304
|
+
await writeFile(filePath, code, "utf-8");
|
|
1305
|
+
}
|
|
1306
|
+
const indexCode = generateIndexFile(grouped, options);
|
|
1307
|
+
const indexPath = `${outputDir}/index.ts`;
|
|
1308
|
+
await writeFile(indexPath, indexCode, "utf-8");
|
|
1309
|
+
}
|
|
1310
|
+
function generateResourceFile(_resourceName, routes, options) {
|
|
1311
|
+
let code = "";
|
|
1312
|
+
code += generateHeader();
|
|
1313
|
+
code += `import { client } from '@spfn/core/client';
|
|
1314
|
+
`;
|
|
1315
|
+
if (options.includeTypes !== false) {
|
|
1316
|
+
code += `import type { InferContract } from '@spfn/core';
|
|
1317
|
+
`;
|
|
1318
|
+
}
|
|
1319
|
+
code += `
|
|
1320
|
+
`;
|
|
1321
|
+
const importGroups = groupContractsByImportPath(routes);
|
|
1322
|
+
const importPaths = Object.keys(importGroups);
|
|
1323
|
+
for (let i = 0; i < importPaths.length; i++) {
|
|
1324
|
+
const importPath = importPaths[i];
|
|
1325
|
+
const contracts = importGroups[importPath];
|
|
1326
|
+
code += `import { ${contracts.join(", ")} } from '${importPath}';
|
|
1327
|
+
`;
|
|
1328
|
+
}
|
|
1329
|
+
code += `
|
|
1330
|
+
`;
|
|
1331
|
+
if (options.includeTypes !== false) {
|
|
1332
|
+
code += `// ============================================
|
|
1333
|
+
`;
|
|
1334
|
+
code += `// Types
|
|
1335
|
+
`;
|
|
1336
|
+
code += `// ============================================
|
|
1337
|
+
|
|
1338
|
+
`;
|
|
1339
|
+
for (let i = 0; i < routes.length; i++) {
|
|
1340
|
+
const route = routes[i];
|
|
1341
|
+
const typeName = generateTypeName(route);
|
|
1342
|
+
const contractType = `typeof ${route.contractName}`;
|
|
1343
|
+
code += `export type ${typeName}Response = InferContract<${contractType}>['response'];
|
|
1344
|
+
`;
|
|
1345
|
+
if (route.hasQuery) {
|
|
1346
|
+
code += `export type ${typeName}Query = InferContract<${contractType}>['query'];
|
|
1347
|
+
`;
|
|
1348
|
+
}
|
|
1349
|
+
if (route.hasParams || route.path.includes(":")) {
|
|
1350
|
+
code += `export type ${typeName}Params = InferContract<${contractType}>['params'];
|
|
1351
|
+
`;
|
|
1352
|
+
}
|
|
1353
|
+
if (route.hasBody) {
|
|
1354
|
+
code += `export type ${typeName}Body = InferContract<${contractType}>['body'];
|
|
1355
|
+
`;
|
|
1356
|
+
}
|
|
1357
|
+
code += `
|
|
1358
|
+
`;
|
|
892
1359
|
}
|
|
893
1360
|
}
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
1361
|
+
code += `// ============================================
|
|
1362
|
+
`;
|
|
1363
|
+
code += `// API Functions
|
|
1364
|
+
`;
|
|
1365
|
+
code += `// ============================================
|
|
1366
|
+
|
|
1367
|
+
`;
|
|
1368
|
+
for (let i = 0; i < routes.length; i++) {
|
|
1369
|
+
const route = routes[i];
|
|
1370
|
+
code += generateFunctionCode(route, options);
|
|
1371
|
+
}
|
|
1372
|
+
return code;
|
|
1373
|
+
}
|
|
1374
|
+
function generateIndexFile(grouped, options) {
|
|
1375
|
+
let code = "";
|
|
1376
|
+
const apiName = options.apiName || "api";
|
|
1377
|
+
const resourceNames = Object.keys(grouped);
|
|
1378
|
+
code += generateHeader();
|
|
1379
|
+
code += `export { client } from '@spfn/core/client';
|
|
1380
|
+
|
|
1381
|
+
`;
|
|
1382
|
+
for (let i = 0; i < resourceNames.length; i++) {
|
|
1383
|
+
const resourceName = resourceNames[i];
|
|
1384
|
+
const routes = grouped[resourceName];
|
|
1385
|
+
const kebabName = toKebabCase(resourceName);
|
|
1386
|
+
const typeNames = [];
|
|
1387
|
+
for (let j = 0; j < routes.length; j++) {
|
|
1388
|
+
const route = routes[j];
|
|
1389
|
+
const typeName = generateTypeName(route);
|
|
1390
|
+
typeNames.push(`${typeName}Response`);
|
|
1391
|
+
if (route.hasQuery) {
|
|
1392
|
+
typeNames.push(`${typeName}Query`);
|
|
1393
|
+
}
|
|
1394
|
+
if (route.hasParams || route.path.includes(":")) {
|
|
1395
|
+
typeNames.push(`${typeName}Params`);
|
|
1396
|
+
}
|
|
1397
|
+
if (route.hasBody) {
|
|
1398
|
+
typeNames.push(`${typeName}Body`);
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
if (typeNames.length > 0) {
|
|
1402
|
+
code += `export type { ${typeNames.join(", ")} } from './${kebabName}';
|
|
1403
|
+
`;
|
|
899
1404
|
}
|
|
900
1405
|
}
|
|
901
|
-
|
|
902
|
-
|
|
1406
|
+
code += `
|
|
1407
|
+
`;
|
|
1408
|
+
for (let i = 0; i < resourceNames.length; i++) {
|
|
1409
|
+
const resourceName = resourceNames[i];
|
|
1410
|
+
const routes = grouped[resourceName];
|
|
1411
|
+
const kebabName = toKebabCase(resourceName);
|
|
1412
|
+
const functionNames = routes.map((route) => generateFunctionName(route));
|
|
1413
|
+
code += `import { ${functionNames.join(", ")} } from './${kebabName}';
|
|
1414
|
+
`;
|
|
903
1415
|
}
|
|
904
|
-
|
|
1416
|
+
code += `
|
|
1417
|
+
`;
|
|
1418
|
+
code += `/**
|
|
1419
|
+
`;
|
|
1420
|
+
code += ` * Type-safe API client
|
|
1421
|
+
`;
|
|
1422
|
+
code += ` */
|
|
1423
|
+
`;
|
|
1424
|
+
code += `export const ${apiName} = {
|
|
1425
|
+
`;
|
|
1426
|
+
let isFirst = true;
|
|
1427
|
+
for (let i = 0; i < resourceNames.length; i++) {
|
|
1428
|
+
const resourceName = resourceNames[i];
|
|
1429
|
+
const routes = grouped[resourceName];
|
|
1430
|
+
for (let j = 0; j < routes.length; j++) {
|
|
1431
|
+
const route = routes[j];
|
|
1432
|
+
const functionName = generateFunctionName(route);
|
|
1433
|
+
if (!isFirst) {
|
|
1434
|
+
code += `,
|
|
1435
|
+
`;
|
|
1436
|
+
}
|
|
1437
|
+
code += ` ${functionName}`;
|
|
1438
|
+
isFirst = false;
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
code += `
|
|
1442
|
+
} as const;
|
|
1443
|
+
`;
|
|
1444
|
+
return code;
|
|
1445
|
+
}
|
|
905
1446
|
|
|
906
|
-
// src/
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
1447
|
+
// src/codegen/built-in/contract/index.ts
|
|
1448
|
+
var contractLogger = logger.child("contract-gen");
|
|
1449
|
+
var DEFAULT_CONTRACTS_DIR = "src/lib/contracts";
|
|
1450
|
+
var DEFAULT_OUTPUT_PATH = "src/lib/api";
|
|
1451
|
+
var contractCache = null;
|
|
1452
|
+
function needsFullRegeneration(event) {
|
|
1453
|
+
if (event === "add" || event === "unlink") {
|
|
1454
|
+
return true;
|
|
1455
|
+
}
|
|
1456
|
+
if (!contractCache) {
|
|
1457
|
+
return true;
|
|
1458
|
+
}
|
|
1459
|
+
return false;
|
|
1460
|
+
}
|
|
1461
|
+
function createClientOptions(contractsDir, outputPath, baseUrl, apiName) {
|
|
1462
|
+
return {
|
|
1463
|
+
routesDir: contractsDir,
|
|
1464
|
+
outputPath,
|
|
1465
|
+
baseUrl,
|
|
1466
|
+
apiName,
|
|
1467
|
+
includeTypes: true,
|
|
1468
|
+
includeJsDoc: true,
|
|
1469
|
+
splitByResource: true
|
|
1470
|
+
};
|
|
1471
|
+
}
|
|
1472
|
+
function generateApiName(prefix) {
|
|
1473
|
+
if (!prefix || prefix === "/api") {
|
|
1474
|
+
return "api";
|
|
916
1475
|
}
|
|
1476
|
+
const name = prefix.replace(/^\/[_-]?/, "").replace(/[_-]/g, "");
|
|
1477
|
+
if (!name) {
|
|
1478
|
+
return "api";
|
|
1479
|
+
}
|
|
1480
|
+
return `${name}Api`;
|
|
917
1481
|
}
|
|
918
|
-
function
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
1482
|
+
function readPrefixFromPackageJson(cwd) {
|
|
1483
|
+
try {
|
|
1484
|
+
const packageJsonPath = join(cwd, "package.json");
|
|
1485
|
+
if (!existsSync(packageJsonPath)) {
|
|
1486
|
+
return void 0;
|
|
1487
|
+
}
|
|
1488
|
+
const content = readFileSync(packageJsonPath, "utf-8");
|
|
1489
|
+
const packageJson = JSON.parse(content);
|
|
1490
|
+
return packageJson.spfn?.prefix;
|
|
1491
|
+
} catch (error) {
|
|
1492
|
+
return void 0;
|
|
922
1493
|
}
|
|
923
|
-
return "pino";
|
|
924
1494
|
}
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
1495
|
+
function createContractGenerator(config = {}) {
|
|
1496
|
+
const contractsDir = config.contractsDir ?? DEFAULT_CONTRACTS_DIR;
|
|
1497
|
+
const outputPath = config.outputPath ?? DEFAULT_OUTPUT_PATH;
|
|
1498
|
+
const runOn = config.runOn ?? ["watch", "manual", "build"];
|
|
1499
|
+
return {
|
|
1500
|
+
name: "contract",
|
|
1501
|
+
watchPatterns: [
|
|
1502
|
+
`${contractsDir}/**/*.ts`
|
|
1503
|
+
],
|
|
1504
|
+
runOn,
|
|
1505
|
+
async generate(options) {
|
|
1506
|
+
const cwd = options.cwd;
|
|
1507
|
+
const fullContractsDir = join(cwd, contractsDir);
|
|
1508
|
+
const fullOutputPath = join(cwd, outputPath);
|
|
1509
|
+
const prefix = readPrefixFromPackageJson(cwd);
|
|
1510
|
+
const apiName = generateApiName(prefix);
|
|
1511
|
+
try {
|
|
1512
|
+
if (!existsSync(fullContractsDir)) {
|
|
1513
|
+
if (options.debug) {
|
|
1514
|
+
contractLogger.warn(`No contracts directory found at ${contractsDir}`);
|
|
1515
|
+
}
|
|
1516
|
+
return;
|
|
1517
|
+
}
|
|
1518
|
+
const changedFile = options.trigger?.changedFile;
|
|
1519
|
+
if (changedFile && !needsFullRegeneration(changedFile.event)) {
|
|
1520
|
+
if (options.debug) {
|
|
1521
|
+
contractLogger.info("Attempting incremental update", {
|
|
1522
|
+
file: changedFile.path,
|
|
1523
|
+
event: changedFile.event
|
|
1524
|
+
});
|
|
1525
|
+
}
|
|
1526
|
+
const success = await attemptIncrementalUpdate({
|
|
1527
|
+
cwd,
|
|
1528
|
+
contractsDir: fullContractsDir,
|
|
1529
|
+
outputPath: fullOutputPath,
|
|
1530
|
+
changedFilePath: changedFile.path,
|
|
1531
|
+
baseUrl: config.baseUrl,
|
|
1532
|
+
apiName,
|
|
1533
|
+
debug: options.debug
|
|
1534
|
+
});
|
|
1535
|
+
if (success) {
|
|
1536
|
+
if (options.debug) {
|
|
1537
|
+
contractLogger.info("Incremental update successful");
|
|
1538
|
+
}
|
|
1539
|
+
return;
|
|
1540
|
+
}
|
|
1541
|
+
if (options.debug) {
|
|
1542
|
+
contractLogger.info("Incremental update failed, doing full regen");
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1545
|
+
const allContracts = await scanContracts(fullContractsDir, prefix);
|
|
1546
|
+
if (allContracts.length === 0) {
|
|
1547
|
+
if (options.debug) {
|
|
1548
|
+
contractLogger.warn("No contracts found");
|
|
1549
|
+
}
|
|
1550
|
+
contractCache = null;
|
|
1551
|
+
return;
|
|
1552
|
+
}
|
|
1553
|
+
const clientOptions = createClientOptions(fullContractsDir, fullOutputPath, config.baseUrl, apiName);
|
|
1554
|
+
const stats = await generateClient(allContracts, clientOptions);
|
|
1555
|
+
contractCache = {
|
|
1556
|
+
contracts: allContracts,
|
|
1557
|
+
lastScan: Date.now()
|
|
1558
|
+
};
|
|
1559
|
+
if (options.debug) {
|
|
1560
|
+
contractLogger.info("Client generated", {
|
|
1561
|
+
endpoints: stats.methodsGenerated,
|
|
1562
|
+
resources: stats.resourcesGenerated,
|
|
1563
|
+
duration: stats.duration,
|
|
1564
|
+
mode: changedFile ? "incremental-fallback" : "full"
|
|
1565
|
+
});
|
|
1566
|
+
}
|
|
1567
|
+
} catch (error) {
|
|
1568
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1569
|
+
contractLogger.error("Generation failed", err);
|
|
1570
|
+
throw err;
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
};
|
|
1574
|
+
}
|
|
1575
|
+
async function attemptIncrementalUpdate(options) {
|
|
1576
|
+
const { cwd, contractsDir, outputPath, changedFilePath, baseUrl, apiName, debug } = options;
|
|
1577
|
+
if (!contractCache) {
|
|
1578
|
+
return false;
|
|
1579
|
+
}
|
|
933
1580
|
try {
|
|
934
|
-
const
|
|
935
|
-
if (
|
|
936
|
-
|
|
937
|
-
|
|
1581
|
+
const fullPath = join(cwd, changedFilePath);
|
|
1582
|
+
if (!existsSync(fullPath)) {
|
|
1583
|
+
return false;
|
|
1584
|
+
}
|
|
1585
|
+
const updatedContracts = await scanContracts(contractsDir);
|
|
1586
|
+
if (updatedContracts.length === 0) {
|
|
1587
|
+
contractCache = null;
|
|
1588
|
+
return false;
|
|
1589
|
+
}
|
|
1590
|
+
const changedContracts = findChangedContracts(
|
|
1591
|
+
contractCache.contracts,
|
|
1592
|
+
updatedContracts,
|
|
1593
|
+
changedFilePath
|
|
1594
|
+
);
|
|
1595
|
+
if (changedContracts.size === 0) {
|
|
1596
|
+
if (debug) {
|
|
1597
|
+
contractLogger.info("No contract changes detected, skipping regeneration");
|
|
938
1598
|
}
|
|
939
|
-
return
|
|
1599
|
+
return true;
|
|
940
1600
|
}
|
|
941
|
-
const
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
1601
|
+
const clientOptions = createClientOptions(contractsDir, outputPath, baseUrl, apiName);
|
|
1602
|
+
const stats = await generateClient(updatedContracts, clientOptions);
|
|
1603
|
+
contractCache = {
|
|
1604
|
+
contracts: updatedContracts,
|
|
1605
|
+
lastScan: Date.now()
|
|
1606
|
+
};
|
|
1607
|
+
if (debug) {
|
|
1608
|
+
contractLogger.info("Incremental update successful", {
|
|
1609
|
+
changedContracts: changedContracts.size,
|
|
948
1610
|
endpoints: stats.methodsGenerated,
|
|
949
1611
|
resources: stats.resourcesGenerated,
|
|
950
1612
|
duration: stats.duration
|
|
951
1613
|
});
|
|
952
1614
|
}
|
|
953
|
-
return
|
|
1615
|
+
return true;
|
|
954
1616
|
} catch (error) {
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
return
|
|
1617
|
+
if (debug) {
|
|
1618
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1619
|
+
contractLogger.warn("Incremental update failed", err);
|
|
1620
|
+
}
|
|
1621
|
+
return false;
|
|
960
1622
|
}
|
|
961
1623
|
}
|
|
962
|
-
|
|
963
|
-
const
|
|
964
|
-
const
|
|
965
|
-
const
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
1624
|
+
function findChangedContracts(oldContracts, newContracts, changedFilePath) {
|
|
1625
|
+
const changed = /* @__PURE__ */ new Set();
|
|
1626
|
+
const oldInFile = oldContracts.filter((c) => c.contractFile?.includes(changedFilePath));
|
|
1627
|
+
const newInFile = newContracts.filter((c) => c.contractFile?.includes(changedFilePath));
|
|
1628
|
+
if (oldInFile.length !== newInFile.length) {
|
|
1629
|
+
newInFile.forEach((c) => changed.add(c.contractName));
|
|
1630
|
+
return changed;
|
|
1631
|
+
}
|
|
1632
|
+
for (const newContract of newInFile) {
|
|
1633
|
+
const oldContract = oldInFile.find((c) => c.contractName === newContract.contractName);
|
|
1634
|
+
if (!oldContract) {
|
|
1635
|
+
changed.add(newContract.contractName);
|
|
1636
|
+
continue;
|
|
1637
|
+
}
|
|
1638
|
+
if (oldContract.method !== newContract.method || oldContract.path !== newContract.path || oldContract.hasQuery !== newContract.hasQuery || oldContract.hasBody !== newContract.hasBody || oldContract.hasParams !== newContract.hasParams) {
|
|
1639
|
+
changed.add(newContract.contractName);
|
|
1640
|
+
}
|
|
969
1641
|
}
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
}
|
|
983
|
-
});
|
|
984
|
-
const regenerate = async () => {
|
|
985
|
-
if (isGenerating) {
|
|
986
|
-
pendingRegeneration = true;
|
|
987
|
-
return;
|
|
988
|
-
}
|
|
989
|
-
isGenerating = true;
|
|
990
|
-
pendingRegeneration = false;
|
|
991
|
-
if (options.debug) {
|
|
992
|
-
codegenLogger.info("Contracts changed, regenerating...");
|
|
1642
|
+
return changed;
|
|
1643
|
+
}
|
|
1644
|
+
var configLogger = logger.child("config");
|
|
1645
|
+
function loadCodegenConfig(cwd) {
|
|
1646
|
+
const rcPath = join(cwd, ".spfnrc.json");
|
|
1647
|
+
if (existsSync(rcPath)) {
|
|
1648
|
+
try {
|
|
1649
|
+
const content = readFileSync(rcPath, "utf-8");
|
|
1650
|
+
const config = JSON.parse(content);
|
|
1651
|
+
if (config.codegen) {
|
|
1652
|
+
configLogger.info("Loaded config from .spfnrc.json");
|
|
1653
|
+
return config.codegen;
|
|
993
1654
|
}
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
1655
|
+
} catch (error) {
|
|
1656
|
+
configLogger.warn("Failed to parse .spfnrc.json", error);
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
const pkgPath = join(cwd, "package.json");
|
|
1660
|
+
if (existsSync(pkgPath)) {
|
|
1661
|
+
try {
|
|
1662
|
+
const content = readFileSync(pkgPath, "utf-8");
|
|
1663
|
+
const pkg = JSON.parse(content);
|
|
1664
|
+
if (pkg.spfn?.codegen) {
|
|
1665
|
+
configLogger.info("Loaded config from package.json");
|
|
1666
|
+
return pkg.spfn.codegen;
|
|
998
1667
|
}
|
|
999
|
-
}
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1668
|
+
} catch (error) {
|
|
1669
|
+
configLogger.warn("Failed to parse package.json", error);
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
configLogger.info("Using default config");
|
|
1673
|
+
return {
|
|
1674
|
+
generators: [
|
|
1675
|
+
{ name: "@spfn/core:contract", enabled: true }
|
|
1676
|
+
]
|
|
1677
|
+
};
|
|
1678
|
+
}
|
|
1679
|
+
async function loadGeneratorFromPackage(packageName, generatorName, config) {
|
|
1680
|
+
try {
|
|
1681
|
+
const generatorsModule = await import(`${packageName}/generators`);
|
|
1682
|
+
if (generatorsModule.generators?.[generatorName]) {
|
|
1683
|
+
const createFn = generatorsModule.generators[generatorName];
|
|
1684
|
+
const generator = createFn(config);
|
|
1685
|
+
configLogger.info(`Loaded ${packageName}:${generatorName}`);
|
|
1686
|
+
return generator;
|
|
1687
|
+
}
|
|
1688
|
+
const conventionalName = `create${capitalize(generatorName)}Generator`;
|
|
1689
|
+
if (generatorsModule[conventionalName]) {
|
|
1690
|
+
const createFn = generatorsModule[conventionalName];
|
|
1691
|
+
const generator = createFn(config);
|
|
1692
|
+
configLogger.info(`Loaded ${packageName}:${generatorName} (via ${conventionalName})`);
|
|
1693
|
+
return generator;
|
|
1694
|
+
}
|
|
1695
|
+
configLogger.warn(
|
|
1696
|
+
`Generator "${generatorName}" not found in ${packageName}/generators. Expected: generators.${generatorName} or ${conventionalName}`
|
|
1697
|
+
);
|
|
1698
|
+
return null;
|
|
1699
|
+
} catch (error) {
|
|
1700
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1701
|
+
configLogger.warn(
|
|
1702
|
+
`Failed to load ${packageName}:${generatorName}. Make sure ${packageName} is installed. Error: ${err.message}`
|
|
1703
|
+
);
|
|
1704
|
+
return null;
|
|
1007
1705
|
}
|
|
1008
1706
|
}
|
|
1009
|
-
|
|
1010
|
-
|
|
1707
|
+
function capitalize(str) {
|
|
1708
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
1709
|
+
}
|
|
1710
|
+
async function createGeneratorsFromConfig(config, cwd) {
|
|
1711
|
+
const generators = [];
|
|
1712
|
+
if (!config.generators || config.generators.length === 0) {
|
|
1713
|
+
return generators;
|
|
1714
|
+
}
|
|
1715
|
+
for (const generatorConfig of config.generators) {
|
|
1716
|
+
try {
|
|
1717
|
+
if ("path" in generatorConfig) {
|
|
1718
|
+
const generatorPath = generatorConfig.path.startsWith(".") ? join(cwd, generatorConfig.path) : generatorConfig.path;
|
|
1719
|
+
configLogger.info(`Loading custom generator: ${generatorPath}`);
|
|
1720
|
+
let module;
|
|
1721
|
+
if (generatorPath.endsWith(".ts")) {
|
|
1722
|
+
const jiti = createJiti(cwd, {
|
|
1723
|
+
interopDefault: true
|
|
1724
|
+
});
|
|
1725
|
+
module = jiti(generatorPath);
|
|
1726
|
+
} else {
|
|
1727
|
+
module = await import(generatorPath);
|
|
1728
|
+
}
|
|
1729
|
+
const createGenerator = module.default || module.createGenerator || module;
|
|
1730
|
+
if (typeof createGenerator === "function") {
|
|
1731
|
+
const generator = createGenerator();
|
|
1732
|
+
generators.push(generator);
|
|
1733
|
+
configLogger.info(`Custom generator loaded: ${generator.name}`);
|
|
1734
|
+
} else {
|
|
1735
|
+
configLogger.warn(`Invalid generator at ${generatorPath}: expected function`);
|
|
1736
|
+
}
|
|
1737
|
+
} else if ("name" in generatorConfig && generatorConfig.name.includes(":")) {
|
|
1738
|
+
if (generatorConfig.enabled !== false) {
|
|
1739
|
+
const [packageName, generatorName] = generatorConfig.name.split(":");
|
|
1740
|
+
const { enabled, name, ...generatorOptions } = generatorConfig;
|
|
1741
|
+
const generator = await loadGeneratorFromPackage(
|
|
1742
|
+
packageName,
|
|
1743
|
+
generatorName,
|
|
1744
|
+
generatorOptions
|
|
1745
|
+
);
|
|
1746
|
+
if (generator) {
|
|
1747
|
+
generators.push(generator);
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
} else if ("name" in generatorConfig) {
|
|
1751
|
+
configLogger.warn(
|
|
1752
|
+
`Invalid generator name "${generatorConfig.name}". Use package:name format (e.g., "@spfn/core:contract")`
|
|
1753
|
+
);
|
|
1754
|
+
}
|
|
1755
|
+
} catch (error) {
|
|
1756
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1757
|
+
configLogger.error("Failed to load generator", err);
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
return generators;
|
|
1011
1761
|
}
|
|
1012
1762
|
|
|
1013
|
-
export {
|
|
1763
|
+
export { CodegenOrchestrator, createContractGenerator, createGeneratorsFromConfig, loadCodegenConfig };
|
|
1014
1764
|
//# sourceMappingURL=index.js.map
|
|
1015
1765
|
//# sourceMappingURL=index.js.map
|