clawfire 0.1.0

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 (87) hide show
  1. package/README.md +182 -0
  2. package/dist/admin.cjs +309 -0
  3. package/dist/admin.cjs.map +1 -0
  4. package/dist/admin.d.cts +93 -0
  5. package/dist/admin.d.ts +93 -0
  6. package/dist/admin.js +274 -0
  7. package/dist/admin.js.map +1 -0
  8. package/dist/auth-DQ3cifhb.d.cts +55 -0
  9. package/dist/auth-DtnUPbXT.d.ts +55 -0
  10. package/dist/chunk-37Y2XI7X.js +75 -0
  11. package/dist/chunk-YGIPORYL.js +339 -0
  12. package/dist/cli.js +241 -0
  13. package/dist/client.cjs +97 -0
  14. package/dist/client.cjs.map +1 -0
  15. package/dist/client.d.cts +4 -0
  16. package/dist/client.d.ts +4 -0
  17. package/dist/client.js +68 -0
  18. package/dist/client.js.map +1 -0
  19. package/dist/codegen.cjs +648 -0
  20. package/dist/codegen.cjs.map +1 -0
  21. package/dist/codegen.d.cts +25 -0
  22. package/dist/codegen.d.ts +25 -0
  23. package/dist/codegen.js +617 -0
  24. package/dist/codegen.js.map +1 -0
  25. package/dist/config-QMBJRn9G.d.cts +46 -0
  26. package/dist/config-QMBJRn9G.d.ts +46 -0
  27. package/dist/dev-server-QAVWINAT.js +973 -0
  28. package/dist/dev.cjs +1388 -0
  29. package/dist/dev.cjs.map +1 -0
  30. package/dist/dev.d.cts +111 -0
  31. package/dist/dev.d.ts +111 -0
  32. package/dist/dev.js +1349 -0
  33. package/dist/dev.js.map +1 -0
  34. package/dist/discover-BPMAZFBD.js +9 -0
  35. package/dist/discover-DYNqz_ym.d.cts +28 -0
  36. package/dist/discover-DYNqz_ym.d.ts +28 -0
  37. package/dist/errors-s_mP7rs9.d.cts +33 -0
  38. package/dist/errors-s_mP7rs9.d.ts +33 -0
  39. package/dist/functions.cjs +1156 -0
  40. package/dist/functions.cjs.map +1 -0
  41. package/dist/functions.d.cts +115 -0
  42. package/dist/functions.d.ts +115 -0
  43. package/dist/functions.js +1108 -0
  44. package/dist/functions.js.map +1 -0
  45. package/dist/hosting-7WVFHAYJ.js +85 -0
  46. package/dist/html-PCUCJGBH.js +7 -0
  47. package/dist/index.cjs +349 -0
  48. package/dist/index.cjs.map +1 -0
  49. package/dist/index.d.cts +22 -0
  50. package/dist/index.d.ts +22 -0
  51. package/dist/index.js +312 -0
  52. package/dist/index.js.map +1 -0
  53. package/dist/playground.cjs +364 -0
  54. package/dist/playground.cjs.map +1 -0
  55. package/dist/playground.d.cts +12 -0
  56. package/dist/playground.d.ts +12 -0
  57. package/dist/playground.js +337 -0
  58. package/dist/playground.js.map +1 -0
  59. package/dist/router-BVB_I-tu.d.ts +65 -0
  60. package/dist/router-Cikk8Heq.d.cts +65 -0
  61. package/dist/schema-BJsictSV.d.cts +172 -0
  62. package/dist/schema-BJsictSV.d.ts +172 -0
  63. package/package.json +150 -0
  64. package/templates/CLAUDE.md +71 -0
  65. package/templates/app/routes/auth/login.ts +35 -0
  66. package/templates/app/routes/health.ts +20 -0
  67. package/templates/app/schemas/user.ts +26 -0
  68. package/templates/clawfire.config.ts +25 -0
  69. package/templates/functions/index.ts +43 -0
  70. package/templates/starter/.claude/skills/clawfire-api/SKILL.md +131 -0
  71. package/templates/starter/.claude/skills/clawfire-auth/SKILL.md +111 -0
  72. package/templates/starter/.claude/skills/clawfire-deploy/SKILL.md +95 -0
  73. package/templates/starter/.claude/skills/clawfire-diagnose/SKILL.md +99 -0
  74. package/templates/starter/.claude/skills/clawfire-model/SKILL.md +128 -0
  75. package/templates/starter/CLAUDE.md +227 -0
  76. package/templates/starter/app/routes/health.ts +20 -0
  77. package/templates/starter/app/routes/todos/create.ts +25 -0
  78. package/templates/starter/app/routes/todos/delete.ts +20 -0
  79. package/templates/starter/app/routes/todos/list.ts +26 -0
  80. package/templates/starter/app/routes/todos/update.ts +32 -0
  81. package/templates/starter/app/schemas/todo.ts +16 -0
  82. package/templates/starter/app/store.ts +56 -0
  83. package/templates/starter/clawfire.config.ts +25 -0
  84. package/templates/starter/dev.ts +12 -0
  85. package/templates/starter/package.json +19 -0
  86. package/templates/starter/public/index.html +365 -0
  87. package/templates/starter/tsconfig.json +17 -0
@@ -0,0 +1,973 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ discoverRoutes
4
+ } from "./chunk-37Y2XI7X.js";
5
+ import {
6
+ generatePlaygroundHtml
7
+ } from "./chunk-YGIPORYL.js";
8
+
9
+ // src/dev/dev-server.ts
10
+ import http from "http";
11
+ import { resolve, relative } from "path";
12
+ import { existsSync as existsSync2, readFileSync } from "fs";
13
+ import { pathToFileURL } from "url";
14
+
15
+ // src/core/schema.ts
16
+ import { z } from "zod";
17
+ function zodToJsonSchema(schema) {
18
+ return extractZodShape(schema);
19
+ }
20
+ function extractZodShape(schema) {
21
+ const def = schema._def;
22
+ if (!def) return { type: "unknown" };
23
+ switch (def.typeName) {
24
+ case "ZodObject": {
25
+ const shape = schema.shape;
26
+ const properties = {};
27
+ const required = [];
28
+ for (const [key, value] of Object.entries(shape)) {
29
+ properties[key] = extractZodShape(value);
30
+ if (!value.isOptional?.()) {
31
+ const innerDef = value._def;
32
+ if (innerDef?.typeName !== "ZodOptional" && innerDef?.typeName !== "ZodDefault") {
33
+ required.push(key);
34
+ }
35
+ }
36
+ }
37
+ return { type: "object", properties, ...required.length > 0 ? { required } : {} };
38
+ }
39
+ case "ZodString":
40
+ return { type: "string", ...def.checks?.length ? extractStringChecks(def.checks) : {} };
41
+ case "ZodNumber":
42
+ return { type: "number" };
43
+ case "ZodBoolean":
44
+ return { type: "boolean" };
45
+ case "ZodArray":
46
+ return { type: "array", items: extractZodShape(def.type) };
47
+ case "ZodEnum":
48
+ return { type: "string", enum: def.values };
49
+ case "ZodOptional":
50
+ return { ...extractZodShape(def.innerType), optional: true };
51
+ case "ZodDefault":
52
+ return { ...extractZodShape(def.innerType), default: def.defaultValue() };
53
+ case "ZodNullable":
54
+ return { ...extractZodShape(def.innerType), nullable: true };
55
+ case "ZodLiteral":
56
+ return { type: typeof def.value, const: def.value };
57
+ case "ZodUnion":
58
+ return { oneOf: def.options.map((o) => extractZodShape(o)) };
59
+ case "ZodRecord":
60
+ return { type: "object", additionalProperties: extractZodShape(def.valueType) };
61
+ case "ZodDate":
62
+ return { type: "string", format: "date-time" };
63
+ default:
64
+ return { type: "unknown" };
65
+ }
66
+ }
67
+ function extractStringChecks(checks) {
68
+ const result = {};
69
+ for (const check of checks) {
70
+ switch (check.kind) {
71
+ case "min":
72
+ result.minLength = check.value;
73
+ break;
74
+ case "max":
75
+ result.maxLength = check.value;
76
+ break;
77
+ case "email":
78
+ result.format = "email";
79
+ break;
80
+ case "url":
81
+ result.format = "uri";
82
+ break;
83
+ case "uuid":
84
+ result.format = "uuid";
85
+ break;
86
+ }
87
+ }
88
+ return result;
89
+ }
90
+ function contractToManifest(path, contract) {
91
+ return {
92
+ path,
93
+ method: "POST",
94
+ meta: contract.meta,
95
+ inputSchema: zodToJsonSchema(contract.input),
96
+ outputSchema: zodToJsonSchema(contract.output)
97
+ };
98
+ }
99
+
100
+ // src/core/errors.ts
101
+ var HTTP_STATUS_MAP = {
102
+ VALIDATION_ERROR: 400,
103
+ UNAUTHORIZED: 401,
104
+ FORBIDDEN: 403,
105
+ NOT_FOUND: 404,
106
+ CONFLICT: 409,
107
+ RATE_LIMITED: 429,
108
+ REAUTH_REQUIRED: 401,
109
+ INTERNAL_ERROR: 500,
110
+ SERVICE_UNAVAILABLE: 503
111
+ };
112
+ var ClawfireError = class extends Error {
113
+ code;
114
+ statusCode;
115
+ details;
116
+ constructor(code, message, details) {
117
+ super(message);
118
+ this.name = "ClawfireError";
119
+ this.code = code;
120
+ this.statusCode = HTTP_STATUS_MAP[code];
121
+ this.details = details;
122
+ }
123
+ toJSON() {
124
+ return {
125
+ error: {
126
+ code: this.code,
127
+ message: this.message,
128
+ ...this.details ? { details: this.details } : {}
129
+ }
130
+ };
131
+ }
132
+ };
133
+ var Errors = {
134
+ validation: (message, details) => new ClawfireError("VALIDATION_ERROR", message, details),
135
+ unauthorized: (message = "Authentication required") => new ClawfireError("UNAUTHORIZED", message),
136
+ forbidden: (message = "Insufficient permissions") => new ClawfireError("FORBIDDEN", message),
137
+ notFound: (message = "Resource not found") => new ClawfireError("NOT_FOUND", message),
138
+ conflict: (message) => new ClawfireError("CONFLICT", message),
139
+ rateLimited: (message = "Too many requests") => new ClawfireError("RATE_LIMITED", message),
140
+ reauthRequired: (message = "Re-authentication required for this action") => new ClawfireError("REAUTH_REQUIRED", message),
141
+ internal: (message = "Internal server error") => new ClawfireError("INTERNAL_ERROR", message),
142
+ unavailable: (message = "Service temporarily unavailable") => new ClawfireError("SERVICE_UNAVAILABLE", message)
143
+ };
144
+
145
+ // src/core/logger.ts
146
+ var SENSITIVE_FIELDS = [
147
+ "password",
148
+ "token",
149
+ "secret",
150
+ "apiKey",
151
+ "api_key",
152
+ "authorization",
153
+ "credit_card",
154
+ "creditCard",
155
+ "ssn",
156
+ "cardNumber",
157
+ "card_number",
158
+ "cvv",
159
+ "pin"
160
+ ];
161
+ var LOG_LEVELS = {
162
+ debug: 0,
163
+ info: 1,
164
+ warn: 2,
165
+ error: 3
166
+ };
167
+ var currentLevel = "info";
168
+ function shouldLog(level) {
169
+ return LOG_LEVELS[level] >= LOG_LEVELS[currentLevel];
170
+ }
171
+ function maskSensitive(obj) {
172
+ if (obj === null || obj === void 0) return obj;
173
+ if (typeof obj === "string") return obj;
174
+ if (typeof obj !== "object") return obj;
175
+ if (Array.isArray(obj)) {
176
+ return obj.map(maskSensitive);
177
+ }
178
+ const masked = {};
179
+ for (const [key, value] of Object.entries(obj)) {
180
+ if (SENSITIVE_FIELDS.some((f) => key.toLowerCase().includes(f.toLowerCase()))) {
181
+ masked[key] = "***MASKED***";
182
+ } else if (typeof value === "object" && value !== null) {
183
+ masked[key] = maskSensitive(value);
184
+ } else {
185
+ masked[key] = value;
186
+ }
187
+ }
188
+ return masked;
189
+ }
190
+ function formatLog(level, message, data) {
191
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
192
+ const prefix = `[${timestamp}] [CLAWFIRE] [${level.toUpperCase()}]`;
193
+ if (data !== void 0) {
194
+ return `${prefix} ${message} ${JSON.stringify(maskSensitive(data))}`;
195
+ }
196
+ return `${prefix} ${message}`;
197
+ }
198
+ var logger = {
199
+ debug(message, data) {
200
+ if (shouldLog("debug")) console.debug(formatLog("debug", message, data));
201
+ },
202
+ info(message, data) {
203
+ if (shouldLog("info")) console.info(formatLog("info", message, data));
204
+ },
205
+ warn(message, data) {
206
+ if (shouldLog("warn")) console.warn(formatLog("warn", message, data));
207
+ },
208
+ error(message, data) {
209
+ if (shouldLog("error")) console.error(formatLog("error", message, data));
210
+ }
211
+ };
212
+
213
+ // src/firebase/auth.ts
214
+ async function verifyToken(auth, idToken) {
215
+ const decoded = await auth.verifyIdToken(idToken);
216
+ return {
217
+ uid: decoded.uid,
218
+ email: decoded.email,
219
+ emailVerified: decoded.email_verified,
220
+ role: decoded.role || decoded.customClaims?.role,
221
+ customClaims: decoded,
222
+ token: idToken
223
+ };
224
+ }
225
+ async function verifyReauth(auth, idToken, maxAgeSeconds = 300) {
226
+ const decoded = await auth.verifyIdToken(idToken, true);
227
+ const authTime = decoded.auth_time * 1e3;
228
+ const now = Date.now();
229
+ if (now - authTime > maxAgeSeconds * 1e3) {
230
+ throw Errors.reauthRequired(
231
+ `Re-authentication required. Last auth was ${Math.floor((now - authTime) / 1e3)}s ago.`
232
+ );
233
+ }
234
+ return {
235
+ uid: decoded.uid,
236
+ email: decoded.email,
237
+ emailVerified: decoded.email_verified,
238
+ role: decoded.role || decoded.customClaims?.role,
239
+ customClaims: decoded,
240
+ token: idToken
241
+ };
242
+ }
243
+ function extractBearerToken(authHeader) {
244
+ if (!authHeader) return null;
245
+ const parts = authHeader.split(" ");
246
+ if (parts.length !== 2 || parts[0] !== "Bearer") return null;
247
+ return parts[1];
248
+ }
249
+ function checkAuthLevel(authCtx, level, roles, reauthenticated) {
250
+ switch (level) {
251
+ case "public":
252
+ return;
253
+ // 누구나 접근 가능
254
+ case "authenticated":
255
+ if (!authCtx) throw Errors.unauthorized();
256
+ return;
257
+ case "role":
258
+ if (!authCtx) throw Errors.unauthorized();
259
+ if (!roles || roles.length === 0) return;
260
+ if (!authCtx.role || !roles.includes(authCtx.role)) {
261
+ throw Errors.forbidden(`Required role: ${roles.join(" or ")}`);
262
+ }
263
+ return;
264
+ case "reauth":
265
+ if (!authCtx) throw Errors.unauthorized();
266
+ if (!reauthenticated) {
267
+ throw Errors.reauthRequired();
268
+ }
269
+ return;
270
+ }
271
+ }
272
+
273
+ // src/routing/router.ts
274
+ var RateLimiter = class {
275
+ store = /* @__PURE__ */ new Map();
276
+ defaultLimit;
277
+ constructor(defaultLimit) {
278
+ this.defaultLimit = defaultLimit;
279
+ }
280
+ check(key, limit) {
281
+ const max = limit || this.defaultLimit;
282
+ const now = Date.now();
283
+ const entry = this.store.get(key);
284
+ if (!entry || now > entry.resetAt) {
285
+ this.store.set(key, { count: 1, resetAt: now + 6e4 });
286
+ return true;
287
+ }
288
+ if (entry.count >= max) {
289
+ return false;
290
+ }
291
+ entry.count++;
292
+ return true;
293
+ }
294
+ // 오래된 엔트리 정리
295
+ cleanup() {
296
+ const now = Date.now();
297
+ for (const [key, entry] of this.store) {
298
+ if (now > entry.resetAt) this.store.delete(key);
299
+ }
300
+ }
301
+ };
302
+ var ClawfireRouter = class {
303
+ routes = /* @__PURE__ */ new Map();
304
+ options;
305
+ rateLimiter;
306
+ cleanupInterval;
307
+ constructor(options = {}) {
308
+ this.options = options;
309
+ this.rateLimiter = new RateLimiter(options.rateLimit || 100);
310
+ this.cleanupInterval = setInterval(() => this.rateLimiter.cleanup(), 6e4);
311
+ }
312
+ /** 라우트 등록 */
313
+ register(path, contract) {
314
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
315
+ this.routes.set(normalizedPath, { path: normalizedPath, contract });
316
+ logger.debug(`Route registered: ${normalizedPath}`);
317
+ return this;
318
+ }
319
+ /** 여러 라우트 한 번에 등록 */
320
+ registerAll(routes) {
321
+ for (const [path, contract] of Object.entries(routes)) {
322
+ this.register(path, contract);
323
+ }
324
+ return this;
325
+ }
326
+ /** 매니페스트 생성 */
327
+ getManifest() {
328
+ const apis = [];
329
+ for (const [path, route] of this.routes) {
330
+ apis.push(contractToManifest(path, route.contract));
331
+ }
332
+ return {
333
+ version: "1.0.0",
334
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
335
+ apis,
336
+ models: {}
337
+ };
338
+ }
339
+ /** HTTP 요청 핸들러 (Firebase Functions에서 사용) */
340
+ async handleRequest(req, res) {
341
+ const corsOrigins = this.options.cors || [];
342
+ const origin = req.headers?.origin || req.headers?.Origin || "";
343
+ if (corsOrigins.length > 0 && corsOrigins.includes(origin)) {
344
+ res.set({
345
+ "Access-Control-Allow-Origin": origin,
346
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
347
+ "Access-Control-Allow-Headers": "Content-Type, Authorization",
348
+ "Access-Control-Max-Age": "86400"
349
+ });
350
+ } else if (corsOrigins.length === 0) {
351
+ res.set({
352
+ "Access-Control-Allow-Origin": "",
353
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
354
+ "Access-Control-Allow-Headers": "Content-Type, Authorization"
355
+ });
356
+ }
357
+ if (req.method === "OPTIONS") {
358
+ res.status(204).end();
359
+ return;
360
+ }
361
+ res.set({
362
+ "X-Content-Type-Options": "nosniff",
363
+ "X-Frame-Options": "DENY",
364
+ "X-XSS-Protection": "1; mode=block",
365
+ "Content-Type": "application/json"
366
+ });
367
+ let routePath = req.path || req.url || "";
368
+ if (routePath.startsWith("/api")) {
369
+ routePath = routePath.slice(4);
370
+ }
371
+ if (routePath === "/__manifest") {
372
+ res.status(200).json(this.getManifest());
373
+ return;
374
+ }
375
+ if (req.method && req.method !== "POST") {
376
+ res.status(405).json({ error: { code: "METHOD_NOT_ALLOWED", message: "Only POST is allowed" } });
377
+ return;
378
+ }
379
+ const route = this.matchRoute(routePath);
380
+ if (!route) {
381
+ res.status(404).json({ error: { code: "NOT_FOUND", message: `API not found: ${routePath}` } });
382
+ return;
383
+ }
384
+ try {
385
+ const clientKey = req.ip || "unknown";
386
+ const rateLimit = route.contract.meta.rateLimit || this.options.rateLimit;
387
+ if (rateLimit && !this.rateLimiter.check(clientKey, rateLimit)) {
388
+ throw Errors.rateLimited();
389
+ }
390
+ let authCtx = null;
391
+ let reauthenticated = false;
392
+ const authHeader = req.headers?.authorization || req.headers?.Authorization;
393
+ if (authHeader && this.options.auth) {
394
+ const token = extractBearerToken(authHeader);
395
+ if (token) {
396
+ if (route.contract.meta.reauth || route.contract.meta.auth === "reauth") {
397
+ authCtx = await verifyReauth(this.options.auth, token);
398
+ reauthenticated = true;
399
+ } else {
400
+ authCtx = await verifyToken(this.options.auth, token);
401
+ }
402
+ }
403
+ }
404
+ if (route.contract.meta.auth) {
405
+ checkAuthLevel(authCtx, route.contract.meta.auth, route.contract.meta.roles, reauthenticated);
406
+ }
407
+ const rawInput = req.body || {};
408
+ const parsed = route.contract.input.safeParse(rawInput);
409
+ if (!parsed.success) {
410
+ throw Errors.validation("Invalid input", parsed.error.flatten());
411
+ }
412
+ const ctx = {
413
+ auth: authCtx,
414
+ reauthenticated,
415
+ headers: req.headers,
416
+ ip: req.ip
417
+ };
418
+ let result;
419
+ if (this.options.middleware && this.options.middleware.length > 0) {
420
+ result = await this.runMiddleware(
421
+ this.options.middleware,
422
+ parsed.data,
423
+ ctx,
424
+ () => route.contract.handler(parsed.data, ctx)
425
+ );
426
+ } else {
427
+ result = await route.contract.handler(parsed.data, ctx);
428
+ }
429
+ res.status(200).json({ data: result });
430
+ } catch (err) {
431
+ if (err instanceof ClawfireError) {
432
+ logger.warn(`API error [${err.code}]: ${err.message}`);
433
+ res.status(err.statusCode).json(err.toJSON());
434
+ } else {
435
+ logger.error("Unhandled error", err);
436
+ res.status(500).json({
437
+ error: {
438
+ code: "INTERNAL_ERROR",
439
+ message: "An unexpected error occurred"
440
+ }
441
+ });
442
+ }
443
+ }
444
+ }
445
+ /** 라우트 매칭 (동적 파라미터 지원) */
446
+ matchRoute(path) {
447
+ const exact = this.routes.get(path);
448
+ if (exact) return exact;
449
+ for (const [routePath, route] of this.routes) {
450
+ if (this.matchDynamicRoute(routePath, path)) {
451
+ return route;
452
+ }
453
+ }
454
+ return void 0;
455
+ }
456
+ matchDynamicRoute(pattern, actual) {
457
+ const patternParts = pattern.split("/").filter(Boolean);
458
+ const actualParts = actual.split("/").filter(Boolean);
459
+ if (patternParts.length !== actualParts.length) return false;
460
+ return patternParts.every(
461
+ (part, i) => part.startsWith(":") || part.startsWith("[") || part === actualParts[i]
462
+ );
463
+ }
464
+ /** 미들웨어 체인 실행 */
465
+ async runMiddleware(middlewares, input, ctx, handler) {
466
+ let index = 0;
467
+ const next = async () => {
468
+ if (index >= middlewares.length) {
469
+ return handler();
470
+ }
471
+ const mw = middlewares[index++];
472
+ return mw(input, ctx, next);
473
+ };
474
+ return next();
475
+ }
476
+ /** 등록된 라우트 목록 */
477
+ getRoutes() {
478
+ return Array.from(this.routes.values());
479
+ }
480
+ /** 리소스 정리 */
481
+ destroy() {
482
+ if (this.cleanupInterval) {
483
+ clearInterval(this.cleanupInterval);
484
+ }
485
+ }
486
+ };
487
+ function createRouter(options) {
488
+ return new ClawfireRouter(options);
489
+ }
490
+
491
+ // src/dev/watcher.ts
492
+ import { watch, existsSync, readdirSync } from "fs";
493
+ import { join, extname } from "path";
494
+ import { EventEmitter } from "events";
495
+ var FileWatcher = class extends EventEmitter {
496
+ watchers = [];
497
+ debounceTimers = /* @__PURE__ */ new Map();
498
+ debounceMs;
499
+ constructor(debounceMs = 150) {
500
+ super();
501
+ this.debounceMs = debounceMs;
502
+ }
503
+ /**
504
+ * 디렉터리 감시 시작
505
+ */
506
+ watchDir(dir, eventType) {
507
+ if (!existsSync(dir)) return this;
508
+ try {
509
+ const watcher = watch(dir, { recursive: true }, (event, filename) => {
510
+ if (!filename) return;
511
+ const filePath = join(dir, filename);
512
+ if (!this.isWatchedFile(filePath)) return;
513
+ this.emitDebounced(filePath, eventType);
514
+ });
515
+ watcher.on("error", (err) => {
516
+ if (err.code === "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM") {
517
+ this.watchDirRecursiveManual(dir, eventType);
518
+ }
519
+ });
520
+ this.watchers.push(watcher);
521
+ } catch {
522
+ this.watchDirRecursiveManual(dir, eventType);
523
+ }
524
+ return this;
525
+ }
526
+ /**
527
+ * 단일 파일 감시
528
+ */
529
+ watchFile(filePath, eventType) {
530
+ if (!existsSync(filePath)) return this;
531
+ const watcher = watch(filePath, (event) => {
532
+ this.emitDebounced(filePath, eventType);
533
+ });
534
+ this.watchers.push(watcher);
535
+ return this;
536
+ }
537
+ /**
538
+ * Linux fallback: 디렉터리 수동 재귀 감시
539
+ */
540
+ watchDirRecursiveManual(dir, eventType) {
541
+ if (!existsSync(dir)) return;
542
+ const watcher = watch(dir, (event, filename) => {
543
+ if (!filename) return;
544
+ const filePath = join(dir, filename);
545
+ if (!this.isWatchedFile(filePath)) return;
546
+ this.emitDebounced(filePath, eventType);
547
+ });
548
+ this.watchers.push(watcher);
549
+ try {
550
+ const entries = readdirSync(dir, { withFileTypes: true });
551
+ for (const entry of entries) {
552
+ if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
553
+ this.watchDirRecursiveManual(join(dir, entry.name), eventType);
554
+ }
555
+ }
556
+ } catch {
557
+ }
558
+ }
559
+ /**
560
+ * 감시 대상 파일인지 확인
561
+ */
562
+ isWatchedFile(filePath) {
563
+ const ext = extname(filePath);
564
+ return [".ts", ".tsx", ".js", ".jsx", ".json"].includes(ext);
565
+ }
566
+ /**
567
+ * 디바운스 이벤트 발생
568
+ */
569
+ emitDebounced(filePath, type) {
570
+ const existing = this.debounceTimers.get(filePath);
571
+ if (existing) clearTimeout(existing);
572
+ this.debounceTimers.set(
573
+ filePath,
574
+ setTimeout(() => {
575
+ this.debounceTimers.delete(filePath);
576
+ const event = { type, filePath, timestamp: Date.now() };
577
+ this.emit("change", event);
578
+ this.emit(type, event);
579
+ }, this.debounceMs)
580
+ );
581
+ }
582
+ /**
583
+ * 모든 감시 중지
584
+ */
585
+ close() {
586
+ for (const watcher of this.watchers) {
587
+ watcher.close();
588
+ }
589
+ this.watchers = [];
590
+ for (const timer of this.debounceTimers.values()) {
591
+ clearTimeout(timer);
592
+ }
593
+ this.debounceTimers.clear();
594
+ this.removeAllListeners();
595
+ }
596
+ };
597
+
598
+ // src/dev/dev-server.ts
599
+ var DevServer = class {
600
+ server = null;
601
+ router;
602
+ watcher = null;
603
+ sseClients = [];
604
+ sseIdCounter = 0;
605
+ options;
606
+ routesDir;
607
+ schemasDir;
608
+ playgroundHtml = "";
609
+ importCounter = 0;
610
+ // ESM 캐시 버스팅용
611
+ isReloading = false;
612
+ constructor(options = {}) {
613
+ this.options = {
614
+ projectDir: options.projectDir || process.cwd(),
615
+ port: options.port || 3456,
616
+ routerOptions: options.routerOptions || {},
617
+ hotReload: options.hotReload !== false,
618
+ debounceMs: options.debounceMs || 150,
619
+ onSetupRoutes: options.onSetupRoutes || (() => {
620
+ })
621
+ };
622
+ this.routesDir = resolve(this.options.projectDir, "app/routes");
623
+ this.schemasDir = resolve(this.options.projectDir, "app/schemas");
624
+ this.router = createRouter({
625
+ cors: ["*"],
626
+ // dev에서는 모든 origin 허용
627
+ rateLimit: 0,
628
+ // dev에서는 rate limit 비활성화
629
+ ...this.options.routerOptions
630
+ });
631
+ }
632
+ /**
633
+ * 개발 서버 시작
634
+ */
635
+ async start() {
636
+ await this.loadRoutes();
637
+ this.regeneratePlayground();
638
+ this.server = http.createServer((req, res) => this.handleHttpRequest(req, res));
639
+ if (this.options.hotReload) {
640
+ this.startWatcher();
641
+ }
642
+ await new Promise((resolve2, reject) => {
643
+ this.server.listen(this.options.port, () => {
644
+ resolve2();
645
+ });
646
+ this.server.on("error", reject);
647
+ });
648
+ this.printStartupBanner();
649
+ }
650
+ /**
651
+ * 서버 종료
652
+ */
653
+ async stop() {
654
+ this.watcher?.close();
655
+ for (const client of this.sseClients) {
656
+ client.res.end();
657
+ }
658
+ this.sseClients = [];
659
+ this.router.destroy();
660
+ if (this.server) {
661
+ await new Promise((resolve2) => {
662
+ this.server.close(() => resolve2());
663
+ });
664
+ }
665
+ }
666
+ // ─── Route Loading ─────────────────────────────────────────────────
667
+ /**
668
+ * 라우트 파일 로딩 (또는 수동 콜백)
669
+ */
670
+ async loadRoutes() {
671
+ this.router.destroy();
672
+ this.router = createRouter({
673
+ cors: ["*"],
674
+ rateLimit: 0,
675
+ ...this.options.routerOptions
676
+ });
677
+ if (this.options.onSetupRoutes) {
678
+ await this.options.onSetupRoutes(this.router);
679
+ if (this.router.getRoutes().length > 0) return;
680
+ }
681
+ if (!existsSync2(this.routesDir)) return;
682
+ const discovered = discoverRoutes(this.routesDir);
683
+ for (const route of discovered) {
684
+ try {
685
+ const fullPath = resolve(this.routesDir, route.filePath);
686
+ const fileUrl = pathToFileURL(fullPath).href;
687
+ const mod = await import(`${fileUrl}?v=${++this.importCounter}`);
688
+ const contract = mod.default;
689
+ if (contract && typeof contract.handler === "function" && contract.input && contract.output && contract.meta) {
690
+ this.router.register(route.apiPath, contract);
691
+ }
692
+ } catch (err) {
693
+ logger.warn(`Failed to load route: ${route.filePath}`, err);
694
+ }
695
+ }
696
+ }
697
+ /**
698
+ * 라우트 핫 리로드
699
+ */
700
+ async reloadRoutes(event) {
701
+ if (this.isReloading) return;
702
+ this.isReloading = true;
703
+ const relPath = relative(this.options.projectDir, event.filePath);
704
+ const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString();
705
+ console.log(`
706
+ \x1B[33m[${timestamp}]\x1B[0m \x1B[36m${relPath}\x1B[0m changed`);
707
+ console.log(" Reloading routes...");
708
+ try {
709
+ await this.loadRoutes();
710
+ this.regeneratePlayground();
711
+ const routeCount = this.router.getRoutes().length;
712
+ console.log(` \x1B[32m\u2713\x1B[0m ${routeCount} routes loaded`);
713
+ this.broadcastSSE({
714
+ type: event.type,
715
+ file: relPath,
716
+ timestamp: event.timestamp,
717
+ routes: routeCount
718
+ });
719
+ } catch (err) {
720
+ console.log(` \x1B[31m\u2717\x1B[0m Reload failed:`, err);
721
+ this.broadcastSSE({
722
+ type: "error",
723
+ file: relPath,
724
+ message: err instanceof Error ? err.message : "Unknown error"
725
+ });
726
+ } finally {
727
+ this.isReloading = false;
728
+ }
729
+ }
730
+ // ─── File Watcher ──────────────────────────────────────────────────
731
+ startWatcher() {
732
+ this.watcher = new FileWatcher(this.options.debounceMs);
733
+ if (existsSync2(this.routesDir)) {
734
+ this.watcher.watchDir(this.routesDir, "route-change");
735
+ }
736
+ if (existsSync2(this.schemasDir)) {
737
+ this.watcher.watchDir(this.schemasDir, "schema-change");
738
+ }
739
+ const configFile = resolve(this.options.projectDir, "clawfire.config.ts");
740
+ if (existsSync2(configFile)) {
741
+ this.watcher.watchFile(configFile, "config-change");
742
+ }
743
+ this.watcher.on("change", (event) => {
744
+ this.reloadRoutes(event);
745
+ });
746
+ }
747
+ // ─── SSE (Server-Sent Events) ──────────────────────────────────────
748
+ handleSSE(req, res) {
749
+ res.writeHead(200, {
750
+ "Content-Type": "text/event-stream",
751
+ "Cache-Control": "no-cache",
752
+ "Connection": "keep-alive",
753
+ "Access-Control-Allow-Origin": "*"
754
+ });
755
+ const clientId = ++this.sseIdCounter;
756
+ const client = { id: clientId, res };
757
+ this.sseClients.push(client);
758
+ res.write(`data: ${JSON.stringify({ type: "connected", id: clientId })}
759
+
760
+ `);
761
+ req.on("close", () => {
762
+ this.sseClients = this.sseClients.filter((c) => c.id !== clientId);
763
+ });
764
+ }
765
+ broadcastSSE(data) {
766
+ const message = `data: ${JSON.stringify(data)}
767
+
768
+ `;
769
+ for (const client of this.sseClients) {
770
+ try {
771
+ client.res.write(message);
772
+ } catch {
773
+ }
774
+ }
775
+ }
776
+ // ─── Playground ────────────────────────────────────────────────────
777
+ regeneratePlayground() {
778
+ const baseHtml = generatePlaygroundHtml({
779
+ title: "Clawfire Dev Playground",
780
+ apiBaseUrl: `http://localhost:${this.options.port}`
781
+ });
782
+ const liveReloadScript = `
783
+ <script>
784
+ (function() {
785
+ const banner = document.createElement('div');
786
+ banner.id = 'dev-banner';
787
+ banner.style.cssText = 'position:fixed;bottom:0;left:0;right:0;padding:6px 16px;background:#1a1a2e;color:#f97316;font-size:12px;font-family:monospace;z-index:9999;display:flex;align-items:center;gap:8px;border-top:1px solid #2a2a2a;';
788
+ banner.innerHTML = '<span style="width:8px;height:8px;border-radius:50%;background:#22c55e;display:inline-block;" id="dev-dot"></span><span>Clawfire Dev Server</span><span style="color:#666;margin-left:auto;" id="dev-status">Connected</span>';
789
+ document.body.appendChild(banner);
790
+
791
+ let reconnectTimer;
792
+ function connect() {
793
+ const es = new EventSource('http://localhost:${this.options.port}/__dev/events');
794
+
795
+ es.onopen = () => {
796
+ document.getElementById('dev-dot').style.background = '#22c55e';
797
+ document.getElementById('dev-status').textContent = 'Connected';
798
+ if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
799
+ };
800
+
801
+ es.onmessage = (e) => {
802
+ try {
803
+ const data = JSON.parse(e.data);
804
+ if (data.type === 'connected') return;
805
+
806
+ if (data.type === 'error') {
807
+ document.getElementById('dev-dot').style.background = '#ef4444';
808
+ document.getElementById('dev-status').textContent = 'Error: ' + (data.message || 'reload failed');
809
+ return;
810
+ }
811
+
812
+ // \uD30C\uC77C \uBCC0\uACBD \u2192 \uD398\uC774\uC9C0 \uC0C8\uB85C\uACE0\uCE68
813
+ document.getElementById('dev-dot').style.background = '#eab308';
814
+ document.getElementById('dev-status').textContent = 'Reloading...';
815
+ setTimeout(() => window.location.reload(), 300);
816
+ } catch {}
817
+ };
818
+
819
+ es.onerror = () => {
820
+ es.close();
821
+ document.getElementById('dev-dot').style.background = '#ef4444';
822
+ document.getElementById('dev-status').textContent = 'Disconnected \u2014 reconnecting...';
823
+ reconnectTimer = setTimeout(connect, 2000);
824
+ };
825
+ }
826
+
827
+ connect();
828
+ })();
829
+ </script>`;
830
+ this.playgroundHtml = baseHtml.replace("</body>", liveReloadScript + "\n</body>");
831
+ }
832
+ // ─── HTTP Request Handler ──────────────────────────────────────────
833
+ handleHttpRequest(req, res) {
834
+ const url = new URL(req.url || "/", `http://localhost:${this.options.port}`);
835
+ if (url.pathname === "/__dev/events") {
836
+ this.handleSSE(req, res);
837
+ return;
838
+ }
839
+ if (url.pathname === "/" || url.pathname === "/__playground") {
840
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
841
+ res.end(this.playgroundHtml);
842
+ return;
843
+ }
844
+ if (!url.pathname.startsWith("/api") && !url.pathname.startsWith("/__")) {
845
+ const publicDir = resolve(this.options.projectDir, "public");
846
+ const filePath = resolve(publicDir, url.pathname.slice(1));
847
+ if (existsSync2(filePath) && !filePath.includes("..")) {
848
+ try {
849
+ const content = readFileSync(filePath);
850
+ const ext = filePath.split(".").pop() || "";
851
+ const mimeTypes = {
852
+ html: "text/html",
853
+ css: "text/css",
854
+ js: "application/javascript",
855
+ json: "application/json",
856
+ png: "image/png",
857
+ jpg: "image/jpeg",
858
+ svg: "image/svg+xml",
859
+ ico: "image/x-icon",
860
+ woff2: "font/woff2"
861
+ };
862
+ res.writeHead(200, { "Content-Type": mimeTypes[ext] || "application/octet-stream" });
863
+ res.end(content);
864
+ return;
865
+ } catch {
866
+ }
867
+ }
868
+ }
869
+ if (url.pathname.startsWith("/api")) {
870
+ res.setHeader("Access-Control-Allow-Origin", "*");
871
+ res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
872
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
873
+ if (req.method === "OPTIONS") {
874
+ res.writeHead(204);
875
+ res.end();
876
+ return;
877
+ }
878
+ let body = "";
879
+ req.on("data", (chunk) => {
880
+ body += chunk;
881
+ });
882
+ req.on("end", async () => {
883
+ let parsed = {};
884
+ try {
885
+ parsed = body ? JSON.parse(body) : {};
886
+ } catch {
887
+ }
888
+ await this.router.handleRequest(
889
+ {
890
+ method: req.method,
891
+ path: url.pathname,
892
+ body: parsed,
893
+ headers: req.headers,
894
+ ip: req.socket.remoteAddress || "127.0.0.1"
895
+ },
896
+ {
897
+ set(h) {
898
+ for (const [k, v] of Object.entries(h)) {
899
+ try {
900
+ res.setHeader(k, v);
901
+ } catch {
902
+ }
903
+ }
904
+ },
905
+ status(code) {
906
+ return {
907
+ json(data) {
908
+ res.writeHead(code, { "Content-Type": "application/json" });
909
+ res.end(JSON.stringify(data));
910
+ },
911
+ send(data) {
912
+ res.writeHead(code);
913
+ res.end(data);
914
+ },
915
+ end() {
916
+ res.writeHead(code);
917
+ res.end();
918
+ }
919
+ };
920
+ }
921
+ }
922
+ );
923
+ });
924
+ return;
925
+ }
926
+ res.writeHead(404);
927
+ res.end("Not found");
928
+ }
929
+ // ─── Startup Banner ────────────────────────────────────────────────
930
+ printStartupBanner() {
931
+ const routes = this.router.getRoutes();
932
+ const watching = this.options.hotReload;
933
+ console.log("");
934
+ console.log(" \x1B[1m\x1B[33m\u26A1 Clawfire Dev Server\x1B[0m");
935
+ console.log(" \x1B[2m\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\x1B[0m");
936
+ console.log(` \x1B[36mPlayground\x1B[0m : http://localhost:${this.options.port}`);
937
+ console.log(` \x1B[36mAPI\x1B[0m : http://localhost:${this.options.port}/api/...`);
938
+ console.log(` \x1B[36mManifest\x1B[0m : http://localhost:${this.options.port}/api/__manifest`);
939
+ console.log("");
940
+ console.log(` \x1B[32mRoutes (${routes.length})\x1B[0m:`);
941
+ for (const route of routes) {
942
+ const auth = route.contract.meta.auth || "public";
943
+ const authColor = auth === "public" ? "32" : auth === "authenticated" ? "34" : auth === "role" ? "33" : "31";
944
+ console.log(` POST /api\x1B[1m${route.path}\x1B[0m \x1B[${authColor}m[${auth}]\x1B[0m \x1B[2m${route.contract.meta.description}\x1B[0m`);
945
+ }
946
+ console.log("");
947
+ if (watching) {
948
+ console.log(` \x1B[35mHot Reload\x1B[0m : \x1B[32mON\x1B[0m`);
949
+ console.log(` \x1B[2mWatching: app/routes/, app/schemas/\x1B[0m`);
950
+ } else {
951
+ console.log(` \x1B[35mHot Reload\x1B[0m : OFF`);
952
+ }
953
+ console.log(`
954
+ \x1B[2mPress Ctrl+C to stop\x1B[0m
955
+ `);
956
+ }
957
+ };
958
+ async function startDevServer(options) {
959
+ const server = new DevServer(options);
960
+ await server.start();
961
+ const shutdown = async () => {
962
+ console.log("\n Shutting down...");
963
+ await server.stop();
964
+ process.exit(0);
965
+ };
966
+ process.on("SIGINT", shutdown);
967
+ process.on("SIGTERM", shutdown);
968
+ return server;
969
+ }
970
+ export {
971
+ DevServer,
972
+ startDevServer
973
+ };