code-review

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
Your knowledge of Cloudflare Workers APIs, types, and wrangler configuration may be outdated. Prefer retrieval over pre-training for any Workers code review task.
你对Cloudflare Workers APIs、类型以及wrangler配置的认知可能已过时。在进行任何Workers代码审查任务时,优先使用检索而非预训练知识

Reference Sources

参考来源

Use the repo's local copies — do not run
npm pack
or install packages to fetch types.
SourceWhere to find itUse for
Wrangler config schema
node_modules/wrangler/config-schema.json
Config fields, binding shapes, allowed values
Workers types
node_modules/@cloudflare/workers-types/index.d.ts
API usage, handler signatures, binding types
Cloudflare docs searchUse the
cloudflare-docs
search tool or read files in this repo
API reference, compatibility dates/flags, binding docs
Read these files directly when you need to verify a type, config field, or API signature. The reference guides in
references/
describe what to validate — not how to fetch packages.
使用仓库的本地副本——请勿运行
npm pack
或安装包来获取类型定义。
来源查找位置用途
Wrangler 配置 schema
node_modules/wrangler/config-schema.json
配置字段、绑定结构、允许的值
Workers 类型定义
node_modules/@cloudflare/workers-types/index.d.ts
API 使用方式、处理器签名、绑定类型
Cloudflare 文档搜索使用
cloudflare-docs
搜索工具或阅读本仓库中的文件
API 参考、兼容性日期/标识、绑定文档
需要验证类型、配置字段或API签名时,请直接阅读这些文件。
references/
目录下的参考指南说明了需要验证的内容——而非获取包的方法。

Review Process

审查流程

1. Build Context

1. 构建上下文

Read full files, not just diffs or isolated snippets. Code that looks wrong in isolation may be correct given surrounding logic.
  • Identify the purpose of the code: is it a complete Worker, a snippet, a configuration example?
  • Check git history for context:
    git log --oneline -5 -- <file>
  • Understand which bindings, types, and patterns the code depends on
阅读完整文件,而非仅查看差异或孤立片段。孤立看可能有问题的代码,结合上下文逻辑后可能是正确的。
  • 明确代码用途:是完整的Worker、代码片段还是配置示例?
  • 查看git历史获取上下文:
    git log --oneline -5 -- <file>
  • 理解代码依赖的绑定、类型和模式

2. Categorize the Code

2. 代码分类

Every code block falls into one of three categories. Review in the context of its category.
CategoryDefinitionExpectations
IllustrativeDemonstrates a concept; uses comments for most logicCorrect API names, realistic signatures
DemonstrativeFunctional but incomplete; would work if placed in the right contextSyntactically valid, correct APIs and binding access
ExecutableStandalone and complete; runs without modificationCompiles, runs, includes imports and config
每个代码块都属于以下三类之一。需结合其分类进行审查。
分类定义预期要求
说明性代码演示某个概念;多数逻辑通过注释说明API 名称正确、签名符合实际场景
演示性代码具备功能但不完整;放入正确上下文即可运行语法有效、API 使用正确、绑定访问方式正确
可执行代码独立且完整;无需修改即可运行可编译、可运行、包含导入语句和配置

3. Validate with Tools

3. 使用工具验证

Run type-checking and linting. Tool output is evidence, not opinion.
bash
npx tsc --noEmit                    # TypeScript errors
npx eslint <files>                  # Lint issues
For config files, validate against the latest wrangler config schema (see
references/wrangler-config.md
for retrieval) and check that all fields, binding types, and values conform.
运行类型检查和代码扫描。工具输出是客观证据,而非主观意见。
bash
npx tsc --noEmit                    # TypeScript 错误检查
npx eslint <files>                  # 代码扫描问题
对于配置文件,需对照最新的wrangler配置schema验证(参考
references/wrangler-config.md
获取方式),确保所有字段、绑定类型和值都符合要求。

4. Check Against Rules

4. 对照规则检查

See
references/workers-types.md
for type system rules,
references/wrangler-config.md
for config validation, and
references/common-patterns.md
for correct API patterns.
Quick-reference rules:
RuleDetail
Binding access
env.X
in module export handlers;
this.env.X
in classes extending platform base classes. See
references/common-patterns.md
.
No
any
Never use
any
for binding types, handler params, or API responses. Use proper generics.
No type-system cheatsFlag
as unknown as T
, unjustified
@ts-ignore
, unsafe assertions. See
references/workers-types.md
.
Config-code consistencyBinding names in wrangler config must match
env.X
usage in code. See
references/wrangler-config.md
.
Required config fieldsVerify against the wrangler config schema — do not assume which fields are required.
Concise examplesExamples should focus on core logic. Minimize boilerplate that distracts from what the code teaches.
Floating promisesEvery
Promise
must be
await
ed,
return
ed,
void
ed, or passed to
ctx.waitUntil()
. See
references/common-patterns.md
.
SerializationData crossing Queue, Workflow step, or DO storage boundaries must be structured-clone serializable. See
references/common-patterns.md
.
StreamingLarge/unknown payloads must stream, not buffer. Flag
await response.text()
on unbounded data.
Error handlingMinimal but present — null checks on nullable returns, basic fetch error handling. Do not distract with verbose try/catch.
类型系统规则请参考
references/workers-types.md
,配置验证规则请参考
references/wrangler-config.md
,正确API模式请参考
references/common-patterns.md
速查规则:
规则细节说明
绑定访问方式模块导出处理器中使用
env.X
;继承平台基类的类中使用
this.env.X
。详见
references/common-patterns.md
禁止使用
any
绑定类型、处理器参数或API响应绝不能使用
any
。请使用正确的泛型。
禁止类型系统作弊标记
as unknown as T
、无正当理由的
@ts-ignore
、不安全的类型断言。详见
references/workers-types.md
配置与代码一致性wrangler配置中的绑定名称必须与代码中
env.X
的使用保持一致。详见
references/wrangler-config.md
必填配置字段对照wrangler配置schema验证——不要主观假设哪些字段是必填的。
示例简洁性示例应聚焦核心逻辑。尽量减少分散注意力的样板代码。
浮动Promise每个
Promise
必须被
await
return
void
处理,或传递给
ctx.waitUntil()
。详见
references/common-patterns.md
序列化要求跨Queue、Workflow步骤或DO存储边界的数据必须支持结构化克隆序列化。详见
references/common-patterns.md
流处理要求大体积/未知大小的负载必须使用流处理,而非缓冲。标记对无界数据调用
await response.text()
的情况。
错误处理至少具备基础错误处理——对可空返回值做空值检查、基础的fetch错误处理。避免使用冗长的try/catch分散注意力。

5. Assess Risk

5. 风险评估

RiskTriggers
HIGHAuth, crypto, external calls, value transfer, validation removal, access control, binding misconfiguration
MEDIUMBusiness logic, state changes, new public APIs, error handling, config changes
LOWComments, logging, formatting, minor style
Focus deeper analysis on HIGH risk. For critical paths, check blast radius: how many other files reference this code?
Security logic escalation: for crypto, auth, and timing-sensitive code, do not stop at verifying API calls are correct. Examine the surrounding logic for flaws that undermine the security property (e.g., correct
timingSafeEqual
call but early return on length mismatch). See
references/common-patterns.md
Security section.
风险等级触发场景
高风险认证、加密、外部调用、值传输、验证移除、访问控制、绑定配置错误
中风险业务逻辑、状态变更、新公开API、错误处理、配置变更
低风险注释、日志、格式、 minor 风格问题
重点深入分析高风险内容。对于关键路径,检查影响范围:有多少其他文件引用了此代码?
安全逻辑升级:对于加密、认证和时序敏感代码,不要仅验证API调用是否正确。需检查周边逻辑是否存在破坏安全属性的缺陷(例如,正确调用
timingSafeEqual
但因长度不匹配提前返回)。详见
references/common-patterns.md
的安全章节。

Anti-patterns to Flag

需要标记的反模式

Anti-patternWhy it matters
any
on
Env
or handler params
Defeats type safety for every binding access downstream
as unknown as T
double-cast
Hides real type incompatibilities — fix the underlying design
@ts-ignore
/
@ts-expect-error
without explanation
Masks errors silently; require a comment justifying each suppression
Buffering unbounded data (
await res.text()
,
await res.json()
on streams)
Memory exhaustion on large payloads; use streaming
Hardcoded secrets or API keysUse
env
bindings and
wrangler secret
blockConcurrencyWhile
on every request
Only for initialization; blocks all concurrent requests
Single global Durable ObjectCreates a bottleneck; shard by coordination atom
In-memory-only state in DOsLost on eviction; persist to SQLite storage
Missing DO migrations in configNew DO classes require migration entries or deployment fails
Floating promises (
step.do()
,
fetch()
without
await
)
Silent bugs — drops results, breaks Workflow durability, ignores errors
Non-serializable values across boundaries (
Response
,
Error
in step/queue)
Compiles but fails at runtime; extract plain data before crossing boundary
implements
instead of
extends
on platform base classes
Legacy pattern — loses
this.ctx
,
this.env
access from base class
反模式影响原因
Env
或处理器参数使用
any
类型
破坏所有下游绑定访问的类型安全性
使用
as unknown as T
双重类型转换
隐藏真实的类型不兼容问题——应修复底层设计
无说明的
@ts-ignore
/
@ts-expect-error
静默掩盖错误;要求为每个抑制添加注释说明理由
缓冲无界数据(对流调用
await res.text()
await res.json()
大负载会导致内存耗尽;应使用流处理
硬编码密钥或API密钥应使用
env
绑定和
wrangler secret
功能
每个请求都调用
blockConcurrencyWhile
仅用于初始化;会阻塞所有并发请求
单一全局Durable Object会造成性能瓶颈;应按协调原子分片
Durable Object中仅使用内存状态实例被回收时数据丢失;应持久化到SQLite存储
配置中缺少Durable Object迁移新DO类需要迁移条目,否则部署会失败
浮动Promise(
step.do()
fetch()
未加
await
静默bug——丢失结果、破坏Workflow持久性、忽略错误
跨边界使用不可序列化值(步骤/队列中的
Response
Error
编译通过但运行时失败;跨边界前需提取普通数据
平台基类使用
implements
而非
extends
旧模式——会丢失基类中的
this.ctx
this.env
访问权限

What NOT to Flag

无需标记的内容

  • Style not enforced by linters
  • "Could be cleaner" when code is correct and clear
  • Theoretical performance concerns without evidence
  • Missing features not in scope of the example
  • Pre-existing issues in unchanged code
  • TOML config in existing docs (only flag for new content)
  • 未被linter强制执行的风格问题
  • 代码正确清晰时的"可以更简洁"建议
  • 无证据的理论性能担忧
  • 示例范围外的缺失功能
  • 未修改代码中已存在的问题
  • 现有文档中的TOML配置(仅针对新内容标记)

Output Format

输出格式

**[SEVERITY]** Brief description
`file.ts:42` — explanation with evidence (tool output, type error, config mismatch)
Suggested fix: `code` (if applicable)
Severity: CRITICAL (security, data loss, crash) | HIGH (type error, wrong API, broken config) | MEDIUM (missing validation, edge case, outdated pattern) | LOW (style, minor improvement)
End with a summary count by severity. If no issues found, say so directly.
**[严重等级]** 简要描述
`file.ts:42` — 附带证据的解释(工具输出、类型错误、配置不匹配)
建议修复:`代码`(如适用)
严重等级:CRITICAL(安全问题、数据丢失、崩溃)| HIGH(类型错误、API误用、配置失效)| MEDIUM(缺少验证、边缘场景、过时模式)| LOW(风格问题、小改进)
结尾按严重等级统计问题数量。若无问题,直接说明。

Principles

原则

  • Be certain. Investigate before flagging. If you cannot confirm an API, binding pattern, or config field, retrieve the docs or schema first.
  • Provide evidence. Reference line numbers, tool output, schema fields, or type definitions.
  • Correctness over completeness. A concise example that works is better than a comprehensive one with errors.
  • Respect existing patterns. Do not flag conventions already established in the codebase unless actively harmful.
  • Focus on what developers will copy. Code in documentation gets pasted into production. Treat it accordingly.
  • 确保准确。标记前先调查。若无法确认API、绑定模式或配置字段,先检索文档或schema。
  • 提供证据。引用行号、工具输出、schema字段或类型定义。
  • 正确性优先于完整性。一个能运行的简洁示例,比有错误的全面示例更好。
  • 尊重现有模式。除非有危害,否则不要标记代码库中已确立的约定。
  • 聚焦开发者会复制的内容。文档中的代码会被直接粘贴到生产环境。请以此标准对待。",