@spfn/core 0.1.0-alpha.88 → 0.2.0-beta.2

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.
Files changed (71) hide show
  1. package/README.md +1046 -384
  2. package/dist/boss-D-fGtVgM.d.ts +187 -0
  3. package/dist/cache/index.d.ts +13 -33
  4. package/dist/cache/index.js +14 -703
  5. package/dist/cache/index.js.map +1 -1
  6. package/dist/codegen/index.d.ts +167 -17
  7. package/dist/codegen/index.js +76 -1419
  8. package/dist/codegen/index.js.map +1 -1
  9. package/dist/config/index.d.ts +1191 -0
  10. package/dist/config/index.js +264 -0
  11. package/dist/config/index.js.map +1 -0
  12. package/dist/db/index.d.ts +728 -59
  13. package/dist/db/index.js +1028 -1225
  14. package/dist/db/index.js.map +1 -1
  15. package/dist/env/index.d.ts +579 -308
  16. package/dist/env/index.js +438 -930
  17. package/dist/env/index.js.map +1 -1
  18. package/dist/errors/index.d.ts +417 -29
  19. package/dist/errors/index.js +359 -98
  20. package/dist/errors/index.js.map +1 -1
  21. package/dist/event/index.d.ts +108 -0
  22. package/dist/event/index.js +122 -0
  23. package/dist/event/index.js.map +1 -0
  24. package/dist/job/index.d.ts +172 -0
  25. package/dist/job/index.js +361 -0
  26. package/dist/job/index.js.map +1 -0
  27. package/dist/logger/index.d.ts +20 -79
  28. package/dist/logger/index.js +82 -387
  29. package/dist/logger/index.js.map +1 -1
  30. package/dist/middleware/index.d.ts +2 -11
  31. package/dist/middleware/index.js +49 -703
  32. package/dist/middleware/index.js.map +1 -1
  33. package/dist/nextjs/index.d.ts +120 -0
  34. package/dist/nextjs/index.js +416 -0
  35. package/dist/nextjs/index.js.map +1 -0
  36. package/dist/{client/nextjs/index.d.ts → nextjs/server.d.ts} +288 -262
  37. package/dist/nextjs/server.js +568 -0
  38. package/dist/nextjs/server.js.map +1 -0
  39. package/dist/route/index.d.ts +686 -25
  40. package/dist/route/index.js +440 -1287
  41. package/dist/route/index.js.map +1 -1
  42. package/dist/route/types.d.ts +38 -0
  43. package/dist/route/types.js +3 -0
  44. package/dist/route/types.js.map +1 -0
  45. package/dist/server/index.d.ts +201 -67
  46. package/dist/server/index.js +921 -3182
  47. package/dist/server/index.js.map +1 -1
  48. package/dist/types-BGl4QL1w.d.ts +77 -0
  49. package/dist/types-DRG2XMTR.d.ts +157 -0
  50. package/package.json +52 -47
  51. package/dist/auto-loader-JFaZ9gON.d.ts +0 -80
  52. package/dist/client/index.d.ts +0 -358
  53. package/dist/client/index.js +0 -357
  54. package/dist/client/index.js.map +0 -1
  55. package/dist/client/nextjs/index.js +0 -371
  56. package/dist/client/nextjs/index.js.map +0 -1
  57. package/dist/codegen/generators/index.d.ts +0 -19
  58. package/dist/codegen/generators/index.js +0 -1404
  59. package/dist/codegen/generators/index.js.map +0 -1
  60. package/dist/database-errors-BNNmLTJE.d.ts +0 -86
  61. package/dist/events/index.d.ts +0 -183
  62. package/dist/events/index.js +0 -77
  63. package/dist/events/index.js.map +0 -1
  64. package/dist/index-DHiAqhKv.d.ts +0 -101
  65. package/dist/index.d.ts +0 -8
  66. package/dist/index.js +0 -3674
  67. package/dist/index.js.map +0 -1
  68. package/dist/types/index.d.ts +0 -121
  69. package/dist/types/index.js +0 -38
  70. package/dist/types/index.js.map +0 -1
  71. package/dist/types-BXibIEyj.d.ts +0 -60
@@ -1,1404 +0,0 @@
1
- import { join } from 'path';
2
- import { existsSync, mkdirSync, createWriteStream, statSync, readdirSync, renameSync, unlinkSync, accessSync, constants, writeFileSync, readFileSync } from 'fs';
3
- import { readdir, stat, mkdir, writeFile } from 'fs/promises';
4
- import * as ts from 'typescript';
5
-
6
- // src/codegen/built-in/contract/index.ts
7
-
8
- // src/logger/types.ts
9
- var LOG_LEVEL_PRIORITY = {
10
- debug: 0,
11
- info: 1,
12
- warn: 2,
13
- error: 3,
14
- fatal: 4
15
- };
16
-
17
- // src/logger/formatters.ts
18
- var SENSITIVE_KEYS = [
19
- "password",
20
- "passwd",
21
- "pwd",
22
- "secret",
23
- "token",
24
- "apikey",
25
- "api_key",
26
- "accesstoken",
27
- "access_token",
28
- "refreshtoken",
29
- "refresh_token",
30
- "authorization",
31
- "auth",
32
- "cookie",
33
- "session",
34
- "sessionid",
35
- "session_id",
36
- "privatekey",
37
- "private_key",
38
- "creditcard",
39
- "credit_card",
40
- "cardnumber",
41
- "card_number",
42
- "cvv",
43
- "ssn",
44
- "pin"
45
- ];
46
- var MASKED_VALUE = "***MASKED***";
47
- function isSensitiveKey(key) {
48
- const lowerKey = key.toLowerCase();
49
- return SENSITIVE_KEYS.some((sensitive) => lowerKey.includes(sensitive));
50
- }
51
- function maskSensitiveData(data) {
52
- if (data === null || data === void 0) {
53
- return data;
54
- }
55
- if (Array.isArray(data)) {
56
- return data.map((item) => maskSensitiveData(item));
57
- }
58
- if (typeof data === "object") {
59
- const masked = {};
60
- for (const [key, value] of Object.entries(data)) {
61
- if (isSensitiveKey(key)) {
62
- masked[key] = MASKED_VALUE;
63
- } else if (typeof value === "object" && value !== null) {
64
- masked[key] = maskSensitiveData(value);
65
- } else {
66
- masked[key] = value;
67
- }
68
- }
69
- return masked;
70
- }
71
- return data;
72
- }
73
- var COLORS = {
74
- reset: "\x1B[0m",
75
- bright: "\x1B[1m",
76
- dim: "\x1B[2m",
77
- // 로그 레벨 컬러
78
- debug: "\x1B[36m",
79
- // cyan
80
- info: "\x1B[32m",
81
- // green
82
- warn: "\x1B[33m",
83
- // yellow
84
- error: "\x1B[31m",
85
- // red
86
- fatal: "\x1B[35m",
87
- // magenta
88
- // 추가 컬러
89
- gray: "\x1B[90m"
90
- };
91
- function formatTimestamp(date) {
92
- return date.toISOString();
93
- }
94
- function formatTimestampHuman(date) {
95
- const year = date.getFullYear();
96
- const month = String(date.getMonth() + 1).padStart(2, "0");
97
- const day = String(date.getDate()).padStart(2, "0");
98
- const hours = String(date.getHours()).padStart(2, "0");
99
- const minutes = String(date.getMinutes()).padStart(2, "0");
100
- const seconds = String(date.getSeconds()).padStart(2, "0");
101
- const ms = String(date.getMilliseconds()).padStart(3, "0");
102
- return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${ms}`;
103
- }
104
- function formatError(error) {
105
- const lines = [];
106
- lines.push(`${error.name}: ${error.message}`);
107
- if (error.stack) {
108
- const stackLines = error.stack.split("\n").slice(1);
109
- lines.push(...stackLines);
110
- }
111
- return lines.join("\n");
112
- }
113
- function formatConsole(metadata, colorize = true) {
114
- const parts = [];
115
- const timestamp = formatTimestampHuman(metadata.timestamp);
116
- if (colorize) {
117
- parts.push(`${COLORS.gray}[${timestamp}]${COLORS.reset}`);
118
- } else {
119
- parts.push(`[${timestamp}]`);
120
- }
121
- if (metadata.module) {
122
- if (colorize) {
123
- parts.push(`${COLORS.dim}[module=${metadata.module}]${COLORS.reset}`);
124
- } else {
125
- parts.push(`[module=${metadata.module}]`);
126
- }
127
- }
128
- if (metadata.context && Object.keys(metadata.context).length > 0) {
129
- Object.entries(metadata.context).forEach(([key, value]) => {
130
- let valueStr;
131
- if (typeof value === "string") {
132
- valueStr = value;
133
- } else if (typeof value === "object" && value !== null) {
134
- try {
135
- valueStr = JSON.stringify(value);
136
- } catch (error) {
137
- valueStr = "[circular]";
138
- }
139
- } else {
140
- valueStr = String(value);
141
- }
142
- if (colorize) {
143
- parts.push(`${COLORS.dim}[${key}=${valueStr}]${COLORS.reset}`);
144
- } else {
145
- parts.push(`[${key}=${valueStr}]`);
146
- }
147
- });
148
- }
149
- const levelStr = metadata.level.toUpperCase();
150
- if (colorize) {
151
- const color = COLORS[metadata.level];
152
- parts.push(`${color}(${levelStr})${COLORS.reset}:`);
153
- } else {
154
- parts.push(`(${levelStr}):`);
155
- }
156
- if (colorize) {
157
- parts.push(`${COLORS.bright}${metadata.message}${COLORS.reset}`);
158
- } else {
159
- parts.push(metadata.message);
160
- }
161
- let output = parts.join(" ");
162
- if (metadata.error) {
163
- output += "\n" + formatError(metadata.error);
164
- }
165
- return output;
166
- }
167
- function formatJSON(metadata) {
168
- const obj = {
169
- timestamp: formatTimestamp(metadata.timestamp),
170
- level: metadata.level,
171
- message: metadata.message
172
- };
173
- if (metadata.module) {
174
- obj.module = metadata.module;
175
- }
176
- if (metadata.context) {
177
- obj.context = metadata.context;
178
- }
179
- if (metadata.error) {
180
- obj.error = {
181
- name: metadata.error.name,
182
- message: metadata.error.message,
183
- stack: metadata.error.stack
184
- };
185
- }
186
- return JSON.stringify(obj);
187
- }
188
-
189
- // src/logger/logger.ts
190
- var Logger = class _Logger {
191
- config;
192
- module;
193
- constructor(config) {
194
- this.config = config;
195
- this.module = config.module;
196
- }
197
- /**
198
- * Get current log level
199
- */
200
- get level() {
201
- return this.config.level;
202
- }
203
- /**
204
- * Create child logger (per module)
205
- */
206
- child(module) {
207
- return new _Logger({
208
- ...this.config,
209
- module
210
- });
211
- }
212
- /**
213
- * Debug log
214
- */
215
- debug(message, context) {
216
- this.log("debug", message, void 0, context);
217
- }
218
- /**
219
- * Info log
220
- */
221
- info(message, context) {
222
- this.log("info", message, void 0, context);
223
- }
224
- warn(message, errorOrContext, context) {
225
- if (errorOrContext instanceof Error) {
226
- this.log("warn", message, errorOrContext, context);
227
- } else {
228
- this.log("warn", message, void 0, errorOrContext);
229
- }
230
- }
231
- error(message, errorOrContext, context) {
232
- if (errorOrContext instanceof Error) {
233
- this.log("error", message, errorOrContext, context);
234
- } else {
235
- this.log("error", message, void 0, errorOrContext);
236
- }
237
- }
238
- fatal(message, errorOrContext, context) {
239
- if (errorOrContext instanceof Error) {
240
- this.log("fatal", message, errorOrContext, context);
241
- } else {
242
- this.log("fatal", message, void 0, errorOrContext);
243
- }
244
- }
245
- /**
246
- * Log processing (internal)
247
- */
248
- log(level, message, error, context) {
249
- if (LOG_LEVEL_PRIORITY[level] < LOG_LEVEL_PRIORITY[this.config.level]) {
250
- return;
251
- }
252
- const metadata = {
253
- timestamp: /* @__PURE__ */ new Date(),
254
- level,
255
- message,
256
- module: this.module,
257
- error,
258
- // Mask sensitive information in context to prevent credential leaks
259
- context: context ? maskSensitiveData(context) : void 0
260
- };
261
- this.processTransports(metadata);
262
- }
263
- /**
264
- * Process Transports
265
- */
266
- processTransports(metadata) {
267
- const promises = this.config.transports.filter((transport) => transport.enabled).map((transport) => this.safeTransportLog(transport, metadata));
268
- Promise.all(promises).catch((error) => {
269
- const errorMessage = error instanceof Error ? error.message : String(error);
270
- process.stderr.write(`[Logger] Transport error: ${errorMessage}
271
- `);
272
- });
273
- }
274
- /**
275
- * Transport log (error-safe)
276
- */
277
- async safeTransportLog(transport, metadata) {
278
- try {
279
- await transport.log(metadata);
280
- } catch (error) {
281
- const errorMessage = error instanceof Error ? error.message : String(error);
282
- process.stderr.write(`[Logger] Transport "${transport.name}" failed: ${errorMessage}
283
- `);
284
- }
285
- }
286
- /**
287
- * Close all Transports
288
- */
289
- async close() {
290
- const closePromises = this.config.transports.filter((transport) => transport.close).map((transport) => transport.close());
291
- await Promise.all(closePromises);
292
- }
293
- };
294
-
295
- // src/logger/transports/console.ts
296
- var ConsoleTransport = class {
297
- name = "console";
298
- level;
299
- enabled;
300
- colorize;
301
- constructor(config) {
302
- this.level = config.level;
303
- this.enabled = config.enabled;
304
- this.colorize = config.colorize ?? true;
305
- }
306
- async log(metadata) {
307
- if (!this.enabled) {
308
- return;
309
- }
310
- if (LOG_LEVEL_PRIORITY[metadata.level] < LOG_LEVEL_PRIORITY[this.level]) {
311
- return;
312
- }
313
- const message = formatConsole(metadata, this.colorize);
314
- if (metadata.level === "warn" || metadata.level === "error" || metadata.level === "fatal") {
315
- console.error(message);
316
- } else {
317
- console.log(message);
318
- }
319
- }
320
- };
321
- var FileTransport = class {
322
- name = "file";
323
- level;
324
- enabled;
325
- logDir;
326
- maxFileSize;
327
- maxFiles;
328
- currentStream = null;
329
- currentFilename = null;
330
- constructor(config) {
331
- this.level = config.level;
332
- this.enabled = config.enabled;
333
- this.logDir = config.logDir;
334
- this.maxFileSize = config.maxFileSize ?? 10 * 1024 * 1024;
335
- this.maxFiles = config.maxFiles ?? 10;
336
- if (!existsSync(this.logDir)) {
337
- mkdirSync(this.logDir, { recursive: true });
338
- }
339
- }
340
- async log(metadata) {
341
- if (!this.enabled) {
342
- return;
343
- }
344
- if (LOG_LEVEL_PRIORITY[metadata.level] < LOG_LEVEL_PRIORITY[this.level]) {
345
- return;
346
- }
347
- const message = formatJSON(metadata);
348
- const filename = this.getLogFilename(metadata.timestamp);
349
- if (this.currentFilename !== filename) {
350
- await this.rotateStream(filename);
351
- await this.cleanOldFiles();
352
- } else if (this.currentFilename) {
353
- await this.checkAndRotateBySize();
354
- }
355
- if (this.currentStream) {
356
- return new Promise((resolve, reject) => {
357
- this.currentStream.write(message + "\n", "utf-8", (error) => {
358
- if (error) {
359
- process.stderr.write(`[FileTransport] Failed to write log: ${error.message}
360
- `);
361
- reject(error);
362
- } else {
363
- resolve();
364
- }
365
- });
366
- });
367
- }
368
- }
369
- /**
370
- * 스트림 교체 (날짜 변경 시)
371
- */
372
- async rotateStream(filename) {
373
- if (this.currentStream) {
374
- await this.closeStream();
375
- }
376
- const filepath = join(this.logDir, filename);
377
- this.currentStream = createWriteStream(filepath, {
378
- flags: "a",
379
- // append mode
380
- encoding: "utf-8"
381
- });
382
- this.currentFilename = filename;
383
- this.currentStream.on("error", (error) => {
384
- process.stderr.write(`[FileTransport] Stream error: ${error.message}
385
- `);
386
- this.currentStream = null;
387
- this.currentFilename = null;
388
- });
389
- }
390
- /**
391
- * 현재 스트림 닫기
392
- */
393
- async closeStream() {
394
- if (!this.currentStream) {
395
- return;
396
- }
397
- return new Promise((resolve, reject) => {
398
- this.currentStream.end((error) => {
399
- if (error) {
400
- reject(error);
401
- } else {
402
- this.currentStream = null;
403
- this.currentFilename = null;
404
- resolve();
405
- }
406
- });
407
- });
408
- }
409
- /**
410
- * 파일 크기 체크 및 크기 기반 로테이션
411
- */
412
- async checkAndRotateBySize() {
413
- if (!this.currentFilename) {
414
- return;
415
- }
416
- const filepath = join(this.logDir, this.currentFilename);
417
- if (!existsSync(filepath)) {
418
- return;
419
- }
420
- try {
421
- const stats = statSync(filepath);
422
- if (stats.size >= this.maxFileSize) {
423
- await this.rotateBySize();
424
- }
425
- } catch (error) {
426
- const errorMessage = error instanceof Error ? error.message : String(error);
427
- process.stderr.write(`[FileTransport] Failed to check file size: ${errorMessage}
428
- `);
429
- }
430
- }
431
- /**
432
- * 크기 기반 로테이션 수행
433
- * 예: 2025-01-01.log -> 2025-01-01.1.log, 2025-01-01.1.log -> 2025-01-01.2.log
434
- */
435
- async rotateBySize() {
436
- if (!this.currentFilename) {
437
- return;
438
- }
439
- await this.closeStream();
440
- const baseName = this.currentFilename.replace(/\.log$/, "");
441
- const files = readdirSync(this.logDir);
442
- const relatedFiles = files.filter((file) => file.startsWith(baseName) && file.endsWith(".log")).sort().reverse();
443
- for (const file of relatedFiles) {
444
- const match = file.match(/\.(\d+)\.log$/);
445
- if (match) {
446
- const oldNum = parseInt(match[1], 10);
447
- const newNum = oldNum + 1;
448
- const oldPath = join(this.logDir, file);
449
- const newPath2 = join(this.logDir, `${baseName}.${newNum}.log`);
450
- try {
451
- renameSync(oldPath, newPath2);
452
- } catch (error) {
453
- const errorMessage = error instanceof Error ? error.message : String(error);
454
- process.stderr.write(`[FileTransport] Failed to rotate file: ${errorMessage}
455
- `);
456
- }
457
- }
458
- }
459
- const currentPath = join(this.logDir, this.currentFilename);
460
- const newPath = join(this.logDir, `${baseName}.1.log`);
461
- try {
462
- if (existsSync(currentPath)) {
463
- renameSync(currentPath, newPath);
464
- }
465
- } catch (error) {
466
- const errorMessage = error instanceof Error ? error.message : String(error);
467
- process.stderr.write(`[FileTransport] Failed to rotate current file: ${errorMessage}
468
- `);
469
- }
470
- await this.rotateStream(this.currentFilename);
471
- }
472
- /**
473
- * 오래된 로그 파일 정리
474
- * maxFiles 개수를 초과하는 로그 파일 삭제
475
- */
476
- async cleanOldFiles() {
477
- try {
478
- if (!existsSync(this.logDir)) {
479
- return;
480
- }
481
- const files = readdirSync(this.logDir);
482
- const logFiles = files.filter((file) => file.endsWith(".log")).map((file) => {
483
- const filepath = join(this.logDir, file);
484
- const stats = statSync(filepath);
485
- return { file, mtime: stats.mtime };
486
- }).sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
487
- if (logFiles.length > this.maxFiles) {
488
- const filesToDelete = logFiles.slice(this.maxFiles);
489
- for (const { file } of filesToDelete) {
490
- const filepath = join(this.logDir, file);
491
- try {
492
- unlinkSync(filepath);
493
- } catch (error) {
494
- const errorMessage = error instanceof Error ? error.message : String(error);
495
- process.stderr.write(`[FileTransport] Failed to delete old file "${file}": ${errorMessage}
496
- `);
497
- }
498
- }
499
- }
500
- } catch (error) {
501
- const errorMessage = error instanceof Error ? error.message : String(error);
502
- process.stderr.write(`[FileTransport] Failed to clean old files: ${errorMessage}
503
- `);
504
- }
505
- }
506
- /**
507
- * 날짜별 로그 파일명 생성
508
- */
509
- getLogFilename(date) {
510
- const year = date.getFullYear();
511
- const month = String(date.getMonth() + 1).padStart(2, "0");
512
- const day = String(date.getDate()).padStart(2, "0");
513
- return `${year}-${month}-${day}.log`;
514
- }
515
- async close() {
516
- await this.closeStream();
517
- }
518
- };
519
- function isFileLoggingEnabled() {
520
- return process.env.LOGGER_FILE_ENABLED === "true";
521
- }
522
- function getDefaultLogLevel() {
523
- const isProduction = process.env.NODE_ENV === "production";
524
- const isDevelopment = process.env.NODE_ENV === "development";
525
- if (isDevelopment) {
526
- return "debug";
527
- }
528
- if (isProduction) {
529
- return "info";
530
- }
531
- return "warn";
532
- }
533
- function getConsoleConfig() {
534
- const isProduction = process.env.NODE_ENV === "production";
535
- return {
536
- level: "debug",
537
- enabled: true,
538
- colorize: !isProduction
539
- // Dev: colored output, Production: plain text
540
- };
541
- }
542
- function getFileConfig() {
543
- const isProduction = process.env.NODE_ENV === "production";
544
- return {
545
- level: "info",
546
- enabled: isProduction,
547
- // File logging in production only
548
- logDir: process.env.LOG_DIR || "./logs",
549
- maxFileSize: 10 * 1024 * 1024,
550
- // 10MB
551
- maxFiles: 10
552
- };
553
- }
554
- function validateDirectoryWritable(dirPath) {
555
- if (!existsSync(dirPath)) {
556
- try {
557
- mkdirSync(dirPath, { recursive: true });
558
- } catch (error) {
559
- const errorMessage = error instanceof Error ? error.message : String(error);
560
- throw new Error(`Failed to create log directory "${dirPath}": ${errorMessage}`);
561
- }
562
- }
563
- try {
564
- accessSync(dirPath, constants.W_OK);
565
- } catch {
566
- throw new Error(`Log directory "${dirPath}" is not writable. Please check permissions.`);
567
- }
568
- const testFile = join(dirPath, ".logger-write-test");
569
- try {
570
- writeFileSync(testFile, "test", "utf-8");
571
- unlinkSync(testFile);
572
- } catch (error) {
573
- const errorMessage = error instanceof Error ? error.message : String(error);
574
- throw new Error(`Cannot write to log directory "${dirPath}": ${errorMessage}`);
575
- }
576
- }
577
- function validateFileConfig() {
578
- if (!isFileLoggingEnabled()) {
579
- return;
580
- }
581
- const logDir = process.env.LOG_DIR;
582
- if (!logDir) {
583
- throw new Error(
584
- "LOG_DIR environment variable is required when LOGGER_FILE_ENABLED=true. Example: LOG_DIR=/var/log/myapp"
585
- );
586
- }
587
- validateDirectoryWritable(logDir);
588
- }
589
- function validateSlackConfig() {
590
- const webhookUrl = process.env.SLACK_WEBHOOK_URL;
591
- if (!webhookUrl) {
592
- return;
593
- }
594
- if (!webhookUrl.startsWith("https://hooks.slack.com/")) {
595
- throw new Error(
596
- `Invalid SLACK_WEBHOOK_URL: "${webhookUrl}". Slack webhook URLs must start with "https://hooks.slack.com/"`
597
- );
598
- }
599
- }
600
- function validateEmailConfig() {
601
- const smtpHost = process.env.SMTP_HOST;
602
- const smtpPort = process.env.SMTP_PORT;
603
- const emailFrom = process.env.EMAIL_FROM;
604
- const emailTo = process.env.EMAIL_TO;
605
- const hasAnyEmailConfig = smtpHost || smtpPort || emailFrom || emailTo;
606
- if (!hasAnyEmailConfig) {
607
- return;
608
- }
609
- const missingFields = [];
610
- if (!smtpHost) missingFields.push("SMTP_HOST");
611
- if (!smtpPort) missingFields.push("SMTP_PORT");
612
- if (!emailFrom) missingFields.push("EMAIL_FROM");
613
- if (!emailTo) missingFields.push("EMAIL_TO");
614
- if (missingFields.length > 0) {
615
- throw new Error(
616
- `Email transport configuration incomplete. Missing: ${missingFields.join(", ")}. Either set all required fields or remove all email configuration.`
617
- );
618
- }
619
- const port = parseInt(smtpPort, 10);
620
- if (isNaN(port) || port < 1 || port > 65535) {
621
- throw new Error(
622
- `Invalid SMTP_PORT: "${smtpPort}". Must be a number between 1 and 65535.`
623
- );
624
- }
625
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
626
- if (!emailRegex.test(emailFrom)) {
627
- throw new Error(`Invalid EMAIL_FROM format: "${emailFrom}"`);
628
- }
629
- const recipients = emailTo.split(",").map((e) => e.trim());
630
- for (const email of recipients) {
631
- if (!emailRegex.test(email)) {
632
- throw new Error(`Invalid email address in EMAIL_TO: "${email}"`);
633
- }
634
- }
635
- }
636
- function validateEnvironment() {
637
- const nodeEnv = process.env.NODE_ENV;
638
- if (!nodeEnv) {
639
- process.stderr.write(
640
- "[Logger] Warning: NODE_ENV is not set. Defaulting to test environment.\n"
641
- );
642
- }
643
- }
644
- function validateConfig() {
645
- try {
646
- validateEnvironment();
647
- validateFileConfig();
648
- validateSlackConfig();
649
- validateEmailConfig();
650
- } catch (error) {
651
- if (error instanceof Error) {
652
- throw new Error(`[Logger] Configuration validation failed: ${error.message}`);
653
- }
654
- throw error;
655
- }
656
- }
657
-
658
- // src/logger/factory.ts
659
- function initializeTransports() {
660
- const transports = [];
661
- const consoleConfig = getConsoleConfig();
662
- transports.push(new ConsoleTransport(consoleConfig));
663
- const fileConfig = getFileConfig();
664
- if (fileConfig.enabled) {
665
- transports.push(new FileTransport(fileConfig));
666
- }
667
- return transports;
668
- }
669
- function initializeLogger() {
670
- validateConfig();
671
- return new Logger({
672
- level: getDefaultLogLevel(),
673
- transports: initializeTransports()
674
- });
675
- }
676
- var logger = initializeLogger();
677
-
678
- // src/codegen/built-in/contract/scanner.ts
679
- var scannerLogger = logger.child("contract-scanner");
680
- async function scanContracts(contractsDir, packagePrefix) {
681
- scannerLogger.debug("Starting contract scan", { contractsDir, packagePrefix });
682
- const contractFiles = await scanContractFiles(contractsDir);
683
- scannerLogger.debug("Found contract files", { count: contractFiles.length, files: contractFiles });
684
- const mappings = [];
685
- for (let i = 0; i < contractFiles.length; i++) {
686
- const filePath = contractFiles[i];
687
- scannerLogger.debug("Extracting contracts from file", { filePath });
688
- const exports = extractContractExports(filePath);
689
- scannerLogger.debug("Extracted contracts", { filePath, count: exports.length, contracts: exports.map((e) => e.name) });
690
- for (let j = 0; j < exports.length; j++) {
691
- const contractExport = exports[j];
692
- scannerLogger.debug("Processing contract", { name: contractExport.name, method: contractExport.method, path: contractExport.path });
693
- if (!contractExport.path.startsWith("/")) {
694
- throw new Error(
695
- `Contract '${contractExport.name}' in ${filePath} must use absolute path. Found: '${contractExport.path}'. Use '/your-path' instead.`
696
- );
697
- }
698
- if (packagePrefix && !contractExport.path.startsWith(packagePrefix)) {
699
- throw new Error(
700
- `Contract '${contractExport.name}' in ${filePath} must include package prefix. Expected path to start with '${packagePrefix}', but found: '${contractExport.path}'. Example: path: '${packagePrefix}/${contractExport.path}'`
701
- );
702
- }
703
- mappings.push({
704
- method: contractExport.method,
705
- path: contractExport.path,
706
- contractName: contractExport.name,
707
- contractImportPath: getImportPath(filePath),
708
- routeFile: "",
709
- contractFile: filePath,
710
- hasQuery: contractExport.hasQuery,
711
- hasBody: contractExport.hasBody,
712
- hasParams: contractExport.hasParams
713
- });
714
- }
715
- }
716
- scannerLogger.info("Contract scan completed", { totalMappings: mappings.length });
717
- return mappings;
718
- }
719
- async function scanContractFiles(dir, files = []) {
720
- try {
721
- const entries = await readdir(dir);
722
- for (let i = 0; i < entries.length; i++) {
723
- const entry = entries[i];
724
- const fullPath = join(dir, entry);
725
- const fileStat = await stat(fullPath);
726
- if (fileStat.isDirectory()) {
727
- await scanContractFiles(fullPath, files);
728
- } else {
729
- 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")) {
730
- files.push(fullPath);
731
- }
732
- }
733
- }
734
- } catch (error) {
735
- }
736
- return files;
737
- }
738
- function extractContractExports(filePath) {
739
- const sourceCode = readFileSync(filePath, "utf-8");
740
- const sourceFile = ts.createSourceFile(
741
- filePath,
742
- sourceCode,
743
- ts.ScriptTarget.Latest,
744
- true
745
- );
746
- const exports = [];
747
- function visit(node) {
748
- if (ts.isVariableStatement(node)) {
749
- const hasExport = node.modifiers?.some(
750
- (m) => m.kind === ts.SyntaxKind.ExportKeyword
751
- );
752
- if (hasExport && node.declarationList.declarations.length > 0) {
753
- const declaration = node.declarationList.declarations[0];
754
- if (ts.isVariableDeclaration(declaration) && ts.isIdentifier(declaration.name) && declaration.initializer) {
755
- const name = declaration.name.text;
756
- const hasSatisfiesRouteContract = checkSatisfiesRouteContract(declaration.initializer);
757
- if (hasSatisfiesRouteContract) {
758
- const objectLiteral = extractObjectLiteral(declaration.initializer);
759
- if (objectLiteral) {
760
- const contractData = extractContractData(objectLiteral);
761
- if (contractData.method && contractData.path) {
762
- exports.push({
763
- name,
764
- method: contractData.method,
765
- path: contractData.path,
766
- hasQuery: contractData.hasQuery,
767
- hasBody: contractData.hasBody,
768
- hasParams: contractData.hasParams
769
- });
770
- }
771
- }
772
- return;
773
- }
774
- if (isContractName(name)) {
775
- const objectLiteral = extractObjectLiteral(declaration.initializer);
776
- if (objectLiteral) {
777
- const contractData = extractContractData(objectLiteral);
778
- if (contractData.method && contractData.path) {
779
- exports.push({
780
- name,
781
- method: contractData.method,
782
- path: contractData.path,
783
- hasQuery: contractData.hasQuery,
784
- hasBody: contractData.hasBody,
785
- hasParams: contractData.hasParams
786
- });
787
- }
788
- }
789
- }
790
- }
791
- }
792
- }
793
- ts.forEachChild(node, visit);
794
- }
795
- visit(sourceFile);
796
- return exports;
797
- }
798
- function checkSatisfiesRouteContract(initializer) {
799
- if (!ts.isSatisfiesExpression(initializer)) {
800
- return false;
801
- }
802
- const typeNode = initializer.type;
803
- if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {
804
- return typeNode.typeName.text === "RouteContract";
805
- }
806
- return false;
807
- }
808
- function extractObjectLiteral(initializer) {
809
- if (ts.isObjectLiteralExpression(initializer)) {
810
- return initializer;
811
- }
812
- if (ts.isSatisfiesExpression(initializer)) {
813
- return extractObjectLiteral(initializer.expression);
814
- }
815
- if (ts.isAsExpression(initializer)) {
816
- return extractObjectLiteral(initializer.expression);
817
- }
818
- return void 0;
819
- }
820
- function extractContractData(objectLiteral) {
821
- const result = {};
822
- for (let i = 0; i < objectLiteral.properties.length; i++) {
823
- const prop = objectLiteral.properties[i];
824
- if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
825
- const propName = prop.name.text;
826
- if (propName === "method") {
827
- let value;
828
- if (ts.isStringLiteral(prop.initializer)) {
829
- value = prop.initializer.text;
830
- } else if (ts.isAsExpression(prop.initializer) && ts.isStringLiteral(prop.initializer.expression)) {
831
- value = prop.initializer.expression.text;
832
- }
833
- if (value) result.method = value;
834
- } else if (propName === "path") {
835
- let value;
836
- if (ts.isStringLiteral(prop.initializer)) {
837
- value = prop.initializer.text;
838
- } else if (ts.isAsExpression(prop.initializer) && ts.isStringLiteral(prop.initializer.expression)) {
839
- value = prop.initializer.expression.text;
840
- }
841
- if (value) result.path = value;
842
- } else if (propName === "query") {
843
- result.hasQuery = true;
844
- } else if (propName === "body") {
845
- result.hasBody = true;
846
- } else if (propName === "params") {
847
- result.hasParams = true;
848
- }
849
- }
850
- }
851
- return result;
852
- }
853
- function isContractName(name) {
854
- return name.indexOf("Contract") !== -1 || name.indexOf("contract") !== -1 || name.endsWith("Schema") || name.endsWith("schema");
855
- }
856
- function getImportPath(filePath) {
857
- const srcIndex = filePath.indexOf("/src/");
858
- if (srcIndex === -1) {
859
- throw new Error(`Cannot determine import path for ${filePath}: /src/ directory not found`);
860
- }
861
- let cleanPath = filePath.substring(srcIndex + 5);
862
- if (cleanPath.endsWith(".ts")) {
863
- cleanPath = cleanPath.slice(0, -3);
864
- } else if (cleanPath.endsWith(".js")) {
865
- cleanPath = cleanPath.slice(0, -3);
866
- } else if (cleanPath.endsWith(".mjs")) {
867
- cleanPath = cleanPath.slice(0, -4);
868
- }
869
- return "@/" + cleanPath;
870
- }
871
-
872
- // src/codegen/built-in/contract/helpers.ts
873
- function groupByResource(mappings) {
874
- const grouped = {};
875
- for (let i = 0; i < mappings.length; i++) {
876
- const mapping = mappings[i];
877
- const resource = extractResourceName(mapping.path);
878
- if (!grouped[resource]) {
879
- grouped[resource] = [];
880
- }
881
- grouped[resource].push(mapping);
882
- }
883
- return grouped;
884
- }
885
- function extractResourceName(path) {
886
- let processedPath = path;
887
- if (!processedPath.startsWith("/")) {
888
- processedPath = "/" + processedPath;
889
- }
890
- const segments = processedPath.slice(1).split("/").filter((s) => s && s !== "*");
891
- const staticSegments = [];
892
- for (let i = 0; i < segments.length; i++) {
893
- const seg = segments[i];
894
- if (!seg.startsWith(":")) {
895
- staticSegments.push(seg);
896
- }
897
- }
898
- if (staticSegments.length === 0) {
899
- return "root";
900
- }
901
- const first = toCamelCase(staticSegments[0], false);
902
- if (staticSegments.length === 1) {
903
- return first;
904
- }
905
- const result = [first];
906
- for (let i = 1; i < staticSegments.length; i++) {
907
- const seg = staticSegments[i];
908
- result.push(toCamelCase(seg, true));
909
- }
910
- return result.join("");
911
- }
912
- function toCamelCase(str, capitalize) {
913
- const parts = str.split(/[-_]/);
914
- if (parts.length === 1) {
915
- return capitalize ? str.charAt(0).toUpperCase() + str.slice(1) : str;
916
- }
917
- const result = [];
918
- for (let i = 0; i < parts.length; i++) {
919
- const part = parts[i];
920
- if (i === 0 && !capitalize) {
921
- result.push(part);
922
- } else {
923
- result.push(part.charAt(0).toUpperCase() + part.slice(1));
924
- }
925
- }
926
- return result.join("");
927
- }
928
-
929
- // src/codegen/built-in/contract/emitter.ts
930
- async function generateClient(mappings, options) {
931
- const startTime = Date.now();
932
- const grouped = groupByResource(mappings);
933
- const resourceNames = Object.keys(grouped);
934
- await generateSplitClient(mappings, grouped, options);
935
- return {
936
- routesScanned: mappings.length,
937
- contractsFound: mappings.length,
938
- contractFiles: countUniqueContractFiles(mappings),
939
- resourcesGenerated: resourceNames.length,
940
- methodsGenerated: mappings.length,
941
- duration: Date.now() - startTime
942
- };
943
- }
944
- function generateHeader() {
945
- return `/**
946
- * Auto-generated API Client
947
- *
948
- * Generated by @spfn/core codegen
949
- * DO NOT EDIT MANUALLY
950
- *
951
- * @generated ${(/* @__PURE__ */ new Date()).toISOString()}
952
- */
953
-
954
- `;
955
- }
956
- function groupContractsByImportPath(mappings) {
957
- const groups = {};
958
- for (let i = 0; i < mappings.length; i++) {
959
- const mapping = mappings[i];
960
- const path = mapping.contractImportPath;
961
- if (!groups[path]) {
962
- groups[path] = /* @__PURE__ */ new Set();
963
- }
964
- groups[path].add(mapping.contractName);
965
- }
966
- const result = {};
967
- const keys = Object.keys(groups);
968
- for (let i = 0; i < keys.length; i++) {
969
- const key = keys[i];
970
- result[key] = Array.from(groups[key]);
971
- }
972
- return result;
973
- }
974
- function generateTypeName(mapping) {
975
- let name = mapping.contractName;
976
- if (name.endsWith("Contract")) {
977
- name = name.slice(0, -8);
978
- }
979
- if (name.length > 0) {
980
- name = name.charAt(0).toUpperCase() + name.slice(1);
981
- }
982
- return name;
983
- }
984
- function generateFunctionName(mapping) {
985
- let name = mapping.contractName;
986
- if (name.endsWith("Contract")) {
987
- name = name.slice(0, -8);
988
- }
989
- return name;
990
- }
991
- function generateFunctionCode(mapping, options) {
992
- const functionName = generateFunctionName(mapping);
993
- const hasParams = mapping.hasParams || mapping.path.includes(":");
994
- const hasQuery = mapping.hasQuery || false;
995
- const hasBody = mapping.hasBody || false;
996
- let code = "";
997
- if (options.includeJsDoc !== false) {
998
- code += `/**
999
- `;
1000
- code += ` * ${mapping.method} ${mapping.path}
1001
- `;
1002
- code += ` */
1003
- `;
1004
- }
1005
- code += `export const ${functionName} = (`;
1006
- const params = [];
1007
- const typeName = generateTypeName(mapping);
1008
- if (hasParams) {
1009
- params.push(`params: ${typeName}Params`);
1010
- }
1011
- if (hasQuery) {
1012
- params.push(`query?: ${typeName}Query`);
1013
- }
1014
- if (hasBody) {
1015
- params.push(`body: ${typeName}Body`);
1016
- }
1017
- if (params.length > 0) {
1018
- code += `options: { ${params.join(", ")} }`;
1019
- }
1020
- code += `) => `;
1021
- code += `client.call(${mapping.contractName}`;
1022
- if (params.length > 0) {
1023
- code += `, options`;
1024
- }
1025
- code += `);
1026
-
1027
- `;
1028
- return code;
1029
- }
1030
- function countUniqueContractFiles(mappings) {
1031
- const files = /* @__PURE__ */ new Set();
1032
- for (let i = 0; i < mappings.length; i++) {
1033
- if (mappings[i].contractFile) {
1034
- files.add(mappings[i].contractFile);
1035
- }
1036
- }
1037
- return files.size;
1038
- }
1039
- function toKebabCase(str) {
1040
- if (str.length === 0) {
1041
- return str;
1042
- }
1043
- return str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
1044
- }
1045
- async function generateSplitClient(_mappings, grouped, options) {
1046
- const outputPath = options.outputPath;
1047
- const outputDir = outputPath.endsWith(".ts") || outputPath.endsWith(".js") ? outputPath.replace(/\.[jt]s$/, "") : outputPath;
1048
- await mkdir(outputDir, { recursive: true });
1049
- const resourceNames = Object.keys(grouped);
1050
- for (let i = 0; i < resourceNames.length; i++) {
1051
- const resourceName = resourceNames[i];
1052
- const routes = grouped[resourceName];
1053
- const code = generateResourceFile(resourceName, routes, options);
1054
- const kebabName = toKebabCase(resourceName);
1055
- const filePath = `${outputDir}/${kebabName}.ts`;
1056
- await writeFile(filePath, code, "utf-8");
1057
- }
1058
- const indexCode = generateIndexFile(grouped, options);
1059
- const indexPath = `${outputDir}/index.ts`;
1060
- await writeFile(indexPath, indexCode, "utf-8");
1061
- }
1062
- function generateResourceFile(_resourceName, routes, options) {
1063
- let code = "";
1064
- code += generateHeader();
1065
- code += `import { client } from '@spfn/core/client';
1066
- `;
1067
- if (options.includeTypes !== false) {
1068
- code += `import type { InferContract } from '@spfn/core';
1069
- `;
1070
- }
1071
- code += `
1072
- `;
1073
- const importGroups = groupContractsByImportPath(routes);
1074
- const importPaths = Object.keys(importGroups);
1075
- for (let i = 0; i < importPaths.length; i++) {
1076
- const importPath = importPaths[i];
1077
- const contracts = importGroups[importPath];
1078
- code += `import { ${contracts.join(", ")} } from '${importPath}';
1079
- `;
1080
- }
1081
- code += `
1082
- `;
1083
- if (options.includeTypes !== false) {
1084
- code += `// ============================================
1085
- `;
1086
- code += `// Types
1087
- `;
1088
- code += `// ============================================
1089
-
1090
- `;
1091
- for (let i = 0; i < routes.length; i++) {
1092
- const route = routes[i];
1093
- const typeName = generateTypeName(route);
1094
- const contractType = `typeof ${route.contractName}`;
1095
- code += `export type ${typeName}Response = InferContract<${contractType}>['response'];
1096
- `;
1097
- if (route.hasQuery) {
1098
- code += `export type ${typeName}Query = InferContract<${contractType}>['query'];
1099
- `;
1100
- }
1101
- if (route.hasParams || route.path.includes(":")) {
1102
- code += `export type ${typeName}Params = InferContract<${contractType}>['params'];
1103
- `;
1104
- }
1105
- if (route.hasBody) {
1106
- code += `export type ${typeName}Body = InferContract<${contractType}>['body'];
1107
- `;
1108
- }
1109
- code += `
1110
- `;
1111
- }
1112
- }
1113
- code += `// ============================================
1114
- `;
1115
- code += `// API Functions
1116
- `;
1117
- code += `// ============================================
1118
-
1119
- `;
1120
- for (let i = 0; i < routes.length; i++) {
1121
- const route = routes[i];
1122
- code += generateFunctionCode(route, options);
1123
- }
1124
- return code;
1125
- }
1126
- function generateIndexFile(grouped, options) {
1127
- let code = "";
1128
- const apiName = options.apiName || "api";
1129
- const resourceNames = Object.keys(grouped);
1130
- code += generateHeader();
1131
- code += `export { client } from '@spfn/core/client';
1132
-
1133
- `;
1134
- for (let i = 0; i < resourceNames.length; i++) {
1135
- const resourceName = resourceNames[i];
1136
- const routes = grouped[resourceName];
1137
- const kebabName = toKebabCase(resourceName);
1138
- const typeNames = [];
1139
- for (let j = 0; j < routes.length; j++) {
1140
- const route = routes[j];
1141
- const typeName = generateTypeName(route);
1142
- typeNames.push(`${typeName}Response`);
1143
- if (route.hasQuery) {
1144
- typeNames.push(`${typeName}Query`);
1145
- }
1146
- if (route.hasParams || route.path.includes(":")) {
1147
- typeNames.push(`${typeName}Params`);
1148
- }
1149
- if (route.hasBody) {
1150
- typeNames.push(`${typeName}Body`);
1151
- }
1152
- }
1153
- if (typeNames.length > 0) {
1154
- code += `export type { ${typeNames.join(", ")} } from './${kebabName}';
1155
- `;
1156
- }
1157
- }
1158
- code += `
1159
- `;
1160
- for (let i = 0; i < resourceNames.length; i++) {
1161
- const resourceName = resourceNames[i];
1162
- const routes = grouped[resourceName];
1163
- const kebabName = toKebabCase(resourceName);
1164
- const functionNames = routes.map((route) => generateFunctionName(route));
1165
- code += `import { ${functionNames.join(", ")} } from './${kebabName}';
1166
- `;
1167
- }
1168
- code += `
1169
- `;
1170
- code += `/**
1171
- `;
1172
- code += ` * Type-safe API client
1173
- `;
1174
- code += ` */
1175
- `;
1176
- code += `export const ${apiName} = {
1177
- `;
1178
- let isFirst = true;
1179
- for (let i = 0; i < resourceNames.length; i++) {
1180
- const resourceName = resourceNames[i];
1181
- const routes = grouped[resourceName];
1182
- for (let j = 0; j < routes.length; j++) {
1183
- const route = routes[j];
1184
- const functionName = generateFunctionName(route);
1185
- if (!isFirst) {
1186
- code += `,
1187
- `;
1188
- }
1189
- code += ` ${functionName}`;
1190
- isFirst = false;
1191
- }
1192
- }
1193
- code += `
1194
- } as const;
1195
- `;
1196
- return code;
1197
- }
1198
-
1199
- // src/codegen/built-in/contract/index.ts
1200
- var contractLogger = logger.child("contract-gen");
1201
- var DEFAULT_CONTRACTS_DIR = "src/lib/contracts";
1202
- var DEFAULT_OUTPUT_PATH = "src/lib/api";
1203
- var contractCache = null;
1204
- function needsFullRegeneration(event) {
1205
- if (event === "add" || event === "unlink") {
1206
- return true;
1207
- }
1208
- if (!contractCache) {
1209
- return true;
1210
- }
1211
- return false;
1212
- }
1213
- function createClientOptions(contractsDir, outputPath, baseUrl, apiName) {
1214
- return {
1215
- routesDir: contractsDir,
1216
- outputPath,
1217
- baseUrl,
1218
- apiName,
1219
- includeTypes: true,
1220
- includeJsDoc: true,
1221
- splitByResource: true
1222
- };
1223
- }
1224
- function generateApiName(prefix) {
1225
- if (!prefix || prefix === "/api") {
1226
- return "api";
1227
- }
1228
- const name = prefix.replace(/^\/[_-]?/, "").replace(/[_-]/g, "");
1229
- if (!name) {
1230
- return "api";
1231
- }
1232
- return `${name}Api`;
1233
- }
1234
- function readPrefixFromPackageJson(cwd) {
1235
- try {
1236
- const packageJsonPath = join(cwd, "package.json");
1237
- if (!existsSync(packageJsonPath)) {
1238
- return void 0;
1239
- }
1240
- const content = readFileSync(packageJsonPath, "utf-8");
1241
- const packageJson = JSON.parse(content);
1242
- return packageJson.spfn?.prefix;
1243
- } catch (error) {
1244
- return void 0;
1245
- }
1246
- }
1247
- function createContractGenerator(config = {}) {
1248
- const contractsDir = config.contractsDir ?? DEFAULT_CONTRACTS_DIR;
1249
- const outputPath = config.outputPath ?? DEFAULT_OUTPUT_PATH;
1250
- const runOn = config.runOn ?? ["watch", "manual", "build"];
1251
- return {
1252
- name: "contract",
1253
- watchPatterns: [
1254
- `${contractsDir}/**/*.ts`
1255
- ],
1256
- runOn,
1257
- async generate(options) {
1258
- const cwd = options.cwd;
1259
- const fullContractsDir = join(cwd, contractsDir);
1260
- const fullOutputPath = join(cwd, outputPath);
1261
- const prefix = readPrefixFromPackageJson(cwd);
1262
- const apiName = generateApiName(prefix);
1263
- try {
1264
- if (!existsSync(fullContractsDir)) {
1265
- if (options.debug) {
1266
- contractLogger.warn(`No contracts directory found at ${contractsDir}`);
1267
- }
1268
- return;
1269
- }
1270
- const changedFile = options.trigger?.changedFile;
1271
- if (changedFile && !needsFullRegeneration(changedFile.event)) {
1272
- if (options.debug) {
1273
- contractLogger.info("Attempting incremental update", {
1274
- file: changedFile.path,
1275
- event: changedFile.event
1276
- });
1277
- }
1278
- const success = await attemptIncrementalUpdate({
1279
- cwd,
1280
- contractsDir: fullContractsDir,
1281
- outputPath: fullOutputPath,
1282
- changedFilePath: changedFile.path,
1283
- baseUrl: config.baseUrl,
1284
- apiName,
1285
- debug: options.debug
1286
- });
1287
- if (success) {
1288
- if (options.debug) {
1289
- contractLogger.info("Incremental update successful");
1290
- }
1291
- return;
1292
- }
1293
- if (options.debug) {
1294
- contractLogger.info("Incremental update failed, doing full regen");
1295
- }
1296
- }
1297
- const allContracts = await scanContracts(fullContractsDir, prefix);
1298
- if (allContracts.length === 0) {
1299
- if (options.debug) {
1300
- contractLogger.warn("No contracts found");
1301
- }
1302
- contractCache = null;
1303
- return;
1304
- }
1305
- const clientOptions = createClientOptions(fullContractsDir, fullOutputPath, config.baseUrl, apiName);
1306
- const stats = await generateClient(allContracts, clientOptions);
1307
- contractCache = {
1308
- contracts: allContracts,
1309
- lastScan: Date.now()
1310
- };
1311
- if (options.debug) {
1312
- contractLogger.info("Client generated", {
1313
- endpoints: stats.methodsGenerated,
1314
- resources: stats.resourcesGenerated,
1315
- duration: stats.duration,
1316
- mode: changedFile ? "incremental-fallback" : "full"
1317
- });
1318
- }
1319
- } catch (error) {
1320
- const err = error instanceof Error ? error : new Error(String(error));
1321
- contractLogger.error("Generation failed", err);
1322
- throw err;
1323
- }
1324
- }
1325
- };
1326
- }
1327
- async function attemptIncrementalUpdate(options) {
1328
- const { cwd, contractsDir, outputPath, changedFilePath, baseUrl, apiName, debug } = options;
1329
- if (!contractCache) {
1330
- return false;
1331
- }
1332
- try {
1333
- const fullPath = join(cwd, changedFilePath);
1334
- if (!existsSync(fullPath)) {
1335
- return false;
1336
- }
1337
- const updatedContracts = await scanContracts(contractsDir);
1338
- if (updatedContracts.length === 0) {
1339
- contractCache = null;
1340
- return false;
1341
- }
1342
- const changedContracts = findChangedContracts(
1343
- contractCache.contracts,
1344
- updatedContracts,
1345
- changedFilePath
1346
- );
1347
- if (changedContracts.size === 0) {
1348
- if (debug) {
1349
- contractLogger.info("No contract changes detected, skipping regeneration");
1350
- }
1351
- return true;
1352
- }
1353
- const clientOptions = createClientOptions(contractsDir, outputPath, baseUrl, apiName);
1354
- const stats = await generateClient(updatedContracts, clientOptions);
1355
- contractCache = {
1356
- contracts: updatedContracts,
1357
- lastScan: Date.now()
1358
- };
1359
- if (debug) {
1360
- contractLogger.info("Incremental update successful", {
1361
- changedContracts: changedContracts.size,
1362
- endpoints: stats.methodsGenerated,
1363
- resources: stats.resourcesGenerated,
1364
- duration: stats.duration
1365
- });
1366
- }
1367
- return true;
1368
- } catch (error) {
1369
- if (debug) {
1370
- const err = error instanceof Error ? error : new Error(String(error));
1371
- contractLogger.warn("Incremental update failed", err);
1372
- }
1373
- return false;
1374
- }
1375
- }
1376
- function findChangedContracts(oldContracts, newContracts, changedFilePath) {
1377
- const changed = /* @__PURE__ */ new Set();
1378
- const oldInFile = oldContracts.filter((c) => c.contractFile?.includes(changedFilePath));
1379
- const newInFile = newContracts.filter((c) => c.contractFile?.includes(changedFilePath));
1380
- if (oldInFile.length !== newInFile.length) {
1381
- newInFile.forEach((c) => changed.add(c.contractName));
1382
- return changed;
1383
- }
1384
- for (const newContract of newInFile) {
1385
- const oldContract = oldInFile.find((c) => c.contractName === newContract.contractName);
1386
- if (!oldContract) {
1387
- changed.add(newContract.contractName);
1388
- continue;
1389
- }
1390
- if (oldContract.method !== newContract.method || oldContract.path !== newContract.path || oldContract.hasQuery !== newContract.hasQuery || oldContract.hasBody !== newContract.hasBody || oldContract.hasParams !== newContract.hasParams) {
1391
- changed.add(newContract.contractName);
1392
- }
1393
- }
1394
- return changed;
1395
- }
1396
-
1397
- // src/codegen/generators/index.ts
1398
- var generators = {
1399
- contract: createContractGenerator
1400
- };
1401
-
1402
- export { createContractGenerator, generators };
1403
- //# sourceMappingURL=index.js.map
1404
- //# sourceMappingURL=index.js.map