重要前提
安装AI Skills的关键前提是:必须科学上网,且开启TUN模式,这一点至关重要,直接决定安装能否顺利完成,在此郑重提醒三遍:科学上网,科学上网,科学上网。查看完整安装教程 →
workers-runtime-apis by secondsky/claude-skills
npx skills add https://github.com/secondsky/claude-skills --skill workers-runtime-apis掌握 Workers 运行时 API:Fetch、Streams、Crypto、Cache、WebSockets 和文本编码。
| API | 用途 | 常见用途 |
|---|---|---|
| Fetch | HTTP 请求 | 外部 API、代理 |
| Streams | 数据流 | 大文件、实时处理 |
| Crypto | 密码学 | 哈希、签名、加密 |
| Cache | 响应缓存 | 性能优化 |
| WebSockets | 实时连接 | 聊天、实时更新 |
| Encoding | 文本编码 | UTF-8、Base64 |
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// 基本 fetch
const response = await fetch('https://api.example.com/data');
// 带选项
const postResponse = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${env.API_KEY}`,
},
body: JSON.stringify({ name: 'John' }),
});
// 克隆以进行多次读取
const clone = response.clone();
const json = await response.json();
const text = await clone.text();
return Response.json(json);
}
};
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
| 错误 | 症状 | 预防措施 |
|---|---|---|
| 响应体已读取 | TypeError: Body has already been consumed | 在读取前克隆响应 |
| Fetch 超时 | 请求挂起,worker 超时 | 使用带超时的 AbortController |
| 无效 JSON | SyntaxError: Unexpected token | 解析前检查 content-type |
| 流被锁定 | TypeError: ReadableStream is locked | 不要多次读取流 |
| Crypto 密钥错误 | DOMException: Invalid keyData | 验证密钥格式和算法 |
| 缓存未命中 | 返回 undefined 而非响应 | 返回前检查缓存 |
| WebSocket 关闭 | 连接意外断开 | 处理关闭事件,实现重连 |
| 编码错误 | TypeError: Invalid code point | 正确使用 TextEncoder/TextDecoder |
| CORS 被阻止 | 浏览器拒绝响应 | 添加正确的 CORS 头 |
| 请求大小 | 413 Request Entity Too Large | 流式处理大文件上传 |
async function fetchWithTimeout(url: string, timeout: number = 5000): Promise<Response> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, { signal: controller.signal });
return response;
} finally {
clearTimeout(timeoutId);
}
}
async function fetchWithRetry(
url: string,
options: RequestInit = {},
retries: number = 3
): Promise<Response> {
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(url, options);
if (response.ok) return response;
// 在 5xx 错误时重试
if (response.status >= 500 && i < retries - 1) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
continue;
}
return response;
} catch (error) {
if (i === retries - 1) throw error;
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
}
}
throw new Error('Max retries exceeded');
}
function createUppercaseStream(): TransformStream<string, string> {
return new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk.toUpperCase());
}
});
}
// 用法
const response = await fetch('https://example.com/text');
const transformed = response.body!
.pipeThrough(new TextDecoderStream())
.pipeThrough(createUppercaseStream())
.pipeThrough(new TextEncoderStream());
return new Response(transformed);
async function streamLargeFile(url: string): Promise<Response> {
const response = await fetch(url);
// 直接流式处理,不缓冲
return new Response(response.body, {
headers: {
'Content-Type': response.headers.get('Content-Type') || 'application/octet-stream',
},
});
}
async function sha256(data: string): Promise<string> {
const encoder = new TextEncoder();
const dataBuffer = encoder.encode(data);
const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
async function signHMAC(key: string, data: string): Promise<string> {
const encoder = new TextEncoder();
const keyData = encoder.encode(key);
const dataBuffer = encoder.encode(data);
const cryptoKey = await crypto.subtle.importKey(
'raw',
keyData,
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
);
const signature = await crypto.subtle.sign('HMAC', cryptoKey, dataBuffer);
return btoa(String.fromCharCode(...new Uint8Array(signature)));
}
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const cache = caches.default;
const cacheKey = new Request(request.url, { method: 'GET' });
// 检查缓存
let response = await cache.match(cacheKey);
if (response) {
return response;
}
// 获取并缓存
response = await fetch(request);
response = new Response(response.body, response);
response.headers.set('Cache-Control', 'public, max-age=3600');
// 存储到缓存(不要 await)
ctx.waitUntil(cache.put(cacheKey, response.clone()));
return response;
}
};
// 带 WebSocket 休眠的 Durable Object
export class WebSocketRoom {
state: DurableObjectState;
constructor(state: DurableObjectState) {
this.state = state;
}
async fetch(request: Request): Promise<Response> {
const upgradeHeader = request.headers.get('Upgrade');
if (upgradeHeader !== 'websocket') {
return new Response('Expected websocket', { status: 426 });
}
const pair = new WebSocketPair();
const [client, server] = Object.values(pair);
// 接受连接并启用休眠
this.state.acceptWebSocket(server);
return new Response(null, { status: 101, webSocket: client });
}
async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) {
// 处理传入消息
const data = typeof message === 'string' ? message : new TextDecoder().decode(message);
// 广播给所有连接的客户端
for (const client of this.state.getWebSockets()) {
client.send(data);
}
}
async webSocketClose(ws: WebSocket, code: number, reason: string) {
ws.close(code, reason);
}
}
根据任务加载特定参考文档:
references/fetch-api.md 获取超时、重试、代理模式references/streams-api.md 获取 TransformStream、分块处理references/crypto-api.md 获取 AES、RSA、JWT 验证references/cache-api.md 获取 Cache API 模式、TTL 策略references/websockets.md 获取 WebSocket 模式、Durable Objectsreferences/encoding-api.md 获取 TextEncoder、Base64、Unicode| 模板 | 用途 | 使用场景 |
|---|---|---|
templates/fetch-patterns.ts | HTTP 请求工具 | 构建 API 客户端 |
templates/stream-processing.ts | 流转换 | 处理大文件 |
templates/crypto-operations.ts | Crypto 工具 | 签名、哈希、加密 |
templates/websocket-handler.ts | WebSocket DO | 实时应用 |
每周安装数
68
仓库
GitHub 星标数
93
首次出现
Jan 25, 2026
安全审计
安装于
claude-code62
gemini-cli55
codex54
opencode54
cursor54
github-copilot52
Master the Workers runtime APIs: Fetch, Streams, Crypto, Cache, WebSockets, and text encoding.
| API | Purpose | Common Use |
|---|---|---|
| Fetch | HTTP requests | External APIs, proxying |
| Streams | Data streaming | Large files, real-time |
| Crypto | Cryptography | Hashing, signing, encryption |
| Cache | Response caching | Performance optimization |
| WebSockets | Real-time connections | Chat, live updates |
| Encoding | Text encoding | UTF-8, Base64 |
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// Basic fetch
const response = await fetch('https://api.example.com/data');
// With options
const postResponse = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${env.API_KEY}`,
},
body: JSON.stringify({ name: 'John' }),
});
// Clone for multiple reads
const clone = response.clone();
const json = await response.json();
const text = await clone.text();
return Response.json(json);
}
};
| Error | Symptom | Prevention |
|---|---|---|
| Body already read | TypeError: Body has already been consumed | Clone response before reading |
| Fetch timeout | Request hangs, worker times out | Use AbortController with timeout |
| Invalid JSON | SyntaxError: Unexpected token | Check content-type before parsing |
| Stream locked | TypeError: ReadableStream is locked | Don't read stream multiple times |
| Crypto key error | DOMException: Invalid keyData |
async function fetchWithTimeout(url: string, timeout: number = 5000): Promise<Response> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, { signal: controller.signal });
return response;
} finally {
clearTimeout(timeoutId);
}
}
async function fetchWithRetry(
url: string,
options: RequestInit = {},
retries: number = 3
): Promise<Response> {
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(url, options);
if (response.ok) return response;
// Retry on 5xx errors
if (response.status >= 500 && i < retries - 1) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
continue;
}
return response;
} catch (error) {
if (i === retries - 1) throw error;
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
}
}
throw new Error('Max retries exceeded');
}
function createUppercaseStream(): TransformStream<string, string> {
return new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk.toUpperCase());
}
});
}
// Usage
const response = await fetch('https://example.com/text');
const transformed = response.body!
.pipeThrough(new TextDecoderStream())
.pipeThrough(createUppercaseStream())
.pipeThrough(new TextEncoderStream());
return new Response(transformed);
async function streamLargeFile(url: string): Promise<Response> {
const response = await fetch(url);
// Stream directly without buffering
return new Response(response.body, {
headers: {
'Content-Type': response.headers.get('Content-Type') || 'application/octet-stream',
},
});
}
async function sha256(data: string): Promise<string> {
const encoder = new TextEncoder();
const dataBuffer = encoder.encode(data);
const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
async function signHMAC(key: string, data: string): Promise<string> {
const encoder = new TextEncoder();
const keyData = encoder.encode(key);
const dataBuffer = encoder.encode(data);
const cryptoKey = await crypto.subtle.importKey(
'raw',
keyData,
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
);
const signature = await crypto.subtle.sign('HMAC', cryptoKey, dataBuffer);
return btoa(String.fromCharCode(...new Uint8Array(signature)));
}
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const cache = caches.default;
const cacheKey = new Request(request.url, { method: 'GET' });
// Check cache
let response = await cache.match(cacheKey);
if (response) {
return response;
}
// Fetch and cache
response = await fetch(request);
response = new Response(response.body, response);
response.headers.set('Cache-Control', 'public, max-age=3600');
// Store in cache (don't await)
ctx.waitUntil(cache.put(cacheKey, response.clone()));
return response;
}
};
// Durable Object with WebSocket hibernation
export class WebSocketRoom {
state: DurableObjectState;
constructor(state: DurableObjectState) {
this.state = state;
}
async fetch(request: Request): Promise<Response> {
const upgradeHeader = request.headers.get('Upgrade');
if (upgradeHeader !== 'websocket') {
return new Response('Expected websocket', { status: 426 });
}
const pair = new WebSocketPair();
const [client, server] = Object.values(pair);
// Accept with hibernation
this.state.acceptWebSocket(server);
return new Response(null, { status: 101, webSocket: client });
}
async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) {
// Handle incoming message
const data = typeof message === 'string' ? message : new TextDecoder().decode(message);
// Broadcast to all connected clients
for (const client of this.state.getWebSockets()) {
client.send(data);
}
}
async webSocketClose(ws: WebSocket, code: number, reason: string) {
ws.close(code, reason);
}
}
Load specific references based on the task:
references/fetch-api.md for timeout, retry, proxy patternsreferences/streams-api.md for TransformStream, chunkingreferences/crypto-api.md for AES, RSA, JWT verificationreferences/cache-api.md for Cache API patterns, TTL strategiesreferences/websockets.md for WebSocket patterns, Durable Objectsreferences/encoding-api.md for TextEncoder, Base64, Unicode| Template | Purpose | Use When |
|---|---|---|
templates/fetch-patterns.ts | HTTP request utilities | Building API clients |
templates/stream-processing.ts | Stream transformation | Processing large files |
templates/crypto-operations.ts | Crypto utilities | Signing, hashing, encryption |
templates/websocket-handler.ts | WebSocket DO | Real-time applications |
Weekly Installs
68
Repository
GitHub Stars
93
First Seen
Jan 25, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykWarn
Installed on
claude-code62
gemini-cli55
codex54
opencode54
cursor54
github-copilot52
Azure 升级评估与自动化工具 - 轻松迁移 Functions 计划、托管层级和 SKU
111,700 周安装
| Validate key format and algorithm |
| Cache miss | Returns undefined instead of response | Check cache before returning |
| WebSocket close | Connection drops unexpectedly | Handle close event, implement reconnect |
| Encoding error | TypeError: Invalid code point | Use TextEncoder/TextDecoder properly |
| CORS blocked | Browser rejects response | Add proper CORS headers |
| Request size | 413 Request Entity Too Large | Stream large uploads |