deforge 0.1.0

Universal Edge Function Compiler - Transform standard code to platform-specific deployables
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# DeniCTL 快速开始指南

本指南将帮助您在 5 分钟内创建并部署您的第一个 Edge Function。

## 前置要求

- Rust 1.70+ ([安装 Rust]https://rustup.rs/)
- Node.js 18+ (用于项目依赖管理)

## 1. 安装 DeniCTL

```bash
# 克隆项目
git clone https://github.com/deislet/denictl.git
cd denictl

# 构建并安装
cargo build --release
cargo install --path crates/denictl

# 验证安装
denictl --version
```

## 2. 创建新项目

```bash
# 初始化项目
denictl init my-first-app
cd my-first-app

# 查看项目结构
tree
```

您将看到:
```
my-first-app/
├── functions/          # 边缘函数代码
│   ├── index.ts       # 默认路由 (/)
│   └── api/
│       └── hello.ts   # API 端点 (/api/hello)
├── .config.json       # 项目配置
├── .env               # 环境变量
├── package.json
├── tsconfig.json
└── README.md
```

## 3. 查看示例代码

### functions/index.ts - 默认路由
```typescript
export default async function handler(context: Context): Promise<Response> {
  return new Response('Hello from Edge Function!', {
    headers: { 'Content-Type': 'text/plain' }
  });
}
```

### functions/api/hello.ts - API 端点
```typescript
export default async function handler(context: Context): Promise<Response> {
  const { query } = context;
  const name = query.name || 'World';

  const response = {
    message: `Hello, ${name}!`,
    timestamp: new Date().toISOString(),
    path: context.path
  };

  return new Response(JSON.stringify(response, null, 2), {
    headers: { 'Content-Type': 'application/json' }
  });
}
```

## 4. 验证项目

```bash
# 验证代码是否符合规范
denictl validate

# 输出:
# ✓ Validation passed
# ✓ Project structure valid
# ✓ .config.json valid
# ✓ All handlers valid
```

## 5. 构建项目

```bash
# 构建所有平台
denictl build

# 或只构建特定平台
denictl build --vendor cloudflare
```

您将在 `dist/` 目录看到构建产物:
```
dist/
├── cloudflare/
│   ├── index.ts           # 路由器入口
│   ├── wrangler.toml      # Cloudflare 配置
│   ├── src/               # 转换后的 handlers
│   └── adapters/          # 平台适配器
├── deno/
│   └── ...
└── tencent/
    └── ...
```

## 6. 查看生成的代码

### dist/cloudflare/index.ts - 自动生成的路由器
```typescript
import handler0 from './src/index';
import handler1 from './src/api/hello';

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);

    if (matchRoute(url.pathname, '/')) {
      return handler0.fetch(request, env, ctx);
    }
    if (matchRoute(url.pathname, '/api/hello')) {
      return handler1.fetch(request, env, ctx);
    }

    return new Response('Not Found', { status: 404 });
  }
};
```

### dist/cloudflare/src/index.ts - 转换后的 handler
```typescript
import { createContextBuilder } from '../adapters/context-builder';

// 原始 handler 代码保持不变
export default async function handler(context: Context): Promise<Response> {
  return new Response('Hello from Edge Function!', {
    headers: { 'Content-Type': 'text/plain' }
  });
}

// Cloudflare Workers 包装
export default {
  async fetch(request, env, ctx) {
    const buildContext = createContextBuilder(env, ctx);
    const context = buildContext(request, '/');
    return await handler(context);
  }
};
```

## 7. 部署到 Cloudflare Workers

```bash
# 配置 Cloudflare 凭证
denictl config set cloudflare.api-token YOUR_API_TOKEN

# 部署到 staging 环境
denictl deploy --vendor cloudflare --env staging

# 部署到 production 环境
denictl deploy --vendor cloudflare --env production
```

或者手动使用 wrangler:
```bash
cd dist/cloudflare
npx wrangler deploy
```

## 8. 添加 KV Store 功能

### 修改 .config.json
```json
{
  "services": {
    "kv": { "enabled": true },
    "database": { "enabled": false }
  }
}
```

### 创建 functions/api/count.ts
```typescript
export default async function handler(context: Context): Promise<Response> {
  const { kv } = context.services;

  // 获取当前计数
  const count = await kv.getJSON<number>('visit_count') || 0;

  // 增加计数
  const newCount = count + 1;
  await kv.putJSON('visit_count', newCount);

  return new Response(JSON.stringify({
    count: newCount,
    message: 'Visit count updated'
  }), {
    headers: { 'Content-Type': 'application/json' }
  });
}
```

### 重新构建
```bash
denictl build --vendor cloudflare
```

## 9. 添加动态路由

### 创建 functions/api/users/[id].ts
```typescript
export default async function handler(context: Context): Promise<Response> {
  const { params } = context;
  const userId = params.id;

  // 模拟从数据库获取用户
  const user = {
    id: userId,
    name: `User ${userId}`,
    email: `user${userId}@example.com`
  };

  return new Response(JSON.stringify(user), {
    headers: { 'Content-Type': 'application/json' }
  });
}
```

这将自动映射到路由: `/api/users/:id`

访问: `https://your-worker.workers.dev/api/users/123`

## 10. 本地开发 (即将推出)

```bash
# 启动本地开发服务器
denictl dev

# 服务器将在 http://localhost:8000 启动
# 支持热重载和 Mock 服务
```

## 常见任务

### 验证代码规范
```bash
denictl validate --strict
```

### 构建特定平台
```bash
denictl build --vendor cloudflare
denictl build --vendor deno
denictl build --vendor tencent
```

### 查看部署历史
```bash
denictl deployments list
```

### 回滚部署
```bash
denictl rollback --deployment <deployment-id>
```

## 最佳实践

### 1. 保持代码平台无关

✅ **正确**:
```typescript
const apiKey = context.env.API_KEY;
const kv = context.services.kv;
```

❌ **错误**:
```typescript
if (typeof Deno !== 'undefined') { }
const kv = env.MY_KV;  // 直接访问平台 binding
```

### 2. 使用统一的服务接口

```typescript
// KV Store
await context.services.kv.put('key', 'value');
const value = await context.services.kv.get('key');

// Database
const result = await context.services.database.query(
  'SELECT * FROM users WHERE id = ?',
  [userId]
);
```

### 3. 结构化日志

```typescript
context.log.info('Processing request', { userId, action: 'login' });
context.log.error('Failed to process', { error: error.message });
```

### 4. 使用环境变量

```typescript
const apiEndpoint = context.env.API_ENDPOINT;
const logLevel = context.env.LOG_LEVEL;
```

## 项目配置详解

### .config.json
```json
{
  "version": "1.0",
  "name": "my-app",
  "runtime": "standard-v1",
  "language": "typescript",
  "functionRoot": "./functions",

  "environment": {
    "variables": {
      "LOG_LEVEL": "info",
      "API_BASE": "https://api.example.com"
    },
    "secrets": ["API_KEY", "DB_PASSWORD"]
  },

  "services": {
    "kv": { "enabled": true },
    "database": { "enabled": false }
  },

  "vendors": {
    "cloudflare": { "enabled": true },
    "deno": { "enabled": true },
    "tencent": { "enabled": false }
  },

  "build": {
    "outDir": "./dist",
    "minify": true,
    "sourcemap": true
  }
}
```

## 故障排除

### 验证失败
```bash
# 查看详细错误
denictl validate --strict

# 常见错误:
# - 平台类型检测: typeof Deno
# - 直接访问 context.raw
# - 使用平台特定 API
```

### 构建失败
```bash
# 检查 TypeScript 语法
npx tsc --noEmit

# 查看详细构建日志
denictl build --vendor all
```

### 部署失败
```bash
# 验证配置
denictl config get cloudflare.api-token

# 手动部署
cd dist/cloudflare
npx wrangler deploy
```

## 下一步

- 阅读 [完整文档]./README.md
- 查看 [示例项目]./examples/
- 浏览 [API 参考]./docs/api.md
- 加入 [社区讨论]https://github.com/deislet/denictl/discussions

## 获取帮助

- [GitHub Issues]https://github.com/deislet/denictl/issues
- [讨论区]https://github.com/deislet/denictl/discussions
- [规范文档]https://github.com/deislet/spec

祝您使用愉快! 🚀