[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AK086PJACZ46W254TEX1CH":3,"skill-same:01M7AK086PJACZ46W254TEX1CH":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":24,"commitSha":25,"skillDirectory":5,"forksCount":13,"repositoryHtmlUrl":26,"repositoryHomepageUrl":6,"ownerHtmlUrl":27,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":28,"install":29,"resources":42},"01M7AK086PJACZ46W254TEX1CH","cloudflare-durable-objects",null,"Comprehensive guide for Cloudflare Durable Objects - globally unique, stateful objects for coordination, real-time communication, and persistent state management.\n\nUse when: building real-time applications, creating WebSocket servers with hibernation, implementing chat rooms or multiplayer games, coordinating between multiple clients, managing per-user or per-room state, implementing rate limiting or session management, scheduling tasks with alarms, building queues or workflows, or encountering \"do class export\", \"new_sqlite_classes\", \"migrations required\", \"websocket hibernation\", \"alarm api error\", or \"global uniqueness\" errors.\n\nPrevents 15+ documented issues: class not exported, missing migrations, wrong migration type, constructor overhead blocking hibernation, setTimeout breaking hibernation, in-memory state lost on hibernation, outgoing WebSocket not hibernating, global uniqueness confusion, partial deleteAll on KV backend, binding name mismatches, state size limits exceeded, non-atomic migrations, location hints misunderstood, alarm retry failures, and fetch calls blocking hibernation.\n\nKeywords: durable objects, cloudflare do, DurableObject class, do bindings, websocket hibernation, do state api, ctx.storage.sql, ctx.acceptWebSocket, webSocketMessage, alarm() handler, storage.setAlarm, idFromName, newUniqueId, getByName, DurableObjectStub, serializeAttachment, real-time cloudflare, multiplayer cloudflare, chat room workers, coordination cloudflare, stateful workers, new_sqlite_classes, do migrations, location hints, RPC methods, blockConcurrencyWhile, \"do class export\", \"new_sqlite_classes\", \"migrations required\", \"websocket hibernation\", \"alarm api error\", \"global uniqueness\", \"binding not found\"","davidanthonyn\u002Fclaude-skills","davidanthonyn","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F55152980?v=4","01M7AJ4MY8S5C2RJCGX6626J0G","01M7AJ7JE1K98GRPH9Z57Z0R0W",0,"MIT","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fcloudflare-durable-objects\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: cloudflare-durable-objects\ndescription: |\n  Comprehensive guide for Cloudflare Durable Objects - globally unique, stateful objects for coordination, real-time communication, and persistent state management.\n\n  Use when: building real-time applications, creating WebSocket servers with hibernation, implementing chat rooms or multiplayer games, coordinating between multiple clients, managing per-user or per-room state, implementing rate limiting or session management, scheduling tasks with alarms, building queues or workflows, or encountering \"do class export\", \"new_sqlite_classes\", \"migrations required\", \"websocket hibernation\", \"alarm api error\", or \"global uniqueness\" errors.\n\n  Prevents 15+ documented issues: class not exported, missing migrations, wrong migration type, constructor overhead blocking hibernation, setTimeout breaking hibernation, in-memory state lost on hibernation, outgoing WebSocket not hibernating, global uniqueness confusion, partial deleteAll on KV backend, binding name mismatches, state size limits exceeded, non-atomic migrations, location hints misunderstood, alarm retry failures, and fetch calls blocking hibernation.\n\n  Keywords: durable objects, cloudflare do, DurableObject class, do bindings, websocket hibernation, do state api, ctx.storage.sql, ctx.acceptWebSocket, webSocketMessage, alarm() handler, storage.setAlarm, idFromName, newUniqueId, getByName, DurableObjectStub, serializeAttachment, real-time cloudflare, multiplayer cloudflare, chat room workers, coordination cloudflare, stateful workers, new_sqlite_classes, do migrations, location hints, RPC methods, blockConcurrencyWhile, \"do class export\", \"new_sqlite_classes\", \"migrations required\", \"websocket hibernation\", \"alarm api error\", \"global uniqueness\", \"binding not found\"\nlicense: MIT\n---\n\n# Cloudflare Durable Objects\n\n**Status**: Production Ready ✅\n**Last Updated**: 2025-10-22\n**Dependencies**: cloudflare-worker-base (recommended)\n**Latest Versions**: wrangler@4.43.0+, @cloudflare\u002Fworkers-types@4.20251014.0+\n**Official Docs**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002F\n\n---\n\n## What are Durable Objects?\n\nCloudflare Durable Objects are **globally unique, stateful objects** that provide:\n\n- **Single-point coordination** - Each Durable Object instance is globally unique across Cloudflare's network\n- **Strong consistency** - Transactional, serializable storage (ACID guarantees)\n- **Real-time communication** - WebSocket Hibernation API for thousands of connections per instance\n- **Persistent state** - Built-in SQLite database (up to 1GB) or key-value storage\n- **Scheduled tasks** - Alarms API for future task execution\n- **Global distribution** - Automatically routed to optimal location\n- **Automatic scaling** - Millions of independent instances\n\n**Use Cases**:\n- Chat rooms and real-time collaboration\n- Multiplayer game servers\n- Rate limiting and session management\n- Leader election and coordination\n- WebSocket servers with hibernation\n- Stateful workflows and queues\n- Per-user or per-room logic\n\n---\n\n## Quick Start (10 Minutes)\n\n### Option 1: Scaffold New DO Project\n\n```bash\nnpm create cloudflare@latest my-durable-app -- \\\n  --template=cloudflare\u002Fdurable-objects-template \\\n  --ts \\\n  --git \\\n  --deploy false\n\ncd my-durable-app\nnpm install\nnpm run dev\n```\n\n**What this creates:**\n- Complete Durable Objects project structure\n- TypeScript configuration\n- wrangler.jsonc with bindings and migrations\n- Example DO class implementation\n- Worker to call the DO\n\n### Option 2: Add to Existing Worker\n\n```bash\ncd my-existing-worker\nnpm install -D @cloudflare\u002Fworkers-types\n```\n\n**Create a Durable Object class** (`src\u002Fcounter.ts`):\n\n```typescript\nimport { DurableObject } from 'cloudflare:workers';\n\nexport class Counter extends DurableObject {\n  async increment(): Promise\u003Cnumber> {\n    \u002F\u002F Get current value from storage (default to 0)\n    let value: number = (await this.ctx.storage.get('value')) || 0;\n\n    \u002F\u002F Increment\n    value += 1;\n\n    \u002F\u002F Save back to storage\n    await this.ctx.storage.put('value', value);\n\n    return value;\n  }\n\n  async get(): Promise\u003Cnumber> {\n    return (await this.ctx.storage.get('value')) || 0;\n  }\n}\n\n\u002F\u002F CRITICAL: Export the class\nexport default Counter;\n```\n\n**Configure wrangler.jsonc:**\n\n```jsonc\n{\n  \"$schema\": \"node_modules\u002Fwrangler\u002Fconfig-schema.json\",\n  \"name\": \"my-worker\",\n  \"main\": \"src\u002Findex.ts\",\n  \"compatibility_date\": \"2025-10-22\",\n\n  \u002F\u002F Durable Objects binding\n  \"durable_objects\": {\n    \"bindings\": [\n      {\n        \"name\": \"COUNTER\",           \u002F\u002F How you access it: env.COUNTER\n        \"class_name\": \"Counter\"      \u002F\u002F MUST match exported class name\n      }\n    ]\n  },\n\n  \u002F\u002F REQUIRED: Migration for new DO class\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",                   \u002F\u002F Unique migration identifier\n      \"new_sqlite_classes\": [        \u002F\u002F Use SQLite backend (recommended)\n        \"Counter\"\n      ]\n    }\n  ]\n}\n```\n\n**Call from Worker** (`src\u002Findex.ts`):\n\n```typescript\nimport { Counter } from '.\u002Fcounter';\n\ninterface Env {\n  COUNTER: DurableObjectNamespace\u003CCounter>;\n}\n\nexport { Counter };\n\nexport default {\n  async fetch(request: Request, env: Env): Promise\u003CResponse> {\n    \u002F\u002F Get Durable Object stub by name\n    const id = env.COUNTER.idFromName('global-counter');\n    const stub = env.COUNTER.get(id);\n\n    \u002F\u002F Call RPC method on the DO\n    const count = await stub.increment();\n\n    return new Response(`Count: ${count}`);\n  },\n};\n```\n\n**Deploy:**\n\n```bash\nnpx wrangler deploy\n```\n\n---\n\n## Durable Object Class Structure\n\n### Base Class Pattern\n\nAll Durable Objects **MUST extend `DurableObject`** from `cloudflare:workers`:\n\n```typescript\nimport { DurableObject } from 'cloudflare:workers';\n\nexport class MyDurableObject extends DurableObject {\n  constructor(ctx: DurableObjectState, env: Env) {\n    super(ctx, env);\n\n    \u002F\u002F Optional: Initialize from storage\n    ctx.blockConcurrencyWhile(async () => {\n      \u002F\u002F Load state before handling requests\n      this.someValue = await ctx.storage.get('someKey') || defaultValue;\n    });\n  }\n\n  \u002F\u002F RPC methods (recommended)\n  async myMethod(): Promise\u003Cstring> {\n    return 'Hello from DO!';\n  }\n\n  \u002F\u002F Optional: HTTP fetch handler\n  async fetch(request: Request): Promise\u003CResponse> {\n    return new Response('Hello from DO fetch!');\n  }\n}\n\n\u002F\u002F CRITICAL: Export the class\nexport default MyDurableObject;\n```\n\n### Constructor Pattern\n\n```typescript\nconstructor(ctx: DurableObjectState, env: Env) {\n  super(ctx, env);  \u002F\u002F REQUIRED\n\n  \u002F\u002F Access to environment bindings\n  this.env = env;\n\n  \u002F\u002F this.ctx provides:\n  \u002F\u002F - this.ctx.storage      (storage API)\n  \u002F\u002F - this.ctx.id           (unique ID)\n  \u002F\u002F - this.ctx.waitUntil()  (background tasks)\n  \u002F\u002F - this.ctx.acceptWebSocket() (WebSocket hibernation)\n}\n```\n\n**CRITICAL Rules:**\n- ✅ **Always call `super(ctx, env)`** first\n- ✅ **Keep constructor minimal** - heavy work blocks hibernation wake-up\n- ✅ **Use `ctx.blockConcurrencyWhile()`** to initialize from storage before requests\n- ❌ **Never use `setTimeout` or `setInterval`** - breaks hibernation (use alarms instead)\n- ❌ **Don't rely only on in-memory state** with WebSockets - persist to storage\n\n### Exporting the Class\n\n```typescript\n\u002F\u002F Export as default (required for Worker to use it)\nexport default MyDurableObject;\n\n\u002F\u002F Also export as named export (for type inference in Worker)\nexport { MyDurableObject };\n```\n\n**In Worker:**\n\n```typescript\n\u002F\u002F Import the class for types\nimport { MyDurableObject } from '.\u002Fmy-durable-object';\n\n\u002F\u002F Export it so Worker can instantiate it\nexport { MyDurableObject };\n\ninterface Env {\n  MY_DO: DurableObjectNamespace\u003CMyDurableObject>;\n}\n```\n\n---\n\n## State API - Persistent Storage\n\nDurable Objects provide **two storage APIs** depending on the backend:\n\n1. **SQL API** (SQLite backend) - **Recommended**\n2. **Key-Value API** (KV or SQLite backend)\n\n### Enable SQLite Backend (Recommended)\n\nIn `wrangler.jsonc` migrations:\n\n```jsonc\n{\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",\n      \"new_sqlite_classes\": [\"MyDurableObject\"]  \u002F\u002F ← Use this for SQLite\n    }\n  ]\n}\n```\n\n**Why SQLite?**\n- ✅ Up to **1GB storage** (vs 128MB for KV backend)\n- ✅ **Atomic operations** (deleteAll is all-or-nothing)\n- ✅ **SQL queries** with transactions\n- ✅ **Point-in-time recovery** (PITR)\n- ✅ Synchronous KV API available too\n\n### SQL API\n\nAccess via `ctx.storage.sql`:\n\n```typescript\nimport { DurableObject } from 'cloudflare:workers';\n\nexport class MyDurableObject extends DurableObject {\n  sql: SqlStorage;\n\n  constructor(ctx: DurableObjectState, env: Env) {\n    super(ctx, env);\n    this.sql = ctx.storage.sql;\n\n    \u002F\u002F Create table on first run\n    this.sql.exec(`\n      CREATE TABLE IF NOT EXISTS messages (\n        id INTEGER PRIMARY KEY AUTOINCREMENT,\n        text TEXT NOT NULL,\n        user TEXT NOT NULL,\n        created_at INTEGER NOT NULL\n      );\n\n      CREATE INDEX IF NOT EXISTS idx_created_at ON messages(created_at);\n    `);\n  }\n\n  async addMessage(text: string, user: string): Promise\u003Cnumber> {\n    \u002F\u002F Insert with exec (returns cursor)\n    const cursor = this.sql.exec(\n      'INSERT INTO messages (text, user, created_at) VALUES (?, ?, ?) RETURNING id',\n      text,\n      user,\n      Date.now()\n    );\n\n    const row = cursor.one\u003C{ id: number }>();\n    return row.id;\n  }\n\n  async getMessages(limit: number = 50): Promise\u003Cany[]> {\n    const cursor = this.sql.exec(\n      'SELECT * FROM messages ORDER BY created_at DESC LIMIT ?',\n      limit\n    );\n\n    \u002F\u002F Convert cursor to array\n    return cursor.toArray();\n  }\n\n  async deleteOldMessages(beforeTimestamp: number): Promise\u003Cvoid> {\n    this.sql.exec(\n      'DELETE FROM messages WHERE created_at \u003C ?',\n      beforeTimestamp\n    );\n  }\n}\n```\n\n**SQL API Methods:**\n\n```typescript\n\u002F\u002F Execute query (returns cursor)\nconst cursor = this.sql.exec('SELECT * FROM table WHERE id = ?', id);\n\n\u002F\u002F Get single row\nconst row = cursor.one\u003CRowType>();\n\n\u002F\u002F Get first row or null\nconst row = cursor.one\u003CRowType>({ allowNone: true });\n\n\u002F\u002F Get all rows as array\nconst rows = cursor.toArray\u003CRowType>();\n\n\u002F\u002F Iterate cursor\nfor (const row of cursor) {\n  \u002F\u002F Process row\n}\n\n\u002F\u002F Transactions (synchronous)\nthis.ctx.storage.transactionSync(() => {\n  this.sql.exec('INSERT INTO table1 ...');\n  this.sql.exec('UPDATE table2 ...');\n  \u002F\u002F All or nothing\n});\n```\n\n**CRITICAL SQL Rules:**\n- ✅ Always use **parameterized queries** with `?` placeholders\n- ✅ Create indexes for frequently queried columns\n- ✅ Use transactions for multi-statement operations\n- ❌ Don't access the hidden `__cf_kv` table (used internally for KV API)\n- ❌ Don't enable SQLite on existing deployed KV-backed DOs (not supported)\n\n### Key-Value API\n\nAvailable on **both SQLite and KV backends** via `ctx.storage`:\n\n```typescript\nimport { DurableObject } from 'cloudflare:workers';\n\nexport class MyDurableObject extends DurableObject {\n  async increment(): Promise\u003Cnumber> {\n    \u002F\u002F Get value\n    let count = await this.ctx.storage.get\u003Cnumber>('count') || 0;\n\n    \u002F\u002F Increment\n    count += 1;\n\n    \u002F\u002F Put value back\n    await this.ctx.storage.put('count', count);\n\n    return count;\n  }\n\n  async batchOperations(): Promise\u003Cvoid> {\n    \u002F\u002F Get multiple keys\n    const map = await this.ctx.storage.get\u003Cnumber>(['key1', 'key2', 'key3']);\n\n    \u002F\u002F Put multiple keys\n    await this.ctx.storage.put({\n      key1: 'value1',\n      key2: 'value2',\n      key3: 'value3',\n    });\n\n    \u002F\u002F Delete key\n    await this.ctx.storage.delete('key1');\n\n    \u002F\u002F Delete multiple keys\n    await this.ctx.storage.delete(['key2', 'key3']);\n  }\n\n  async listKeys(): Promise\u003Cstring[]> {\n    \u002F\u002F List all keys\n    const map = await this.ctx.storage.list();\n    return Array.from(map.keys());\n\n    \u002F\u002F List with prefix\n    const mapWithPrefix = await this.ctx.storage.list({\n      prefix: 'user:',\n      limit: 100,\n    });\n  }\n\n  async deleteAllStorage(): Promise\u003Cvoid> {\n    \u002F\u002F Delete alarm first (if set)\n    await this.ctx.storage.deleteAlarm();\n\n    \u002F\u002F Delete all storage (DO will cease to exist after shutdown)\n    await this.ctx.storage.deleteAll();\n  }\n}\n```\n\n**KV API Methods:**\n\n```typescript\n\u002F\u002F Get single value\nconst value = await this.ctx.storage.get\u003CT>('key');\n\n\u002F\u002F Get multiple values (returns Map)\nconst map = await this.ctx.storage.get\u003CT>(['key1', 'key2']);\n\n\u002F\u002F Put single value\nawait this.ctx.storage.put('key', value);\n\n\u002F\u002F Put multiple values\nawait this.ctx.storage.put({ key1: value1, key2: value2 });\n\n\u002F\u002F Delete single key\nawait this.ctx.storage.delete('key');\n\n\u002F\u002F Delete multiple keys\nawait this.ctx.storage.delete(['key1', 'key2']);\n\n\u002F\u002F List keys\nconst map = await this.ctx.storage.list\u003CT>({\n  prefix: 'user:',\n  limit: 100,\n  reverse: false\n});\n\n\u002F\u002F Delete all (atomic on SQLite, may be partial on KV backend)\nawait this.ctx.storage.deleteAll();\n\n\u002F\u002F Transactions (async)\nawait this.ctx.storage.transaction(async (txn) => {\n  await txn.put('key1', value1);\n  await txn.put('key2', value2);\n  \u002F\u002F All or nothing\n});\n```\n\n**Storage Limits:**\n- **SQLite backend**: Up to **1GB** storage per DO instance\n- **KV backend**: Up to **128MB** storage per DO instance\n\n---\n\n## WebSocket Hibernation API\n\nThe **WebSocket Hibernation API** allows Durable Objects to:\n- Handle **thousands of WebSocket connections** per instance\n- **Hibernate** when idle (no messages, no events) to save costs\n- **Wake up** automatically when messages arrive\n- Maintain connections without incurring duration charges during idle periods\n\n**Use for:** Chat rooms, real-time collaboration, multiplayer games, live updates\n\n### How Hibernation Works\n\n1. **Active state** - DO is in memory, handling messages\n2. **Idle state** - No messages for ~10 seconds, DO can hibernate\n3. **Hibernation** - In-memory state cleared, WebSockets stay connected to Cloudflare edge\n4. **Wake up** - New message arrives → constructor runs → handler method called\n\n**CRITICAL:** In-memory state is **lost on hibernation**. Use `serializeAttachment()` to persist per-WebSocket metadata.\n\n### WebSocket Server Pattern\n\n```typescript\nimport { DurableObject } from 'cloudflare:workers';\n\nexport class ChatRoom extends DurableObject {\n  sessions: Map\u003CWebSocket, { userId: string; username: string }>;\n\n  constructor(ctx: DurableObjectState, env: Env) {\n    super(ctx, env);\n\n    \u002F\u002F Restore WebSocket connections after hibernation\n    this.sessions = new Map();\n\n    ctx.getWebSockets().forEach((ws) => {\n      \u002F\u002F Deserialize attachment (persisted metadata)\n      const attachment = ws.deserializeAttachment();\n      this.sessions.set(ws, attachment);\n    });\n  }\n\n  async fetch(request: Request): Promise\u003CResponse> {\n    \u002F\u002F Expect WebSocket upgrade request\n    const upgradeHeader = request.headers.get('Upgrade');\n    if (upgradeHeader !== 'websocket') {\n      return new Response('Expected websocket', { status: 426 });\n    }\n\n    \u002F\u002F Create WebSocket pair\n    const webSocketPair = new WebSocketPair();\n    const [client, server] = Object.values(webSocketPair);\n\n    \u002F\u002F Get user info from URL or headers\n    const url = new URL(request.url);\n    const userId = url.searchParams.get('userId') || 'anonymous';\n    const username = url.searchParams.get('username') || 'Anonymous';\n\n    \u002F\u002F Accept WebSocket with hibernation\n    \u002F\u002F CRITICAL: Use ctx.acceptWebSocket(), NOT ws.accept()\n    this.ctx.acceptWebSocket(server);\n\n    \u002F\u002F Serialize metadata to persist across hibernation\n    const metadata = { userId, username };\n    server.serializeAttachment(metadata);\n\n    \u002F\u002F Track in-memory (will be restored after hibernation)\n    this.sessions.set(server, metadata);\n\n    \u002F\u002F Notify others\n    this.broadcast(`${username} joined`, server);\n\n    \u002F\u002F Return client WebSocket to browser\n    return new Response(null, {\n      status: 101,\n      webSocket: client,\n    });\n  }\n\n  \u002F\u002F Called when WebSocket receives a message\n  async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise\u003Cvoid> {\n    const session = this.sessions.get(ws);\n\n    if (typeof message === 'string') {\n      const data = JSON.parse(message);\n\n      if (data.type === 'chat') {\n        \u002F\u002F Broadcast to all connections\n        this.broadcast(`${session?.username}: ${data.text}`, ws);\n      }\n    }\n  }\n\n  \u002F\u002F Called when WebSocket closes\n  async webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean): Promise\u003Cvoid> {\n    const session = this.sessions.get(ws);\n    this.sessions.delete(ws);\n\n    \u002F\u002F Close the WebSocket\n    ws.close(code, 'Durable Object closing WebSocket');\n\n    \u002F\u002F Notify others\n    if (session) {\n      this.broadcast(`${session.username} left`);\n    }\n  }\n\n  \u002F\u002F Called on WebSocket errors\n  async webSocketError(ws: WebSocket, error: any): Promise\u003Cvoid> {\n    console.error('WebSocket error:', error);\n    const session = this.sessions.get(ws);\n    this.sessions.delete(ws);\n  }\n\n  \u002F\u002F Helper to broadcast to all connections\n  broadcast(message: string, except?: WebSocket): void {\n    this.sessions.forEach((session, ws) => {\n      if (ws !== except && ws.readyState === WebSocket.OPEN) {\n        ws.send(JSON.stringify({ type: 'message', text: message }));\n      }\n    });\n  }\n}\n```\n\n**WebSocket Handler Methods:**\n\n```typescript\n\u002F\u002F Receive message from client\nasync webSocketMessage(\n  ws: WebSocket,\n  message: string | ArrayBuffer\n): Promise\u003Cvoid> {\n  \u002F\u002F Handle message\n}\n\n\u002F\u002F WebSocket closed by client\nasync webSocketClose(\n  ws: WebSocket,\n  code: number,\n  reason: string,\n  wasClean: boolean\n): Promise\u003Cvoid> {\n  \u002F\u002F Cleanup\n}\n\n\u002F\u002F WebSocket error occurred\nasync webSocketError(\n  ws: WebSocket,\n  error: any\n): Promise\u003Cvoid> {\n  \u002F\u002F Handle error\n}\n```\n\n**Hibernation-Safe Patterns:**\n\n```typescript\n\u002F\u002F ✅ CORRECT: Use ctx.acceptWebSocket (enables hibernation)\nthis.ctx.acceptWebSocket(server);\n\n\u002F\u002F ❌ WRONG: Don't use ws.accept() (standard API, no hibernation)\nserver.accept();\n\n\u002F\u002F ✅ CORRECT: Persist metadata across hibernation\nserver.serializeAttachment({ userId: '123', username: 'Alice' });\n\n\u002F\u002F ✅ CORRECT: Restore metadata in constructor\nconstructor(ctx, env) {\n  super(ctx, env);\n\n  ctx.getWebSockets().forEach((ws) => {\n    const metadata = ws.deserializeAttachment();\n    this.sessions.set(ws, metadata);\n  });\n}\n\n\u002F\u002F ❌ WRONG: Don't use setTimeout\u002FsetInterval (prevents hibernation)\nsetTimeout(() => { \u002F* ... *\u002F }, 1000);  \u002F\u002F ❌ NEVER DO THIS\n\n\u002F\u002F ✅ CORRECT: Use alarms for scheduled tasks\nawait this.ctx.storage.setAlarm(Date.now() + 60000);\n```\n\n**When Hibernation Does NOT Occur:**\n- `setTimeout` or `setInterval` callbacks are pending\n- In-progress `fetch()` request (awaited I\u002FO)\n- Standard WebSocket API is used (not hibernation API)\n- Request\u002Fevent is still being processed\n\n---\n\n## Alarms API - Scheduled Tasks\n\nThe **Alarms API** allows Durable Objects to schedule themselves to wake up at a specific time in the future.\n\n**Use for:** Batching, cleanup jobs, reminders, periodic tasks, delayed operations\n\n### Basic Alarm Pattern\n\n```typescript\nimport { DurableObject } from 'cloudflare:workers';\n\nexport class Batcher extends DurableObject {\n  buffer: string[];\n\n  constructor(ctx: DurableObjectState, env: Env) {\n    super(ctx, env);\n\n    ctx.blockConcurrencyWhile(async () => {\n      \u002F\u002F Restore buffer from storage\n      this.buffer = await ctx.storage.get('buffer') || [];\n    });\n  }\n\n  async addItem(item: string): Promise\u003Cvoid> {\n    this.buffer.push(item);\n    await this.ctx.storage.put('buffer', this.buffer);\n\n    \u002F\u002F Schedule alarm for 10 seconds from now (if not already set)\n    const currentAlarm = await this.ctx.storage.getAlarm();\n    if (currentAlarm === null) {\n      await this.ctx.storage.setAlarm(Date.now() + 10000);\n    }\n  }\n\n  \u002F\u002F Called when alarm fires\n  async alarm(alarmInfo: { retryCount: number; isRetry: boolean }): Promise\u003Cvoid> {\n    console.log(`Alarm fired (retry count: ${alarmInfo.retryCount})`);\n\n    \u002F\u002F Process batch\n    if (this.buffer.length > 0) {\n      await this.processBatch(this.buffer);\n\n      \u002F\u002F Clear buffer\n      this.buffer = [];\n      await this.ctx.storage.put('buffer', []);\n    }\n\n    \u002F\u002F Alarm is automatically deleted after successful execution\n  }\n\n  async processBatch(items: string[]): Promise\u003Cvoid> {\n    \u002F\u002F Send to external API, write to database, etc.\n    console.log(`Processing ${items.length} items:`, items);\n  }\n}\n```\n\n**Alarm API Methods:**\n\n```typescript\n\u002F\u002F Set alarm to fire at specific timestamp\nawait this.ctx.storage.setAlarm(Date.now() + 60000);  \u002F\u002F 60 seconds from now\n\n\u002F\u002F Set alarm to fire at specific date\nawait this.ctx.storage.setAlarm(new Date('2025-12-31T23:59:59Z'));\n\n\u002F\u002F Get current alarm (null if not set)\nconst alarmTime = await this.ctx.storage.getAlarm();\n\n\u002F\u002F Delete alarm\nawait this.ctx.storage.deleteAlarm();\n\n\u002F\u002F Alarm handler (called when alarm fires)\nasync alarm(alarmInfo: { retryCount: number; isRetry: boolean }): Promise\u003Cvoid> {\n  \u002F\u002F Do work\n}\n```\n\n**Alarm Behavior:**\n- ✅ **Guaranteed at-least-once execution** - will retry on failure\n- ✅ **Automatic retries** - up to 6 retries with exponential backoff (starting at 2 seconds)\n- ✅ **Persistent** - survives DO hibernation and eviction\n- ✅ **Automatically deleted** after successful execution\n- ⚠️ **One alarm per DO** - setting a new alarm overwrites the previous one\n\n**Retry Pattern (Idempotent Operations):**\n\n```typescript\nasync alarm(alarmInfo: { retryCount: number; isRetry: boolean }): Promise\u003Cvoid> {\n  if (alarmInfo.retryCount > 3) {\n    console.error('Alarm failed after 3 retries, giving up');\n    return;\n  }\n\n  try {\n    \u002F\u002F Idempotent operation (safe to retry)\n    await this.sendNotification();\n  } catch (error) {\n    console.error('Alarm failed:', error);\n    throw error;  \u002F\u002F Will trigger retry\n  }\n}\n```\n\n---\n\n## RPC vs HTTP Fetch\n\nDurable Objects support **two invocation patterns**:\n\n1. **RPC (Remote Procedure Call)** - Recommended for new projects\n2. **HTTP Fetch** - For HTTP request\u002Fresponse flows or legacy compatibility\n\n### RPC Pattern (Recommended)\n\n**Enable RPC** with compatibility date `>= 2024-04-03`:\n\n```jsonc\n{\n  \"compatibility_date\": \"2025-10-22\"\n}\n```\n\n**Define RPC methods** on DO class:\n\n```typescript\nexport class Counter extends DurableObject {\n  \u002F\u002F Public RPC methods (automatically exposed)\n  async increment(): Promise\u003Cnumber> {\n    let value = await this.ctx.storage.get\u003Cnumber>('count') || 0;\n    value += 1;\n    await this.ctx.storage.put('count', value);\n    return value;\n  }\n\n  async decrement(): Promise\u003Cnumber> {\n    let value = await this.ctx.storage.get\u003Cnumber>('count') || 0;\n    value -= 1;\n    await this.ctx.storage.put('count', value);\n    return value;\n  }\n\n  async get(): Promise\u003Cnumber> {\n    return await this.ctx.storage.get\u003Cnumber>('count') || 0;\n  }\n}\n```\n\n**Call from Worker:**\n\n```typescript\n\u002F\u002F Get stub\nconst id = env.COUNTER.idFromName('my-counter');\nconst stub = env.COUNTER.get(id);\n\n\u002F\u002F Call RPC methods directly\nconst count = await stub.increment();\nconst current = await stub.get();\n```\n\n**RPC Benefits:**\n- ✅ **Type-safe** - TypeScript knows method signatures\n- ✅ **Simple** - Direct method calls, no HTTP ceremony\n- ✅ **Automatic serialization** - Handles structured data\n- ✅ **Exception propagation** - Errors thrown in DO are received in Worker\n\n### HTTP Fetch Pattern\n\n**Define `fetch()` handler** on DO class:\n\n```typescript\nexport class Counter extends DurableObject {\n  async fetch(request: Request): Promise\u003CResponse> {\n    const url = new URL(request.url);\n\n    if (url.pathname === '\u002Fincrement' && request.method === 'POST') {\n      let value = await this.ctx.storage.get\u003Cnumber>('count') || 0;\n      value += 1;\n      await this.ctx.storage.put('count', value);\n      return new Response(JSON.stringify({ count: value }));\n    }\n\n    if (url.pathname === '\u002Fget' && request.method === 'GET') {\n      let value = await this.ctx.storage.get\u003Cnumber>('count') || 0;\n      return new Response(JSON.stringify({ count: value }));\n    }\n\n    return new Response('Not found', { status: 404 });\n  }\n}\n```\n\n**Call from Worker:**\n\n```typescript\n\u002F\u002F Get stub\nconst id = env.COUNTER.idFromName('my-counter');\nconst stub = env.COUNTER.get(id);\n\n\u002F\u002F Call fetch\nconst response = await stub.fetch('https:\u002F\u002Ffake-host\u002Fincrement', {\n  method: 'POST',\n});\n\nconst data = await response.json();\n```\n\n### When to Use Each\n\n| Use Case | Recommendation |\n|----------|----------------|\n| **New project** | ✅ RPC (simpler, type-safe) |\n| **HTTP request\u002Fresponse flow** | HTTP Fetch |\n| **Complex routing logic** | HTTP Fetch |\n| **Type safety important** | ✅ RPC |\n| **Legacy compatibility** | HTTP Fetch |\n| **WebSocket upgrades** | HTTP Fetch (required) |\n\n---\n\n## Creating Durable Object Stubs and Routing\n\nTo interact with a Durable Object from a Worker, you need to:\n1. Get a **Durable Object ID**\n2. Create a **stub** from the ID\n3. Call methods on the stub\n\n### Getting Durable Object IDs\n\n**Three methods to create IDs:**\n\n#### 1. `idFromName(name)` - Named DOs (Most Common)\n\nUse when you want **consistent routing** to the same DO instance based on a name:\n\n```typescript\n\u002F\u002F Same name always routes to same DO instance globally\nconst roomId = env.CHAT_ROOM.idFromName('room-123');\nconst userId = env.USER_SESSION.idFromName('user-alice');\nconst globalCounter = env.COUNTER.idFromName('global');\n```\n\n**Use for:**\n- Chat rooms (name = room ID)\n- User sessions (name = user ID)\n- Per-tenant logic (name = tenant ID)\n- Global singletons (name = 'global')\n\n**Characteristics:**\n- ✅ **Deterministic** - same name = same DO instance\n- ✅ **Easy to reference** - just need the name string\n- ⚠️ **First access latency** - ~100-300ms for global uniqueness check\n- ⚠️ **Cached after first use** - subsequent access is fast\n\n#### 2. `newUniqueId()` - Random IDs\n\nUse when you need a **new, unique DO instance**:\n\n```typescript\n\u002F\u002F Creates a random, globally unique ID\nconst id = env.MY_DO.newUniqueId();\n\n\u002F\u002F With jurisdiction restriction (EU data residency)\nconst euId = env.MY_DO.newUniqueId({ jurisdiction: 'eu' });\n\n\u002F\u002F Store the ID for future use\nconst idString = id.toString();\nawait env.KV.put('session:123', idString);\n```\n\n**Use for:**\n- Creating new sessions\u002Frooms that don't exist yet\n- One-time use DOs\n- When you don't have a natural name\n\n**Characteristics:**\n- ✅ **Lower latency** on first use (no global uniqueness check)\n- ⚠️ **Must store ID** to access same DO later\n- ⚠️ **ID format is opaque** - can't derive meaning from it\n\n#### 3. `idFromString(idString)` - Recreate from Saved ID\n\nUse when you've **previously stored an ID** and need to recreate it:\n\n```typescript\n\u002F\u002F Get stored ID string (from KV, D1, cookie, etc.)\nconst idString = await env.KV.get('session:123');\n\n\u002F\u002F Recreate ID\nconst id = env.MY_DO.idFromString(idString);\n\n\u002F\u002F Get stub\nconst stub = env.MY_DO.get(id);\n```\n\n**Throws exception** if:\n- ID string is invalid\n- ID was not created from the same `DurableObjectNamespace`\n\n### Getting Stubs\n\n#### Method 1: `get(id)` - From ID\n\n```typescript\nconst id = env.MY_DO.idFromName('my-instance');\nconst stub = env.MY_DO.get(id);\n\n\u002F\u002F Call methods\nawait stub.myMethod();\n```\n\n#### Method 2: `getByName(name)` - Shortcut for Named DOs\n\n```typescript\n\u002F\u002F Shortcut that combines idFromName + get\nconst stub = env.MY_DO.getByName('my-instance');\n\n\u002F\u002F Equivalent to:\n\u002F\u002F const id = env.MY_DO.idFromName('my-instance');\n\u002F\u002F const stub = env.MY_DO.get(id);\n\nawait stub.myMethod();\n```\n\n**Recommended** for named DOs (cleaner code).\n\n### Location Hints (Geographic Routing)\n\n**Control WHERE a Durable Object is created** with location hints:\n\n```typescript\n\u002F\u002F Create DO near specific location\nconst id = env.MY_DO.idFromName('user-alice');\nconst stub = env.MY_DO.get(id, { locationHint: 'enam' });  \u002F\u002F Eastern North America\n\n\u002F\u002F Available location hints:\n\u002F\u002F - 'wnam' - Western North America\n\u002F\u002F - 'enam' - Eastern North America\n\u002F\u002F - 'sam'  - South America\n\u002F\u002F - 'weur' - Western Europe\n\u002F\u002F - 'eeur' - Eastern Europe\n\u002F\u002F - 'apac' - Asia-Pacific\n\u002F\u002F - 'oc'   - Oceania\n\u002F\u002F - 'afr'  - Africa\n\u002F\u002F - 'me'   - Middle East\n```\n\n**When to use:**\n- ✅ Create DO near user's location (lower latency)\n- ✅ Data residency requirements (e.g., EU users → weur\u002Feeur)\n\n**Limitations:**\n- ⚠️ **Hints are best-effort** - not guaranteed\n- ⚠️ **Only affects first creation** - subsequent access uses existing location\n- ⚠️ **Cannot move existing DOs** - once created, location is fixed\n\n### Jurisdiction Restriction (Data Residency)\n\n**Enforce strict data location** requirements:\n\n```typescript\n\u002F\u002F Create DO that MUST stay in EU\nconst euId = env.MY_DO.newUniqueId({ jurisdiction: 'eu' });\n\n\u002F\u002F Available jurisdictions:\n\u002F\u002F - 'eu' - European Union\n\u002F\u002F - 'fedramp' - FedRAMP (US government)\n```\n\n**Use for:**\n- Regulatory compliance (GDPR, FedRAMP)\n- Data sovereignty requirements\n\n**CRITICAL:**\n- ✅ **Strictly enforced** - DO will never leave jurisdiction\n- ⚠️ **Cannot combine** jurisdiction with location hints\n- ⚠️ **Higher latency** for users outside jurisdiction\n\n---\n\n## Migrations - Managing DO Classes\n\n**Migrations are REQUIRED** when you:\n- Create a new DO class\n- Rename a DO class\n- Delete a DO class\n- Transfer a DO class to another Worker\n\n**Migration Types:**\n\n### 1. Create New DO Class\n\n```jsonc\n{\n  \"durable_objects\": {\n    \"bindings\": [\n      {\n        \"name\": \"COUNTER\",\n        \"class_name\": \"Counter\"\n      }\n    ]\n  },\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",                    \u002F\u002F Unique identifier for this migration\n      \"new_sqlite_classes\": [         \u002F\u002F SQLite backend (recommended)\n        \"Counter\"\n      ]\n    }\n  ]\n}\n```\n\n**For KV backend (legacy):**\n\n```jsonc\n{\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",\n      \"new_classes\": [\"Counter\"]      \u002F\u002F KV backend (128MB limit)\n    }\n  ]\n}\n```\n\n**CRITICAL:**\n- ✅ Use `new_sqlite_classes` for new DOs (up to 1GB storage)\n- ❌ Cannot enable SQLite on existing deployed KV-backed DOs\n\n### 2. Rename DO Class\n\n```jsonc\n{\n  \"durable_objects\": {\n    \"bindings\": [\n      {\n        \"name\": \"MY_DO\",\n        \"class_name\": \"NewClassName\"    \u002F\u002F New class name\n      }\n    ]\n  },\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",\n      \"new_sqlite_classes\": [\"OldClassName\"]\n    },\n    {\n      \"tag\": \"v2\",                      \u002F\u002F New migration tag\n      \"renamed_classes\": [\n        {\n          \"from\": \"OldClassName\",\n          \"to\": \"NewClassName\"\n        }\n      ]\n    }\n  ]\n}\n```\n\n**What happens:**\n- ✅ Existing DO instances keep their data\n- ✅ Old bindings automatically forward to new class\n- ⚠️ **Must export new class** in Worker code\n\n### 3. Delete DO Class\n\n```jsonc\n{\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",\n      \"new_sqlite_classes\": [\"Counter\"]\n    },\n    {\n      \"tag\": \"v2\",\n      \"deleted_classes\": [\"Counter\"]    \u002F\u002F Mark as deleted\n    }\n  ]\n}\n```\n\n**What happens:**\n- ✅ Existing DO instances are **deleted immediately**\n- ✅ All storage is deleted\n- ⚠️ **Cannot undo** - data is permanently lost\n\n**Before deleting:**\n- Export data if needed\n- Update Workers that reference this DO\n\n### 4. Transfer DO Class to Another Worker\n\n```jsonc\n\u002F\u002F In destination Worker:\n{\n  \"durable_objects\": {\n    \"bindings\": [\n      {\n        \"name\": \"TRANSFERRED_DO\",\n        \"class_name\": \"TransferredClass\"\n      }\n    ]\n  },\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",\n      \"transferred_classes\": [\n        {\n          \"from\": \"OriginalClass\",\n          \"from_script\": \"original-worker\",  \u002F\u002F Source Worker name\n          \"to\": \"TransferredClass\"\n        }\n      ]\n    }\n  ]\n}\n```\n\n**What happens:**\n- ✅ DO instances move to new Worker\n- ✅ All storage is transferred\n- ✅ Old bindings automatically forward\n- ⚠️ **Destination class must be exported**\n\n### Migration Rules\n\n**CRITICAL Migration Gotchas:**\n\n❌ **Migrations are ATOMIC** - cannot gradual deploy\n- All instances migrate at once when you deploy\n- No partial rollout support\n\n❌ **Migration tags must be unique**\n- Cannot reuse tags\n- Tags are append-only\n\n❌ **Cannot enable SQLite on existing KV-backed DOs**\n- Must create new DO class instead\n\n✅ **Code changes don't need migrations**\n- Only schema changes (new\u002Frename\u002Fdelete\u002Ftransfer) need migrations\n- You can deploy code updates freely\n\n✅ **Global uniqueness is per account**\n- DO class names are unique across your entire account\n- Even across different Workers\n\n---\n\n## Common Patterns\n\n### Pattern 1: Rate Limiting (Per-User)\n\n```typescript\nexport class RateLimiter extends DurableObject {\n  async checkLimit(userId: string, limit: number, window: number): Promise\u003Cboolean> {\n    const key = `rate:${userId}`;\n    const now = Date.now();\n\n    \u002F\u002F Get recent requests\n    const requests = await this.ctx.storage.get\u003Cnumber[]>(key) || [];\n\n    \u002F\u002F Remove requests outside window\n    const validRequests = requests.filter(timestamp => now - timestamp \u003C window);\n\n    \u002F\u002F Check limit\n    if (validRequests.length >= limit) {\n      return false;  \u002F\u002F Rate limit exceeded\n    }\n\n    \u002F\u002F Add current request\n    validRequests.push(now);\n    await this.ctx.storage.put(key, validRequests);\n\n    return true;  \u002F\u002F Within limit\n  }\n}\n\n\u002F\u002F Worker usage:\nconst limiter = env.RATE_LIMITER.getByName(userId);\nconst allowed = await limiter.checkLimit(userId, 100, 60000);  \u002F\u002F 100 req\u002Fmin\n\nif (!allowed) {\n  return new Response('Rate limit exceeded', { status: 429 });\n}\n```\n\n### Pattern 2: Session Management\n\n```typescript\nexport class UserSession extends DurableObject {\n  sql: SqlStorage;\n\n  constructor(ctx: DurableObjectState, env: Env) {\n    super(ctx, env);\n    this.sql = ctx.storage.sql;\n\n    this.sql.exec(`\n      CREATE TABLE IF NOT EXISTS session (\n        key TEXT PRIMARY KEY,\n        value TEXT NOT NULL,\n        expires_at INTEGER\n      );\n    `);\n\n    \u002F\u002F Schedule cleanup alarm\n    ctx.blockConcurrencyWhile(async () => {\n      const alarm = await ctx.storage.getAlarm();\n      if (alarm === null) {\n        await ctx.storage.setAlarm(Date.now() + 3600000);  \u002F\u002F 1 hour\n      }\n    });\n  }\n\n  async set(key: string, value: any, ttl?: number): Promise\u003Cvoid> {\n    const expiresAt = ttl ? Date.now() + ttl : null;\n\n    this.sql.exec(\n      'INSERT OR REPLACE INTO session (key, value, expires_at) VALUES (?, ?, ?)',\n      key,\n      JSON.stringify(value),\n      expiresAt\n    );\n  }\n\n  async get(key: string): Promise\u003Cany | null> {\n    const cursor = this.sql.exec(\n      'SELECT value, expires_at FROM session WHERE key = ?',\n      key\n    );\n\n    const row = cursor.one\u003C{ value: string; expires_at: number | null }>({ allowNone: true });\n\n    if (!row) {\n      return null;\n    }\n\n    \u002F\u002F Check expiration\n    if (row.expires_at && row.expires_at \u003C Date.now()) {\n      this.sql.exec('DELETE FROM session WHERE key = ?', key);\n      return null;\n    }\n\n    return JSON.parse(row.value);\n  }\n\n  async alarm(): Promise\u003Cvoid> {\n    \u002F\u002F Cleanup expired sessions\n    this.sql.exec('DELETE FROM session WHERE expires_at \u003C ?', Date.now());\n\n    \u002F\u002F Schedule next cleanup\n    await this.ctx.storage.setAlarm(Date.now() + 3600000);\n  }\n}\n```\n\n### Pattern 3: Leader Election\n\n```typescript\nexport class LeaderElection extends DurableObject {\n  sql: SqlStorage;\n\n  constructor(ctx: DurableObjectState, env: Env) {\n    super(ctx, env);\n    this.sql = ctx.storage.sql;\n\n    this.sql.exec(`\n      CREATE TABLE IF NOT EXISTS leader (\n        id INTEGER PRIMARY KEY CHECK (id = 1),\n        worker_id TEXT NOT NULL,\n        elected_at INTEGER NOT NULL\n      );\n    `);\n  }\n\n  async electLeader(workerId: string): Promise\u003Cboolean> {\n    \u002F\u002F Try to become leader\n    try {\n      this.sql.exec(\n        'INSERT INTO leader (id, worker_id, elected_at) VALUES (1, ?, ?)',\n        workerId,\n        Date.now()\n      );\n      return true;  \u002F\u002F Became leader\n    } catch (error) {\n      return false;  \u002F\u002F Someone else is leader\n    }\n  }\n\n  async getLeader(): Promise\u003Cstring | null> {\n    const cursor = this.sql.exec('SELECT worker_id FROM leader WHERE id = 1');\n    const row = cursor.one\u003C{ worker_id: string }>({ allowNone: true });\n    return row?.worker_id || null;\n  }\n\n  async releaseLeadership(workerId: string): Promise\u003Cvoid> {\n    this.sql.exec('DELETE FROM leader WHERE id = 1 AND worker_id = ?', workerId);\n  }\n}\n```\n\n### Pattern 4: Multi-DO Coordination\n\n```typescript\n\u002F\u002F Coordinator DO\nexport class GameCoordinator extends DurableObject {\n  async createGame(gameId: string, env: Env): Promise\u003Cvoid> {\n    \u002F\u002F Create game room DO\n    const gameRoom = env.GAME_ROOM.getByName(gameId);\n    await gameRoom.initialize();\n\n    \u002F\u002F Track in coordinator\n    await this.ctx.storage.put(`game:${gameId}`, {\n      id: gameId,\n      created: Date.now(),\n    });\n  }\n\n  async listGames(): Promise\u003Cstring[]> {\n    const games = await this.ctx.storage.list({ prefix: 'game:' });\n    return Array.from(games.keys()).map(key => key.replace('game:', ''));\n  }\n}\n\n\u002F\u002F Game room DO\nexport class GameRoom extends DurableObject {\n  async initialize(): Promise\u003Cvoid> {\n    await this.ctx.storage.put('state', {\n      players: [],\n      started: false,\n    });\n  }\n\n  async addPlayer(playerId: string): Promise\u003Cvoid> {\n    const state = await this.ctx.storage.get('state');\n    state.players.push(playerId);\n    await this.ctx.storage.put('state', state);\n  }\n}\n```\n\n---\n\n## Critical Rules\n\n### Always Do\n\n✅ **Export DO class** from Worker\n```typescript\nexport class MyDO extends DurableObject { }\nexport default MyDO;  \u002F\u002F Required\n```\n\n✅ **Call `super(ctx, env)`** in constructor\n```typescript\nconstructor(ctx: DurableObjectState, env: Env) {\n  super(ctx, env);  \u002F\u002F Required first line\n}\n```\n\n✅ **Use `new_sqlite_classes`** for new DOs\n```jsonc\n{ \"tag\": \"v1\", \"new_sqlite_classes\": [\"MyDO\"] }\n```\n\n✅ **Use `ctx.acceptWebSocket()`** for hibernation\n```typescript\nthis.ctx.acceptWebSocket(server);  \u002F\u002F Enables hibernation\n```\n\n✅ **Persist critical state** to storage (not just memory)\n```typescript\nawait this.ctx.storage.put('important', value);\n```\n\n✅ **Use alarms** instead of setTimeout\u002FsetInterval\n```typescript\nawait this.ctx.storage.setAlarm(Date.now() + 60000);\n```\n\n✅ **Use parameterized SQL queries**\n```typescript\nthis.sql.exec('SELECT * FROM table WHERE id = ?', id);\n```\n\n✅ **Minimize constructor work**\n```typescript\nconstructor(ctx, env) {\n  super(ctx, env);\n  \u002F\u002F Minimal initialization only\n  ctx.blockConcurrencyWhile(async () => {\n    \u002F\u002F Load from storage\n  });\n}\n```\n\n### Never Do\n\n❌ **Create DO without migration**\n```jsonc\n\u002F\u002F Missing migrations array = error\n```\n\n❌ **Forget to export DO class**\n```typescript\nclass MyDO extends DurableObject { }\n\u002F\u002F Missing: export default MyDO;\n```\n\n❌ **Use `setTimeout` or `setInterval`**\n```typescript\nsetTimeout(() => {}, 1000);  \u002F\u002F Prevents hibernation\n```\n\n❌ **Rely only on in-memory state** with WebSockets\n```typescript\n\u002F\u002F ❌ WRONG: this.sessions will be lost on hibernation\n\u002F\u002F ✅ CORRECT: Use serializeAttachment()\n```\n\n❌ **Deploy migrations gradually**\n```bash\n# Migrations are atomic - cannot use gradual rollout\n```\n\n❌ **Enable SQLite on existing KV-backed DO**\n```jsonc\n\u002F\u002F Not supported - must create new DO class instead\n```\n\n❌ **Use standard WebSocket API** expecting hibernation\n```typescript\nws.accept();  \u002F\u002F ❌ No hibernation\nthis.ctx.acceptWebSocket(ws);  \u002F\u002F ✅ Hibernation enabled\n```\n\n❌ **Assume location hints are guaranteed**\n```typescript\n\u002F\u002F Location hints are best-effort only\n```\n\n---\n\n## Known Issues Prevention\n\nThis skill prevents **15+ documented issues**:\n\n### Issue #1: Class Not Exported\n**Error**: `\"binding not found\"` or `\"Class X not found\"`\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fget-started\u002F\n**Why It Happens**: DO class not exported from Worker\n**Prevention**:\n```typescript\nexport class MyDO extends DurableObject { }\nexport default MyDO;  \u002F\u002F ← Required\n```\n\n### Issue #2: Missing Migration\n**Error**: `\"migrations required\"` or `\"no migration found for class\"`\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Freference\u002Fdurable-objects-migrations\u002F\n**Why It Happens**: Created DO class without migration entry\n**Prevention**: Always add migration when creating new DO class\n```jsonc\n{\n  \"migrations\": [\n    { \"tag\": \"v1\", \"new_sqlite_classes\": [\"MyDO\"] }\n  ]\n}\n```\n\n### Issue #3: Wrong Migration Type (KV vs SQLite)\n**Error**: Schema errors, storage API mismatch\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fapi\u002Fsqlite-storage-api\u002F\n**Why It Happens**: Used `new_classes` instead of `new_sqlite_classes`\n**Prevention**: Use `new_sqlite_classes` for SQLite backend (recommended)\n\n### Issue #4: Constructor Overhead Blocks Hibernation Wake\n**Error**: Slow hibernation wake-up times\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fbest-practices\u002Faccess-durable-objects-storage\u002F\n**Why It Happens**: Heavy work in constructor\n**Prevention**: Minimize constructor, use `blockConcurrencyWhile()`\n```typescript\nconstructor(ctx, env) {\n  super(ctx, env);\n  ctx.blockConcurrencyWhile(async () => {\n    \u002F\u002F Load from storage\n  });\n}\n```\n\n### Issue #5: setTimeout Breaks Hibernation\n**Error**: DO never hibernates, high duration charges\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fconcepts\u002Fdurable-object-lifecycle\u002F\n**Why It Happens**: `setTimeout`\u002F`setInterval` prevents hibernation\n**Prevention**: Use alarms API instead\n```typescript\n\u002F\u002F ❌ WRONG\nsetTimeout(() => {}, 1000);\n\n\u002F\u002F ✅ CORRECT\nawait this.ctx.storage.setAlarm(Date.now() + 1000);\n```\n\n### Issue #6: In-Memory State Lost on Hibernation\n**Error**: WebSocket metadata lost, state reset unexpectedly\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fbest-practices\u002Fwebsockets\u002F\n**Why It Happens**: Relied on in-memory state that's cleared on hibernation\n**Prevention**: Use `serializeAttachment()` for WebSocket metadata\n```typescript\nws.serializeAttachment({ userId, username });\n\n\u002F\u002F Restore in constructor\nctx.getWebSockets().forEach(ws => {\n  const metadata = ws.deserializeAttachment();\n  this.sessions.set(ws, metadata);\n});\n```\n\n### Issue #7: Outgoing WebSocket Cannot Hibernate\n**Error**: High charges despite hibernation API\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fbest-practices\u002Fwebsockets\u002F\n**Why It Happens**: Outgoing WebSockets don't support hibernation\n**Prevention**: Only use hibernation for server-side (incoming) WebSockets\n\n### Issue #8: Global Uniqueness Confusion\n**Error**: Unexpected DO class name conflicts\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fplatform\u002Fknown-issues\u002F#global-uniqueness\n**Why It Happens**: DO class names are globally unique per account\n**Prevention**: Understand DO class names are shared across all Workers in account\n\n### Issue #9: Partial deleteAll on KV Backend\n**Error**: Storage not fully deleted, billing continues\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fapi\u002Flegacy-kv-storage-api\u002F\n**Why It Happens**: KV backend `deleteAll()` can fail partially\n**Prevention**: Use SQLite backend for atomic deleteAll\n\n### Issue #10: Binding Name Mismatch\n**Error**: Runtime error accessing DO binding\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fget-started\u002F\n**Why It Happens**: Binding name in wrangler.jsonc doesn't match code\n**Prevention**: Ensure consistency\n```jsonc\n{ \"bindings\": [{ \"name\": \"MY_DO\", \"class_name\": \"MyDO\" }] }\n```\n```typescript\nenv.MY_DO.getByName('instance');  \u002F\u002F Must match binding name\n```\n\n### Issue #11: State Size Exceeded\n**Error**: `\"state limit exceeded\"` or storage errors\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fplatform\u002Fpricing\u002F\n**Why It Happens**: Exceeded 1GB (SQLite) or 128MB (KV) limit\n**Prevention**: Monitor storage size, implement cleanup with alarms\n\n### Issue #12: Migration Not Atomic\n**Error**: Gradual deployment blocked\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkers\u002Fconfiguration\u002Fversions-and-deployments\u002Fgradual-deployments\u002F\n**Why It Happens**: Tried to use gradual rollout with migrations\n**Prevention**: Migrations deploy atomically across all instances\n\n### Issue #13: Location Hint Ignored\n**Error**: DO created in wrong region\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Freference\u002Fdata-location\u002F\n**Why It Happens**: Location hints are best-effort, not guaranteed\n**Prevention**: Use jurisdiction for strict requirements\n\n### Issue #14: Alarm Retry Failures\n**Error**: Tasks lost after alarm failures\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fapi\u002Falarms\u002F\n**Why It Happens**: Alarm handler throws errors repeatedly\n**Prevention**: Implement idempotent alarm handlers\n```typescript\nasync alarm(info: { retryCount: number }): Promise\u003Cvoid> {\n  if (info.retryCount > 3) {\n    console.error('Giving up after 3 retries');\n    return;\n  }\n  \u002F\u002F Idempotent operation\n}\n```\n\n### Issue #15: Fetch Blocks Hibernation\n**Error**: DO never hibernates despite using hibernation API\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fconcepts\u002Fdurable-object-lifecycle\u002F\n**Why It Happens**: In-progress `fetch()` requests prevent hibernation\n**Prevention**: Ensure all async I\u002FO completes before idle period\n\n---\n\n## Configuration Reference\n\n### Complete wrangler.jsonc Example\n\n```jsonc\n{\n  \"$schema\": \"node_modules\u002Fwrangler\u002Fconfig-schema.json\",\n  \"name\": \"my-worker\",\n  \"main\": \"src\u002Findex.ts\",\n  \"compatibility_date\": \"2025-10-22\",\n\n  \u002F\u002F Durable Objects configuration\n  \"durable_objects\": {\n    \"bindings\": [\n      {\n        \"name\": \"COUNTER\",              \u002F\u002F Binding name (use as env.COUNTER)\n        \"class_name\": \"Counter\"         \u002F\u002F Must match exported class\n      },\n      {\n        \"name\": \"CHAT_ROOM\",\n        \"class_name\": \"ChatRoom\"\n      }\n    ]\n  },\n\n  \u002F\u002F Migrations (required for all DO changes)\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",                      \u002F\u002F Initial migration\n      \"new_sqlite_classes\": [\n        \"Counter\",\n        \"ChatRoom\"\n      ]\n    },\n    {\n      \"tag\": \"v2\",                      \u002F\u002F Rename example\n      \"renamed_classes\": [\n        {\n          \"from\": \"Counter\",\n          \"to\": \"CounterV2\"\n        }\n      ]\n    }\n  ]\n}\n```\n\n---\n\n## TypeScript Types\n\n```typescript\nimport { DurableObject, DurableObjectState, DurableObjectNamespace } from 'cloudflare:workers';\n\n\u002F\u002F Environment bindings\ninterface Env {\n  MY_DO: DurableObjectNamespace\u003CMyDurableObject>;\n  DB: D1Database;\n  \u002F\u002F ... other bindings\n}\n\n\u002F\u002F Durable Object class\nexport class MyDurableObject extends DurableObject\u003CEnv> {\n  sql: SqlStorage;\n\n  constructor(ctx: DurableObjectState, env: Env) {\n    super(ctx, env);\n    this.sql = ctx.storage.sql;\n  }\n\n  async myMethod(): Promise\u003Cstring> {\n    \u002F\u002F Access env bindings\n    await this.env.DB.prepare('...').run();\n    return 'Hello';\n  }\n}\n```\n\n---\n\n## Official Documentation\n\n- **Durable Objects**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002F\n- **State API (SQL)**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fapi\u002Fsqlite-storage-api\u002F\n- **WebSocket Hibernation**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fbest-practices\u002Fwebsockets\u002F\n- **Alarms API**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fapi\u002Falarms\u002F\n- **Migrations**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Freference\u002Fdurable-objects-migrations\u002F\n- **Best Practices**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fbest-practices\u002F\n- **Pricing**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fplatform\u002Fpricing\u002F\n\n---\n\n**Questions? Issues?**\n\n1. Check `references\u002Ftop-errors.md` for common problems\n2. Review `templates\u002F` for working examples\n3. Consult official docs: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002F\n4. Verify migrations configuration carefully\n","# Cloudflare Durable Objects\n\n**Status**: Production Ready ✅\n**Last Updated**: 2025-10-22\n**Dependencies**: cloudflare-worker-base (recommended)\n**Latest Versions**: wrangler@4.43.0+, @cloudflare\u002Fworkers-types@4.20251014.0+\n**Official Docs**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002F\n\n---\n\n## What are Durable Objects?\n\nCloudflare Durable Objects are **globally unique, stateful objects** that provide:\n\n- **Single-point coordination** - Each Durable Object instance is globally unique across Cloudflare's network\n- **Strong consistency** - Transactional, serializable storage (ACID guarantees)\n- **Real-time communication** - WebSocket Hibernation API for thousands of connections per instance\n- **Persistent state** - Built-in SQLite database (up to 1GB) or key-value storage\n- **Scheduled tasks** - Alarms API for future task execution\n- **Global distribution** - Automatically routed to optimal location\n- **Automatic scaling** - Millions of independent instances\n\n**Use Cases**:\n- Chat rooms and real-time collaboration\n- Multiplayer game servers\n- Rate limiting and session management\n- Leader election and coordination\n- WebSocket servers with hibernation\n- Stateful workflows and queues\n- Per-user or per-room logic\n\n---\n\n## Quick Start (10 Minutes)\n\n### Option 1: Scaffold New DO Project\n\n```bash\nnpm create cloudflare@latest my-durable-app -- \\\n  --template=cloudflare\u002Fdurable-objects-template \\\n  --ts \\\n  --git \\\n  --deploy false\n\ncd my-durable-app\nnpm install\nnpm run dev\n```\n\n**What this creates:**\n- Complete Durable Objects project structure\n- TypeScript configuration\n- wrangler.jsonc with bindings and migrations\n- Example DO class implementation\n- Worker to call the DO\n\n### Option 2: Add to Existing Worker\n\n```bash\ncd my-existing-worker\nnpm install -D @cloudflare\u002Fworkers-types\n```\n\n**Create a Durable Object class** (`src\u002Fcounter.ts`):\n\n```typescript\nimport { DurableObject } from 'cloudflare:workers';\n\nexport class Counter extends DurableObject {\n  async increment(): Promise\u003Cnumber> {\n    \u002F\u002F Get current value from storage (default to 0)\n    let value: number = (await this.ctx.storage.get('value')) || 0;\n\n    \u002F\u002F Increment\n    value += 1;\n\n    \u002F\u002F Save back to storage\n    await this.ctx.storage.put('value', value);\n\n    return value;\n  }\n\n  async get(): Promise\u003Cnumber> {\n    return (await this.ctx.storage.get('value')) || 0;\n  }\n}\n\n\u002F\u002F CRITICAL: Export the class\nexport default Counter;\n```\n\n**Configure wrangler.jsonc:**\n\n```jsonc\n{\n  \"$schema\": \"node_modules\u002Fwrangler\u002Fconfig-schema.json\",\n  \"name\": \"my-worker\",\n  \"main\": \"src\u002Findex.ts\",\n  \"compatibility_date\": \"2025-10-22\",\n\n  \u002F\u002F Durable Objects binding\n  \"durable_objects\": {\n    \"bindings\": [\n      {\n        \"name\": \"COUNTER\",           \u002F\u002F How you access it: env.COUNTER\n        \"class_name\": \"Counter\"      \u002F\u002F MUST match exported class name\n      }\n    ]\n  },\n\n  \u002F\u002F REQUIRED: Migration for new DO class\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",                   \u002F\u002F Unique migration identifier\n      \"new_sqlite_classes\": [        \u002F\u002F Use SQLite backend (recommended)\n        \"Counter\"\n      ]\n    }\n  ]\n}\n```\n\n**Call from Worker** (`src\u002Findex.ts`):\n\n```typescript\nimport { Counter } from '.\u002Fcounter';\n\ninterface Env {\n  COUNTER: DurableObjectNamespace\u003CCounter>;\n}\n\nexport { Counter };\n\nexport default {\n  async fetch(request: Request, env: Env): Promise\u003CResponse> {\n    \u002F\u002F Get Durable Object stub by name\n    const id = env.COUNTER.idFromName('global-counter');\n    const stub = env.COUNTER.get(id);\n\n    \u002F\u002F Call RPC method on the DO\n    const count = await stub.increment();\n\n    return new Response(`Count: ${count}`);\n  },\n};\n```\n\n**Deploy:**\n\n```bash\nnpx wrangler deploy\n```\n\n---\n\n## Durable Object Class Structure\n\n### Base Class Pattern\n\nAll Durable Objects **MUST extend `DurableObject`** from `cloudflare:workers`:\n\n```typescript\nimport { DurableObject } from 'cloudflare:workers';\n\nexport class MyDurableObject extends DurableObject {\n  constructor(ctx: DurableObjectState, env: Env) {\n    super(ctx, env);\n\n    \u002F\u002F Optional: Initialize from storage\n    ctx.blockConcurrencyWhile(async () => {\n      \u002F\u002F Load state before handling requests\n      this.someValue = await ctx.storage.get('someKey') || defaultValue;\n    });\n  }\n\n  \u002F\u002F RPC methods (recommended)\n  async myMethod(): Promise\u003Cstring> {\n    return 'Hello from DO!';\n  }\n\n  \u002F\u002F Optional: HTTP fetch handler\n  async fetch(request: Request): Promise\u003CResponse> {\n    return new Response('Hello from DO fetch!');\n  }\n}\n\n\u002F\u002F CRITICAL: Export the class\nexport default MyDurableObject;\n```\n\n### Constructor Pattern\n\n```typescript\nconstructor(ctx: DurableObjectState, env: Env) {\n  super(ctx, env);  \u002F\u002F REQUIRED\n\n  \u002F\u002F Access to environment bindings\n  this.env = env;\n\n  \u002F\u002F this.ctx provides:\n  \u002F\u002F - this.ctx.storage      (storage API)\n  \u002F\u002F - this.ctx.id           (unique ID)\n  \u002F\u002F - this.ctx.waitUntil()  (background tasks)\n  \u002F\u002F - this.ctx.acceptWebSocket() (WebSocket hibernation)\n}\n```\n\n**CRITICAL Rules:**\n- ✅ **Always call `super(ctx, env)`** first\n- ✅ **Keep constructor minimal** - heavy work blocks hibernation wake-up\n- ✅ **Use `ctx.blockConcurrencyWhile()`** to initialize from storage before requests\n- ❌ **Never use `setTimeout` or `setInterval`** - breaks hibernation (use alarms instead)\n- ❌ **Don't rely only on in-memory state** with WebSockets - persist to storage\n\n### Exporting the Class\n\n```typescript\n\u002F\u002F Export as default (required for Worker to use it)\nexport default MyDurableObject;\n\n\u002F\u002F Also export as named export (for type inference in Worker)\nexport { MyDurableObject };\n```\n\n**In Worker:**\n\n```typescript\n\u002F\u002F Import the class for types\nimport { MyDurableObject } from '.\u002Fmy-durable-object';\n\n\u002F\u002F Export it so Worker can instantiate it\nexport { MyDurableObject };\n\ninterface Env {\n  MY_DO: DurableObjectNamespace\u003CMyDurableObject>;\n}\n```\n\n---\n\n## State API - Persistent Storage\n\nDurable Objects provide **two storage APIs** depending on the backend:\n\n1. **SQL API** (SQLite backend) - **Recommended**\n2. **Key-Value API** (KV or SQLite backend)\n\n### Enable SQLite Backend (Recommended)\n\nIn `wrangler.jsonc` migrations:\n\n```jsonc\n{\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",\n      \"new_sqlite_classes\": [\"MyDurableObject\"]  \u002F\u002F ← Use this for SQLite\n    }\n  ]\n}\n```\n\n**Why SQLite?**\n- ✅ Up to **1GB storage** (vs 128MB for KV backend)\n- ✅ **Atomic operations** (deleteAll is all-or-nothing)\n- ✅ **SQL queries** with transactions\n- ✅ **Point-in-time recovery** (PITR)\n- ✅ Synchronous KV API available too\n\n### SQL API\n\nAccess via `ctx.storage.sql`:\n\n```typescript\nimport { DurableObject } from 'cloudflare:workers';\n\nexport class MyDurableObject extends DurableObject {\n  sql: SqlStorage;\n\n  constructor(ctx: DurableObjectState, env: Env) {\n    super(ctx, env);\n    this.sql = ctx.storage.sql;\n\n    \u002F\u002F Create table on first run\n    this.sql.exec(`\n      CREATE TABLE IF NOT EXISTS messages (\n        id INTEGER PRIMARY KEY AUTOINCREMENT,\n        text TEXT NOT NULL,\n        user TEXT NOT NULL,\n        created_at INTEGER NOT NULL\n      );\n\n      CREATE INDEX IF NOT EXISTS idx_created_at ON messages(created_at);\n    `);\n  }\n\n  async addMessage(text: string, user: string): Promise\u003Cnumber> {\n    \u002F\u002F Insert with exec (returns cursor)\n    const cursor = this.sql.exec(\n      'INSERT INTO messages (text, user, created_at) VALUES (?, ?, ?) RETURNING id',\n      text,\n      user,\n      Date.now()\n    );\n\n    const row = cursor.one\u003C{ id: number }>();\n    return row.id;\n  }\n\n  async getMessages(limit: number = 50): Promise\u003Cany[]> {\n    const cursor = this.sql.exec(\n      'SELECT * FROM messages ORDER BY created_at DESC LIMIT ?',\n      limit\n    );\n\n    \u002F\u002F Convert cursor to array\n    return cursor.toArray();\n  }\n\n  async deleteOldMessages(beforeTimestamp: number): Promise\u003Cvoid> {\n    this.sql.exec(\n      'DELETE FROM messages WHERE created_at \u003C ?',\n      beforeTimestamp\n    );\n  }\n}\n```\n\n**SQL API Methods:**\n\n```typescript\n\u002F\u002F Execute query (returns cursor)\nconst cursor = this.sql.exec('SELECT * FROM table WHERE id = ?', id);\n\n\u002F\u002F Get single row\nconst row = cursor.one\u003CRowType>();\n\n\u002F\u002F Get first row or null\nconst row = cursor.one\u003CRowType>({ allowNone: true });\n\n\u002F\u002F Get all rows as array\nconst rows = cursor.toArray\u003CRowType>();\n\n\u002F\u002F Iterate cursor\nfor (const row of cursor) {\n  \u002F\u002F Process row\n}\n\n\u002F\u002F Transactions (synchronous)\nthis.ctx.storage.transactionSync(() => {\n  this.sql.exec('INSERT INTO table1 ...');\n  this.sql.exec('UPDATE table2 ...');\n  \u002F\u002F All or nothing\n});\n```\n\n**CRITICAL SQL Rules:**\n- ✅ Always use **parameterized queries** with `?` placeholders\n- ✅ Create indexes for frequently queried columns\n- ✅ Use transactions for multi-statement operations\n- ❌ Don't access the hidden `__cf_kv` table (used internally for KV API)\n- ❌ Don't enable SQLite on existing deployed KV-backed DOs (not supported)\n\n### Key-Value API\n\nAvailable on **both SQLite and KV backends** via `ctx.storage`:\n\n```typescript\nimport { DurableObject } from 'cloudflare:workers';\n\nexport class MyDurableObject extends DurableObject {\n  async increment(): Promise\u003Cnumber> {\n    \u002F\u002F Get value\n    let count = await this.ctx.storage.get\u003Cnumber>('count') || 0;\n\n    \u002F\u002F Increment\n    count += 1;\n\n    \u002F\u002F Put value back\n    await this.ctx.storage.put('count', count);\n\n    return count;\n  }\n\n  async batchOperations(): Promise\u003Cvoid> {\n    \u002F\u002F Get multiple keys\n    const map = await this.ctx.storage.get\u003Cnumber>(['key1', 'key2', 'key3']);\n\n    \u002F\u002F Put multiple keys\n    await this.ctx.storage.put({\n      key1: 'value1',\n      key2: 'value2',\n      key3: 'value3',\n    });\n\n    \u002F\u002F Delete key\n    await this.ctx.storage.delete('key1');\n\n    \u002F\u002F Delete multiple keys\n    await this.ctx.storage.delete(['key2', 'key3']);\n  }\n\n  async listKeys(): Promise\u003Cstring[]> {\n    \u002F\u002F List all keys\n    const map = await this.ctx.storage.list();\n    return Array.from(map.keys());\n\n    \u002F\u002F List with prefix\n    const mapWithPrefix = await this.ctx.storage.list({\n      prefix: 'user:',\n      limit: 100,\n    });\n  }\n\n  async deleteAllStorage(): Promise\u003Cvoid> {\n    \u002F\u002F Delete alarm first (if set)\n    await this.ctx.storage.deleteAlarm();\n\n    \u002F\u002F Delete all storage (DO will cease to exist after shutdown)\n    await this.ctx.storage.deleteAll();\n  }\n}\n```\n\n**KV API Methods:**\n\n```typescript\n\u002F\u002F Get single value\nconst value = await this.ctx.storage.get\u003CT>('key');\n\n\u002F\u002F Get multiple values (returns Map)\nconst map = await this.ctx.storage.get\u003CT>(['key1', 'key2']);\n\n\u002F\u002F Put single value\nawait this.ctx.storage.put('key', value);\n\n\u002F\u002F Put multiple values\nawait this.ctx.storage.put({ key1: value1, key2: value2 });\n\n\u002F\u002F Delete single key\nawait this.ctx.storage.delete('key');\n\n\u002F\u002F Delete multiple keys\nawait this.ctx.storage.delete(['key1', 'key2']);\n\n\u002F\u002F List keys\nconst map = await this.ctx.storage.list\u003CT>({\n  prefix: 'user:',\n  limit: 100,\n  reverse: false\n});\n\n\u002F\u002F Delete all (atomic on SQLite, may be partial on KV backend)\nawait this.ctx.storage.deleteAll();\n\n\u002F\u002F Transactions (async)\nawait this.ctx.storage.transaction(async (txn) => {\n  await txn.put('key1', value1);\n  await txn.put('key2', value2);\n  \u002F\u002F All or nothing\n});\n```\n\n**Storage Limits:**\n- **SQLite backend**: Up to **1GB** storage per DO instance\n- **KV backend**: Up to **128MB** storage per DO instance\n\n---\n\n## WebSocket Hibernation API\n\nThe **WebSocket Hibernation API** allows Durable Objects to:\n- Handle **thousands of WebSocket connections** per instance\n- **Hibernate** when idle (no messages, no events) to save costs\n- **Wake up** automatically when messages arrive\n- Maintain connections without incurring duration charges during idle periods\n\n**Use for:** Chat rooms, real-time collaboration, multiplayer games, live updates\n\n### How Hibernation Works\n\n1. **Active state** - DO is in memory, handling messages\n2. **Idle state** - No messages for ~10 seconds, DO can hibernate\n3. **Hibernation** - In-memory state cleared, WebSockets stay connected to Cloudflare edge\n4. **Wake up** - New message arrives → constructor runs → handler method called\n\n**CRITICAL:** In-memory state is **lost on hibernation**. Use `serializeAttachment()` to persist per-WebSocket metadata.\n\n### WebSocket Server Pattern\n\n```typescript\nimport { DurableObject } from 'cloudflare:workers';\n\nexport class ChatRoom extends DurableObject {\n  sessions: Map\u003CWebSocket, { userId: string; username: string }>;\n\n  constructor(ctx: DurableObjectState, env: Env) {\n    super(ctx, env);\n\n    \u002F\u002F Restore WebSocket connections after hibernation\n    this.sessions = new Map();\n\n    ctx.getWebSockets().forEach((ws) => {\n      \u002F\u002F Deserialize attachment (persisted metadata)\n      const attachment = ws.deserializeAttachment();\n      this.sessions.set(ws, attachment);\n    });\n  }\n\n  async fetch(request: Request): Promise\u003CResponse> {\n    \u002F\u002F Expect WebSocket upgrade request\n    const upgradeHeader = request.headers.get('Upgrade');\n    if (upgradeHeader !== 'websocket') {\n      return new Response('Expected websocket', { status: 426 });\n    }\n\n    \u002F\u002F Create WebSocket pair\n    const webSocketPair = new WebSocketPair();\n    const [client, server] = Object.values(webSocketPair);\n\n    \u002F\u002F Get user info from URL or headers\n    const url = new URL(request.url);\n    const userId = url.searchParams.get('userId') || 'anonymous';\n    const username = url.searchParams.get('username') || 'Anonymous';\n\n    \u002F\u002F Accept WebSocket with hibernation\n    \u002F\u002F CRITICAL: Use ctx.acceptWebSocket(), NOT ws.accept()\n    this.ctx.acceptWebSocket(server);\n\n    \u002F\u002F Serialize metadata to persist across hibernation\n    const metadata = { userId, username };\n    server.serializeAttachment(metadata);\n\n    \u002F\u002F Track in-memory (will be restored after hibernation)\n    this.sessions.set(server, metadata);\n\n    \u002F\u002F Notify others\n    this.broadcast(`${username} joined`, server);\n\n    \u002F\u002F Return client WebSocket to browser\n    return new Response(null, {\n      status: 101,\n      webSocket: client,\n    });\n  }\n\n  \u002F\u002F Called when WebSocket receives a message\n  async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise\u003Cvoid> {\n    const session = this.sessions.get(ws);\n\n    if (typeof message === 'string') {\n      const data = JSON.parse(message);\n\n      if (data.type === 'chat') {\n        \u002F\u002F Broadcast to all connections\n        this.broadcast(`${session?.username}: ${data.text}`, ws);\n      }\n    }\n  }\n\n  \u002F\u002F Called when WebSocket closes\n  async webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean): Promise\u003Cvoid> {\n    const session = this.sessions.get(ws);\n    this.sessions.delete(ws);\n\n    \u002F\u002F Close the WebSocket\n    ws.close(code, 'Durable Object closing WebSocket');\n\n    \u002F\u002F Notify others\n    if (session) {\n      this.broadcast(`${session.username} left`);\n    }\n  }\n\n  \u002F\u002F Called on WebSocket errors\n  async webSocketError(ws: WebSocket, error: any): Promise\u003Cvoid> {\n    console.error('WebSocket error:', error);\n    const session = this.sessions.get(ws);\n    this.sessions.delete(ws);\n  }\n\n  \u002F\u002F Helper to broadcast to all connections\n  broadcast(message: string, except?: WebSocket): void {\n    this.sessions.forEach((session, ws) => {\n      if (ws !== except && ws.readyState === WebSocket.OPEN) {\n        ws.send(JSON.stringify({ type: 'message', text: message }));\n      }\n    });\n  }\n}\n```\n\n**WebSocket Handler Methods:**\n\n```typescript\n\u002F\u002F Receive message from client\nasync webSocketMessage(\n  ws: WebSocket,\n  message: string | ArrayBuffer\n): Promise\u003Cvoid> {\n  \u002F\u002F Handle message\n}\n\n\u002F\u002F WebSocket closed by client\nasync webSocketClose(\n  ws: WebSocket,\n  code: number,\n  reason: string,\n  wasClean: boolean\n): Promise\u003Cvoid> {\n  \u002F\u002F Cleanup\n}\n\n\u002F\u002F WebSocket error occurred\nasync webSocketError(\n  ws: WebSocket,\n  error: any\n): Promise\u003Cvoid> {\n  \u002F\u002F Handle error\n}\n```\n\n**Hibernation-Safe Patterns:**\n\n```typescript\n\u002F\u002F ✅ CORRECT: Use ctx.acceptWebSocket (enables hibernation)\nthis.ctx.acceptWebSocket(server);\n\n\u002F\u002F ❌ WRONG: Don't use ws.accept() (standard API, no hibernation)\nserver.accept();\n\n\u002F\u002F ✅ CORRECT: Persist metadata across hibernation\nserver.serializeAttachment({ userId: '123', username: 'Alice' });\n\n\u002F\u002F ✅ CORRECT: Restore metadata in constructor\nconstructor(ctx, env) {\n  super(ctx, env);\n\n  ctx.getWebSockets().forEach((ws) => {\n    const metadata = ws.deserializeAttachment();\n    this.sessions.set(ws, metadata);\n  });\n}\n\n\u002F\u002F ❌ WRONG: Don't use setTimeout\u002FsetInterval (prevents hibernation)\nsetTimeout(() => { \u002F* ... *\u002F }, 1000);  \u002F\u002F ❌ NEVER DO THIS\n\n\u002F\u002F ✅ CORRECT: Use alarms for scheduled tasks\nawait this.ctx.storage.setAlarm(Date.now() + 60000);\n```\n\n**When Hibernation Does NOT Occur:**\n- `setTimeout` or `setInterval` callbacks are pending\n- In-progress `fetch()` request (awaited I\u002FO)\n- Standard WebSocket API is used (not hibernation API)\n- Request\u002Fevent is still being processed\n\n---\n\n## Alarms API - Scheduled Tasks\n\nThe **Alarms API** allows Durable Objects to schedule themselves to wake up at a specific time in the future.\n\n**Use for:** Batching, cleanup jobs, reminders, periodic tasks, delayed operations\n\n### Basic Alarm Pattern\n\n```typescript\nimport { DurableObject } from 'cloudflare:workers';\n\nexport class Batcher extends DurableObject {\n  buffer: string[];\n\n  constructor(ctx: DurableObjectState, env: Env) {\n    super(ctx, env);\n\n    ctx.blockConcurrencyWhile(async () => {\n      \u002F\u002F Restore buffer from storage\n      this.buffer = await ctx.storage.get('buffer') || [];\n    });\n  }\n\n  async addItem(item: string): Promise\u003Cvoid> {\n    this.buffer.push(item);\n    await this.ctx.storage.put('buffer', this.buffer);\n\n    \u002F\u002F Schedule alarm for 10 seconds from now (if not already set)\n    const currentAlarm = await this.ctx.storage.getAlarm();\n    if (currentAlarm === null) {\n      await this.ctx.storage.setAlarm(Date.now() + 10000);\n    }\n  }\n\n  \u002F\u002F Called when alarm fires\n  async alarm(alarmInfo: { retryCount: number; isRetry: boolean }): Promise\u003Cvoid> {\n    console.log(`Alarm fired (retry count: ${alarmInfo.retryCount})`);\n\n    \u002F\u002F Process batch\n    if (this.buffer.length > 0) {\n      await this.processBatch(this.buffer);\n\n      \u002F\u002F Clear buffer\n      this.buffer = [];\n      await this.ctx.storage.put('buffer', []);\n    }\n\n    \u002F\u002F Alarm is automatically deleted after successful execution\n  }\n\n  async processBatch(items: string[]): Promise\u003Cvoid> {\n    \u002F\u002F Send to external API, write to database, etc.\n    console.log(`Processing ${items.length} items:`, items);\n  }\n}\n```\n\n**Alarm API Methods:**\n\n```typescript\n\u002F\u002F Set alarm to fire at specific timestamp\nawait this.ctx.storage.setAlarm(Date.now() + 60000);  \u002F\u002F 60 seconds from now\n\n\u002F\u002F Set alarm to fire at specific date\nawait this.ctx.storage.setAlarm(new Date('2025-12-31T23:59:59Z'));\n\n\u002F\u002F Get current alarm (null if not set)\nconst alarmTime = await this.ctx.storage.getAlarm();\n\n\u002F\u002F Delete alarm\nawait this.ctx.storage.deleteAlarm();\n\n\u002F\u002F Alarm handler (called when alarm fires)\nasync alarm(alarmInfo: { retryCount: number; isRetry: boolean }): Promise\u003Cvoid> {\n  \u002F\u002F Do work\n}\n```\n\n**Alarm Behavior:**\n- ✅ **Guaranteed at-least-once execution** - will retry on failure\n- ✅ **Automatic retries** - up to 6 retries with exponential backoff (starting at 2 seconds)\n- ✅ **Persistent** - survives DO hibernation and eviction\n- ✅ **Automatically deleted** after successful execution\n- ⚠️ **One alarm per DO** - setting a new alarm overwrites the previous one\n\n**Retry Pattern (Idempotent Operations):**\n\n```typescript\nasync alarm(alarmInfo: { retryCount: number; isRetry: boolean }): Promise\u003Cvoid> {\n  if (alarmInfo.retryCount > 3) {\n    console.error('Alarm failed after 3 retries, giving up');\n    return;\n  }\n\n  try {\n    \u002F\u002F Idempotent operation (safe to retry)\n    await this.sendNotification();\n  } catch (error) {\n    console.error('Alarm failed:', error);\n    throw error;  \u002F\u002F Will trigger retry\n  }\n}\n```\n\n---\n\n## RPC vs HTTP Fetch\n\nDurable Objects support **two invocation patterns**:\n\n1. **RPC (Remote Procedure Call)** - Recommended for new projects\n2. **HTTP Fetch** - For HTTP request\u002Fresponse flows or legacy compatibility\n\n### RPC Pattern (Recommended)\n\n**Enable RPC** with compatibility date `>= 2024-04-03`:\n\n```jsonc\n{\n  \"compatibility_date\": \"2025-10-22\"\n}\n```\n\n**Define RPC methods** on DO class:\n\n```typescript\nexport class Counter extends DurableObject {\n  \u002F\u002F Public RPC methods (automatically exposed)\n  async increment(): Promise\u003Cnumber> {\n    let value = await this.ctx.storage.get\u003Cnumber>('count') || 0;\n    value += 1;\n    await this.ctx.storage.put('count', value);\n    return value;\n  }\n\n  async decrement(): Promise\u003Cnumber> {\n    let value = await this.ctx.storage.get\u003Cnumber>('count') || 0;\n    value -= 1;\n    await this.ctx.storage.put('count', value);\n    return value;\n  }\n\n  async get(): Promise\u003Cnumber> {\n    return await this.ctx.storage.get\u003Cnumber>('count') || 0;\n  }\n}\n```\n\n**Call from Worker:**\n\n```typescript\n\u002F\u002F Get stub\nconst id = env.COUNTER.idFromName('my-counter');\nconst stub = env.COUNTER.get(id);\n\n\u002F\u002F Call RPC methods directly\nconst count = await stub.increment();\nconst current = await stub.get();\n```\n\n**RPC Benefits:**\n- ✅ **Type-safe** - TypeScript knows method signatures\n- ✅ **Simple** - Direct method calls, no HTTP ceremony\n- ✅ **Automatic serialization** - Handles structured data\n- ✅ **Exception propagation** - Errors thrown in DO are received in Worker\n\n### HTTP Fetch Pattern\n\n**Define `fetch()` handler** on DO class:\n\n```typescript\nexport class Counter extends DurableObject {\n  async fetch(request: Request): Promise\u003CResponse> {\n    const url = new URL(request.url);\n\n    if (url.pathname === '\u002Fincrement' && request.method === 'POST') {\n      let value = await this.ctx.storage.get\u003Cnumber>('count') || 0;\n      value += 1;\n      await this.ctx.storage.put('count', value);\n      return new Response(JSON.stringify({ count: value }));\n    }\n\n    if (url.pathname === '\u002Fget' && request.method === 'GET') {\n      let value = await this.ctx.storage.get\u003Cnumber>('count') || 0;\n      return new Response(JSON.stringify({ count: value }));\n    }\n\n    return new Response('Not found', { status: 404 });\n  }\n}\n```\n\n**Call from Worker:**\n\n```typescript\n\u002F\u002F Get stub\nconst id = env.COUNTER.idFromName('my-counter');\nconst stub = env.COUNTER.get(id);\n\n\u002F\u002F Call fetch\nconst response = await stub.fetch('https:\u002F\u002Ffake-host\u002Fincrement', {\n  method: 'POST',\n});\n\nconst data = await response.json();\n```\n\n### When to Use Each\n\n| Use Case | Recommendation |\n|----------|----------------|\n| **New project** | ✅ RPC (simpler, type-safe) |\n| **HTTP request\u002Fresponse flow** | HTTP Fetch |\n| **Complex routing logic** | HTTP Fetch |\n| **Type safety important** | ✅ RPC |\n| **Legacy compatibility** | HTTP Fetch |\n| **WebSocket upgrades** | HTTP Fetch (required) |\n\n---\n\n## Creating Durable Object Stubs and Routing\n\nTo interact with a Durable Object from a Worker, you need to:\n1. Get a **Durable Object ID**\n2. Create a **stub** from the ID\n3. Call methods on the stub\n\n### Getting Durable Object IDs\n\n**Three methods to create IDs:**\n\n#### 1. `idFromName(name)` - Named DOs (Most Common)\n\nUse when you want **consistent routing** to the same DO instance based on a name:\n\n```typescript\n\u002F\u002F Same name always routes to same DO instance globally\nconst roomId = env.CHAT_ROOM.idFromName('room-123');\nconst userId = env.USER_SESSION.idFromName('user-alice');\nconst globalCounter = env.COUNTER.idFromName('global');\n```\n\n**Use for:**\n- Chat rooms (name = room ID)\n- User sessions (name = user ID)\n- Per-tenant logic (name = tenant ID)\n- Global singletons (name = 'global')\n\n**Characteristics:**\n- ✅ **Deterministic** - same name = same DO instance\n- ✅ **Easy to reference** - just need the name string\n- ⚠️ **First access latency** - ~100-300ms for global uniqueness check\n- ⚠️ **Cached after first use** - subsequent access is fast\n\n#### 2. `newUniqueId()` - Random IDs\n\nUse when you need a **new, unique DO instance**:\n\n```typescript\n\u002F\u002F Creates a random, globally unique ID\nconst id = env.MY_DO.newUniqueId();\n\n\u002F\u002F With jurisdiction restriction (EU data residency)\nconst euId = env.MY_DO.newUniqueId({ jurisdiction: 'eu' });\n\n\u002F\u002F Store the ID for future use\nconst idString = id.toString();\nawait env.KV.put('session:123', idString);\n```\n\n**Use for:**\n- Creating new sessions\u002Frooms that don't exist yet\n- One-time use DOs\n- When you don't have a natural name\n\n**Characteristics:**\n- ✅ **Lower latency** on first use (no global uniqueness check)\n- ⚠️ **Must store ID** to access same DO later\n- ⚠️ **ID format is opaque** - can't derive meaning from it\n\n#### 3. `idFromString(idString)` - Recreate from Saved ID\n\nUse when you've **previously stored an ID** and need to recreate it:\n\n```typescript\n\u002F\u002F Get stored ID string (from KV, D1, cookie, etc.)\nconst idString = await env.KV.get('session:123');\n\n\u002F\u002F Recreate ID\nconst id = env.MY_DO.idFromString(idString);\n\n\u002F\u002F Get stub\nconst stub = env.MY_DO.get(id);\n```\n\n**Throws exception** if:\n- ID string is invalid\n- ID was not created from the same `DurableObjectNamespace`\n\n### Getting Stubs\n\n#### Method 1: `get(id)` - From ID\n\n```typescript\nconst id = env.MY_DO.idFromName('my-instance');\nconst stub = env.MY_DO.get(id);\n\n\u002F\u002F Call methods\nawait stub.myMethod();\n```\n\n#### Method 2: `getByName(name)` - Shortcut for Named DOs\n\n```typescript\n\u002F\u002F Shortcut that combines idFromName + get\nconst stub = env.MY_DO.getByName('my-instance');\n\n\u002F\u002F Equivalent to:\n\u002F\u002F const id = env.MY_DO.idFromName('my-instance');\n\u002F\u002F const stub = env.MY_DO.get(id);\n\nawait stub.myMethod();\n```\n\n**Recommended** for named DOs (cleaner code).\n\n### Location Hints (Geographic Routing)\n\n**Control WHERE a Durable Object is created** with location hints:\n\n```typescript\n\u002F\u002F Create DO near specific location\nconst id = env.MY_DO.idFromName('user-alice');\nconst stub = env.MY_DO.get(id, { locationHint: 'enam' });  \u002F\u002F Eastern North America\n\n\u002F\u002F Available location hints:\n\u002F\u002F - 'wnam' - Western North America\n\u002F\u002F - 'enam' - Eastern North America\n\u002F\u002F - 'sam'  - South America\n\u002F\u002F - 'weur' - Western Europe\n\u002F\u002F - 'eeur' - Eastern Europe\n\u002F\u002F - 'apac' - Asia-Pacific\n\u002F\u002F - 'oc'   - Oceania\n\u002F\u002F - 'afr'  - Africa\n\u002F\u002F - 'me'   - Middle East\n```\n\n**When to use:**\n- ✅ Create DO near user's location (lower latency)\n- ✅ Data residency requirements (e.g., EU users → weur\u002Feeur)\n\n**Limitations:**\n- ⚠️ **Hints are best-effort** - not guaranteed\n- ⚠️ **Only affects first creation** - subsequent access uses existing location\n- ⚠️ **Cannot move existing DOs** - once created, location is fixed\n\n### Jurisdiction Restriction (Data Residency)\n\n**Enforce strict data location** requirements:\n\n```typescript\n\u002F\u002F Create DO that MUST stay in EU\nconst euId = env.MY_DO.newUniqueId({ jurisdiction: 'eu' });\n\n\u002F\u002F Available jurisdictions:\n\u002F\u002F - 'eu' - European Union\n\u002F\u002F - 'fedramp' - FedRAMP (US government)\n```\n\n**Use for:**\n- Regulatory compliance (GDPR, FedRAMP)\n- Data sovereignty requirements\n\n**CRITICAL:**\n- ✅ **Strictly enforced** - DO will never leave jurisdiction\n- ⚠️ **Cannot combine** jurisdiction with location hints\n- ⚠️ **Higher latency** for users outside jurisdiction\n\n---\n\n## Migrations - Managing DO Classes\n\n**Migrations are REQUIRED** when you:\n- Create a new DO class\n- Rename a DO class\n- Delete a DO class\n- Transfer a DO class to another Worker\n\n**Migration Types:**\n\n### 1. Create New DO Class\n\n```jsonc\n{\n  \"durable_objects\": {\n    \"bindings\": [\n      {\n        \"name\": \"COUNTER\",\n        \"class_name\": \"Counter\"\n      }\n    ]\n  },\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",                    \u002F\u002F Unique identifier for this migration\n      \"new_sqlite_classes\": [         \u002F\u002F SQLite backend (recommended)\n        \"Counter\"\n      ]\n    }\n  ]\n}\n```\n\n**For KV backend (legacy):**\n\n```jsonc\n{\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",\n      \"new_classes\": [\"Counter\"]      \u002F\u002F KV backend (128MB limit)\n    }\n  ]\n}\n```\n\n**CRITICAL:**\n- ✅ Use `new_sqlite_classes` for new DOs (up to 1GB storage)\n- ❌ Cannot enable SQLite on existing deployed KV-backed DOs\n\n### 2. Rename DO Class\n\n```jsonc\n{\n  \"durable_objects\": {\n    \"bindings\": [\n      {\n        \"name\": \"MY_DO\",\n        \"class_name\": \"NewClassName\"    \u002F\u002F New class name\n      }\n    ]\n  },\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",\n      \"new_sqlite_classes\": [\"OldClassName\"]\n    },\n    {\n      \"tag\": \"v2\",                      \u002F\u002F New migration tag\n      \"renamed_classes\": [\n        {\n          \"from\": \"OldClassName\",\n          \"to\": \"NewClassName\"\n        }\n      ]\n    }\n  ]\n}\n```\n\n**What happens:**\n- ✅ Existing DO instances keep their data\n- ✅ Old bindings automatically forward to new class\n- ⚠️ **Must export new class** in Worker code\n\n### 3. Delete DO Class\n\n```jsonc\n{\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",\n      \"new_sqlite_classes\": [\"Counter\"]\n    },\n    {\n      \"tag\": \"v2\",\n      \"deleted_classes\": [\"Counter\"]    \u002F\u002F Mark as deleted\n    }\n  ]\n}\n```\n\n**What happens:**\n- ✅ Existing DO instances are **deleted immediately**\n- ✅ All storage is deleted\n- ⚠️ **Cannot undo** - data is permanently lost\n\n**Before deleting:**\n- Export data if needed\n- Update Workers that reference this DO\n\n### 4. Transfer DO Class to Another Worker\n\n```jsonc\n\u002F\u002F In destination Worker:\n{\n  \"durable_objects\": {\n    \"bindings\": [\n      {\n        \"name\": \"TRANSFERRED_DO\",\n        \"class_name\": \"TransferredClass\"\n      }\n    ]\n  },\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",\n      \"transferred_classes\": [\n        {\n          \"from\": \"OriginalClass\",\n          \"from_script\": \"original-worker\",  \u002F\u002F Source Worker name\n          \"to\": \"TransferredClass\"\n        }\n      ]\n    }\n  ]\n}\n```\n\n**What happens:**\n- ✅ DO instances move to new Worker\n- ✅ All storage is transferred\n- ✅ Old bindings automatically forward\n- ⚠️ **Destination class must be exported**\n\n### Migration Rules\n\n**CRITICAL Migration Gotchas:**\n\n❌ **Migrations are ATOMIC** - cannot gradual deploy\n- All instances migrate at once when you deploy\n- No partial rollout support\n\n❌ **Migration tags must be unique**\n- Cannot reuse tags\n- Tags are append-only\n\n❌ **Cannot enable SQLite on existing KV-backed DOs**\n- Must create new DO class instead\n\n✅ **Code changes don't need migrations**\n- Only schema changes (new\u002Frename\u002Fdelete\u002Ftransfer) need migrations\n- You can deploy code updates freely\n\n✅ **Global uniqueness is per account**\n- DO class names are unique across your entire account\n- Even across different Workers\n\n---\n\n## Common Patterns\n\n### Pattern 1: Rate Limiting (Per-User)\n\n```typescript\nexport class RateLimiter extends DurableObject {\n  async checkLimit(userId: string, limit: number, window: number): Promise\u003Cboolean> {\n    const key = `rate:${userId}`;\n    const now = Date.now();\n\n    \u002F\u002F Get recent requests\n    const requests = await this.ctx.storage.get\u003Cnumber[]>(key) || [];\n\n    \u002F\u002F Remove requests outside window\n    const validRequests = requests.filter(timestamp => now - timestamp \u003C window);\n\n    \u002F\u002F Check limit\n    if (validRequests.length >= limit) {\n      return false;  \u002F\u002F Rate limit exceeded\n    }\n\n    \u002F\u002F Add current request\n    validRequests.push(now);\n    await this.ctx.storage.put(key, validRequests);\n\n    return true;  \u002F\u002F Within limit\n  }\n}\n\n\u002F\u002F Worker usage:\nconst limiter = env.RATE_LIMITER.getByName(userId);\nconst allowed = await limiter.checkLimit(userId, 100, 60000);  \u002F\u002F 100 req\u002Fmin\n\nif (!allowed) {\n  return new Response('Rate limit exceeded', { status: 429 });\n}\n```\n\n### Pattern 2: Session Management\n\n```typescript\nexport class UserSession extends DurableObject {\n  sql: SqlStorage;\n\n  constructor(ctx: DurableObjectState, env: Env) {\n    super(ctx, env);\n    this.sql = ctx.storage.sql;\n\n    this.sql.exec(`\n      CREATE TABLE IF NOT EXISTS session (\n        key TEXT PRIMARY KEY,\n        value TEXT NOT NULL,\n        expires_at INTEGER\n      );\n    `);\n\n    \u002F\u002F Schedule cleanup alarm\n    ctx.blockConcurrencyWhile(async () => {\n      const alarm = await ctx.storage.getAlarm();\n      if (alarm === null) {\n        await ctx.storage.setAlarm(Date.now() + 3600000);  \u002F\u002F 1 hour\n      }\n    });\n  }\n\n  async set(key: string, value: any, ttl?: number): Promise\u003Cvoid> {\n    const expiresAt = ttl ? Date.now() + ttl : null;\n\n    this.sql.exec(\n      'INSERT OR REPLACE INTO session (key, value, expires_at) VALUES (?, ?, ?)',\n      key,\n      JSON.stringify(value),\n      expiresAt\n    );\n  }\n\n  async get(key: string): Promise\u003Cany | null> {\n    const cursor = this.sql.exec(\n      'SELECT value, expires_at FROM session WHERE key = ?',\n      key\n    );\n\n    const row = cursor.one\u003C{ value: string; expires_at: number | null }>({ allowNone: true });\n\n    if (!row) {\n      return null;\n    }\n\n    \u002F\u002F Check expiration\n    if (row.expires_at && row.expires_at \u003C Date.now()) {\n      this.sql.exec('DELETE FROM session WHERE key = ?', key);\n      return null;\n    }\n\n    return JSON.parse(row.value);\n  }\n\n  async alarm(): Promise\u003Cvoid> {\n    \u002F\u002F Cleanup expired sessions\n    this.sql.exec('DELETE FROM session WHERE expires_at \u003C ?', Date.now());\n\n    \u002F\u002F Schedule next cleanup\n    await this.ctx.storage.setAlarm(Date.now() + 3600000);\n  }\n}\n```\n\n### Pattern 3: Leader Election\n\n```typescript\nexport class LeaderElection extends DurableObject {\n  sql: SqlStorage;\n\n  constructor(ctx: DurableObjectState, env: Env) {\n    super(ctx, env);\n    this.sql = ctx.storage.sql;\n\n    this.sql.exec(`\n      CREATE TABLE IF NOT EXISTS leader (\n        id INTEGER PRIMARY KEY CHECK (id = 1),\n        worker_id TEXT NOT NULL,\n        elected_at INTEGER NOT NULL\n      );\n    `);\n  }\n\n  async electLeader(workerId: string): Promise\u003Cboolean> {\n    \u002F\u002F Try to become leader\n    try {\n      this.sql.exec(\n        'INSERT INTO leader (id, worker_id, elected_at) VALUES (1, ?, ?)',\n        workerId,\n        Date.now()\n      );\n      return true;  \u002F\u002F Became leader\n    } catch (error) {\n      return false;  \u002F\u002F Someone else is leader\n    }\n  }\n\n  async getLeader(): Promise\u003Cstring | null> {\n    const cursor = this.sql.exec('SELECT worker_id FROM leader WHERE id = 1');\n    const row = cursor.one\u003C{ worker_id: string }>({ allowNone: true });\n    return row?.worker_id || null;\n  }\n\n  async releaseLeadership(workerId: string): Promise\u003Cvoid> {\n    this.sql.exec('DELETE FROM leader WHERE id = 1 AND worker_id = ?', workerId);\n  }\n}\n```\n\n### Pattern 4: Multi-DO Coordination\n\n```typescript\n\u002F\u002F Coordinator DO\nexport class GameCoordinator extends DurableObject {\n  async createGame(gameId: string, env: Env): Promise\u003Cvoid> {\n    \u002F\u002F Create game room DO\n    const gameRoom = env.GAME_ROOM.getByName(gameId);\n    await gameRoom.initialize();\n\n    \u002F\u002F Track in coordinator\n    await this.ctx.storage.put(`game:${gameId}`, {\n      id: gameId,\n      created: Date.now(),\n    });\n  }\n\n  async listGames(): Promise\u003Cstring[]> {\n    const games = await this.ctx.storage.list({ prefix: 'game:' });\n    return Array.from(games.keys()).map(key => key.replace('game:', ''));\n  }\n}\n\n\u002F\u002F Game room DO\nexport class GameRoom extends DurableObject {\n  async initialize(): Promise\u003Cvoid> {\n    await this.ctx.storage.put('state', {\n      players: [],\n      started: false,\n    });\n  }\n\n  async addPlayer(playerId: string): Promise\u003Cvoid> {\n    const state = await this.ctx.storage.get('state');\n    state.players.push(playerId);\n    await this.ctx.storage.put('state', state);\n  }\n}\n```\n\n---\n\n## Critical Rules\n\n### Always Do\n\n✅ **Export DO class** from Worker\n```typescript\nexport class MyDO extends DurableObject { }\nexport default MyDO;  \u002F\u002F Required\n```\n\n✅ **Call `super(ctx, env)`** in constructor\n```typescript\nconstructor(ctx: DurableObjectState, env: Env) {\n  super(ctx, env);  \u002F\u002F Required first line\n}\n```\n\n✅ **Use `new_sqlite_classes`** for new DOs\n```jsonc\n{ \"tag\": \"v1\", \"new_sqlite_classes\": [\"MyDO\"] }\n```\n\n✅ **Use `ctx.acceptWebSocket()`** for hibernation\n```typescript\nthis.ctx.acceptWebSocket(server);  \u002F\u002F Enables hibernation\n```\n\n✅ **Persist critical state** to storage (not just memory)\n```typescript\nawait this.ctx.storage.put('important', value);\n```\n\n✅ **Use alarms** instead of setTimeout\u002FsetInterval\n```typescript\nawait this.ctx.storage.setAlarm(Date.now() + 60000);\n```\n\n✅ **Use parameterized SQL queries**\n```typescript\nthis.sql.exec('SELECT * FROM table WHERE id = ?', id);\n```\n\n✅ **Minimize constructor work**\n```typescript\nconstructor(ctx, env) {\n  super(ctx, env);\n  \u002F\u002F Minimal initialization only\n  ctx.blockConcurrencyWhile(async () => {\n    \u002F\u002F Load from storage\n  });\n}\n```\n\n### Never Do\n\n❌ **Create DO without migration**\n```jsonc\n\u002F\u002F Missing migrations array = error\n```\n\n❌ **Forget to export DO class**\n```typescript\nclass MyDO extends DurableObject { }\n\u002F\u002F Missing: export default MyDO;\n```\n\n❌ **Use `setTimeout` or `setInterval`**\n```typescript\nsetTimeout(() => {}, 1000);  \u002F\u002F Prevents hibernation\n```\n\n❌ **Rely only on in-memory state** with WebSockets\n```typescript\n\u002F\u002F ❌ WRONG: this.sessions will be lost on hibernation\n\u002F\u002F ✅ CORRECT: Use serializeAttachment()\n```\n\n❌ **Deploy migrations gradually**\n```bash\n# Migrations are atomic - cannot use gradual rollout\n```\n\n❌ **Enable SQLite on existing KV-backed DO**\n```jsonc\n\u002F\u002F Not supported - must create new DO class instead\n```\n\n❌ **Use standard WebSocket API** expecting hibernation\n```typescript\nws.accept();  \u002F\u002F ❌ No hibernation\nthis.ctx.acceptWebSocket(ws);  \u002F\u002F ✅ Hibernation enabled\n```\n\n❌ **Assume location hints are guaranteed**\n```typescript\n\u002F\u002F Location hints are best-effort only\n```\n\n---\n\n## Known Issues Prevention\n\nThis skill prevents **15+ documented issues**:\n\n### Issue #1: Class Not Exported\n**Error**: `\"binding not found\"` or `\"Class X not found\"`\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fget-started\u002F\n**Why It Happens**: DO class not exported from Worker\n**Prevention**:\n```typescript\nexport class MyDO extends DurableObject { }\nexport default MyDO;  \u002F\u002F ← Required\n```\n\n### Issue #2: Missing Migration\n**Error**: `\"migrations required\"` or `\"no migration found for class\"`\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Freference\u002Fdurable-objects-migrations\u002F\n**Why It Happens**: Created DO class without migration entry\n**Prevention**: Always add migration when creating new DO class\n```jsonc\n{\n  \"migrations\": [\n    { \"tag\": \"v1\", \"new_sqlite_classes\": [\"MyDO\"] }\n  ]\n}\n```\n\n### Issue #3: Wrong Migration Type (KV vs SQLite)\n**Error**: Schema errors, storage API mismatch\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fapi\u002Fsqlite-storage-api\u002F\n**Why It Happens**: Used `new_classes` instead of `new_sqlite_classes`\n**Prevention**: Use `new_sqlite_classes` for SQLite backend (recommended)\n\n### Issue #4: Constructor Overhead Blocks Hibernation Wake\n**Error**: Slow hibernation wake-up times\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fbest-practices\u002Faccess-durable-objects-storage\u002F\n**Why It Happens**: Heavy work in constructor\n**Prevention**: Minimize constructor, use `blockConcurrencyWhile()`\n```typescript\nconstructor(ctx, env) {\n  super(ctx, env);\n  ctx.blockConcurrencyWhile(async () => {\n    \u002F\u002F Load from storage\n  });\n}\n```\n\n### Issue #5: setTimeout Breaks Hibernation\n**Error**: DO never hibernates, high duration charges\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fconcepts\u002Fdurable-object-lifecycle\u002F\n**Why It Happens**: `setTimeout`\u002F`setInterval` prevents hibernation\n**Prevention**: Use alarms API instead\n```typescript\n\u002F\u002F ❌ WRONG\nsetTimeout(() => {}, 1000);\n\n\u002F\u002F ✅ CORRECT\nawait this.ctx.storage.setAlarm(Date.now() + 1000);\n```\n\n### Issue #6: In-Memory State Lost on Hibernation\n**Error**: WebSocket metadata lost, state reset unexpectedly\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fbest-practices\u002Fwebsockets\u002F\n**Why It Happens**: Relied on in-memory state that's cleared on hibernation\n**Prevention**: Use `serializeAttachment()` for WebSocket metadata\n```typescript\nws.serializeAttachment({ userId, username });\n\n\u002F\u002F Restore in constructor\nctx.getWebSockets().forEach(ws => {\n  const metadata = ws.deserializeAttachment();\n  this.sessions.set(ws, metadata);\n});\n```\n\n### Issue #7: Outgoing WebSocket Cannot Hibernate\n**Error**: High charges despite hibernation API\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fbest-practices\u002Fwebsockets\u002F\n**Why It Happens**: Outgoing WebSockets don't support hibernation\n**Prevention**: Only use hibernation for server-side (incoming) WebSockets\n\n### Issue #8: Global Uniqueness Confusion\n**Error**: Unexpected DO class name conflicts\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fplatform\u002Fknown-issues\u002F#global-uniqueness\n**Why It Happens**: DO class names are globally unique per account\n**Prevention**: Understand DO class names are shared across all Workers in account\n\n### Issue #9: Partial deleteAll on KV Backend\n**Error**: Storage not fully deleted, billing continues\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fapi\u002Flegacy-kv-storage-api\u002F\n**Why It Happens**: KV backend `deleteAll()` can fail partially\n**Prevention**: Use SQLite backend for atomic deleteAll\n\n### Issue #10: Binding Name Mismatch\n**Error**: Runtime error accessing DO binding\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fget-started\u002F\n**Why It Happens**: Binding name in wrangler.jsonc doesn't match code\n**Prevention**: Ensure consistency\n```jsonc\n{ \"bindings\": [{ \"name\": \"MY_DO\", \"class_name\": \"MyDO\" }] }\n```\n```typescript\nenv.MY_DO.getByName('instance');  \u002F\u002F Must match binding name\n```\n\n### Issue #11: State Size Exceeded\n**Error**: `\"state limit exceeded\"` or storage errors\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fplatform\u002Fpricing\u002F\n**Why It Happens**: Exceeded 1GB (SQLite) or 128MB (KV) limit\n**Prevention**: Monitor storage size, implement cleanup with alarms\n\n### Issue #12: Migration Not Atomic\n**Error**: Gradual deployment blocked\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkers\u002Fconfiguration\u002Fversions-and-deployments\u002Fgradual-deployments\u002F\n**Why It Happens**: Tried to use gradual rollout with migrations\n**Prevention**: Migrations deploy atomically across all instances\n\n### Issue #13: Location Hint Ignored\n**Error**: DO created in wrong region\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Freference\u002Fdata-location\u002F\n**Why It Happens**: Location hints are best-effort, not guaranteed\n**Prevention**: Use jurisdiction for strict requirements\n\n### Issue #14: Alarm Retry Failures\n**Error**: Tasks lost after alarm failures\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fapi\u002Falarms\u002F\n**Why It Happens**: Alarm handler throws errors repeatedly\n**Prevention**: Implement idempotent alarm handlers\n```typescript\nasync alarm(info: { retryCount: number }): Promise\u003Cvoid> {\n  if (info.retryCount > 3) {\n    console.error('Giving up after 3 retries');\n    return;\n  }\n  \u002F\u002F Idempotent operation\n}\n```\n\n### Issue #15: Fetch Blocks Hibernation\n**Error**: DO never hibernates despite using hibernation API\n**Source**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fconcepts\u002Fdurable-object-lifecycle\u002F\n**Why It Happens**: In-progress `fetch()` requests prevent hibernation\n**Prevention**: Ensure all async I\u002FO completes before idle period\n\n---\n\n## Configuration Reference\n\n### Complete wrangler.jsonc Example\n\n```jsonc\n{\n  \"$schema\": \"node_modules\u002Fwrangler\u002Fconfig-schema.json\",\n  \"name\": \"my-worker\",\n  \"main\": \"src\u002Findex.ts\",\n  \"compatibility_date\": \"2025-10-22\",\n\n  \u002F\u002F Durable Objects configuration\n  \"durable_objects\": {\n    \"bindings\": [\n      {\n        \"name\": \"COUNTER\",              \u002F\u002F Binding name (use as env.COUNTER)\n        \"class_name\": \"Counter\"         \u002F\u002F Must match exported class\n      },\n      {\n        \"name\": \"CHAT_ROOM\",\n        \"class_name\": \"ChatRoom\"\n      }\n    ]\n  },\n\n  \u002F\u002F Migrations (required for all DO changes)\n  \"migrations\": [\n    {\n      \"tag\": \"v1\",                      \u002F\u002F Initial migration\n      \"new_sqlite_classes\": [\n        \"Counter\",\n        \"ChatRoom\"\n      ]\n    },\n    {\n      \"tag\": \"v2\",                      \u002F\u002F Rename example\n      \"renamed_classes\": [\n        {\n          \"from\": \"Counter\",\n          \"to\": \"CounterV2\"\n        }\n      ]\n    }\n  ]\n}\n```\n\n---\n\n## TypeScript Types\n\n```typescript\nimport { DurableObject, DurableObjectState, DurableObjectNamespace } from 'cloudflare:workers';\n\n\u002F\u002F Environment bindings\ninterface Env {\n  MY_DO: DurableObjectNamespace\u003CMyDurableObject>;\n  DB: D1Database;\n  \u002F\u002F ... other bindings\n}\n\n\u002F\u002F Durable Object class\nexport class MyDurableObject extends DurableObject\u003CEnv> {\n  sql: SqlStorage;\n\n  constructor(ctx: DurableObjectState, env: Env) {\n    super(ctx, env);\n    this.sql = ctx.storage.sql;\n  }\n\n  async myMethod(): Promise\u003Cstring> {\n    \u002F\u002F Access env bindings\n    await this.env.DB.prepare('...').run();\n    return 'Hello';\n  }\n}\n```\n\n---\n\n## Official Documentation\n\n- **Durable Objects**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002F\n- **State API (SQL)**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fapi\u002Fsqlite-storage-api\u002F\n- **WebSocket Hibernation**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fbest-practices\u002Fwebsockets\u002F\n- **Alarms API**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fapi\u002Falarms\u002F\n- **Migrations**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Freference\u002Fdurable-objects-migrations\u002F\n- **Best Practices**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fbest-practices\u002F\n- **Pricing**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002Fplatform\u002Fpricing\u002F\n\n---\n\n**Questions? Issues?**\n\n1. Check `references\u002Ftop-errors.md` for common problems\n2. Review `templates\u002F` for working examples\n3. Consult official docs: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fdurable-objects\u002F\n4. Verify migrations configuration carefully\n",{"name":5,"license":14,"description":23},"Comprehensive guide for Cloudflare Durable Objects - globally unique, stateful objects for coordination, real-time communication, and persistent state management.\n\nUse when: building real-time applications, creating WebSocket servers with hibernation, implementing chat rooms or multiplayer games, coordinating between multiple clients, managing per-user or per-room state, implementing rate limiting or session management, scheduling tasks with alarms, building queues or workflows, or encountering \"do class export\", \"new_sqlite_classes\", \"migrations required\", \"websocket hibernation\", \"alarm api error\", or \"global uniqueness\" errors.\n\nPrevents 15+ documented issues: class not exported, missing migrations, wrong migration type, constructor overhead blocking hibernation, setTimeout breaking hibernation, in-memory state lost on hibernation, outgoing WebSocket not hibernating, global uniqueness confusion, partial deleteAll on KV backend, binding name mismatches, state size limits exceeded, non-atomic migrations, location hints misunderstood, alarm retry failures, and fetch calls blocking hibernation.\n\nKeywords: durable objects, cloudflare do, DurableObject class, do bindings, websocket hibernation, do state api, ctx.storage.sql, ctx.acceptWebSocket, webSocketMessage, alarm() handler, storage.setAlarm, idFromName, newUniqueId, getByName, DurableObjectStub, serializeAttachment, real-time cloudflare, multiplayer cloudflare, chat room workers, coordination cloudflare, stateful workers, new_sqlite_classes, do migrations, location hints, RPC methods, blockConcurrencyWhile, \"do class export\", \"new_sqlite_classes\", \"migrations required\", \"websocket hibernation\", \"alarm api error\", \"global uniqueness\", \"binding not found\"\n","main","45d5ac830c3e238eeba6d0b4e6fd7cf6b56bf380","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn","2026-09-09 16:05:56",{"source":8,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add davidanthonyn\u002Fclaude-skills --skill cloudflare-durable-objects",{"tool":35,"command":36},"bunx","bunx skills add davidanthonyn\u002Fclaude-skills --skill cloudflare-durable-objects",{"tool":38,"command":39},"pnpm","pnpm dlx skills add davidanthonyn\u002Fclaude-skills --skill cloudflare-durable-objects","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fcloudflare-durable-objects\u002FSKILL.md",true,[43,49,53],{"path":44,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":47,"sourceHtmlUrl":48},"README.md","REFERENCE","参考文档",8680,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fcloudflare-durable-objects\u002FREADME.md",{"path":50,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":51,"sourceHtmlUrl":52},"SKILL.json",51378,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fcloudflare-durable-objects\u002FSKILL.json",{"path":54,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":57,"sourceHtmlUrl":58},"SKILL.md.backup","OTHER","其他",47335,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fcloudflare-durable-objects\u002FSKILL.md.backup",[60,67,75,82,89,98],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":18},"01M7AQPHJF528A4MD52YZEZV3R","zustand-state-management","Production-tested setup for Zustand state management in React applications with TypeScript.\nThis skill provides comprehensive patterns for building scalable, type-safe global state.\n\nUse when: setting up global state in React, migrating from Redux or Context API, implementing\nstate persistence with localStorage, configuring TypeScript with Zustand, using slices pattern\nfor modular stores, adding devtools middleware for debugging, handling Next.js SSR hydration,\nor encountering hydration errors, TypeScript inference issues, or persist middleware problems.\n\nPrevents 5 documented issues: Next.js hydration mismatches, TypeScript double parentheses\nsyntax errors, persist middleware export errors, infinite render loops, and slices pattern\ntype inference failures.\n\nKeywords: zustand, state management, React state, TypeScript state, persist middleware,\ndevtools, slices pattern, global state, React hooks, create store, useBoundStore,\nStateCreator, hydration error, text content mismatch, infinite render, localStorage,\nsessionStorage, immer middleware, shallow equality, selector pattern, zustand v5","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fzustand-state-management\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":71,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":18},"01M7AQP2XJRPNYEH323GJ81NN5","zetic-mlange","Help users integrate the ZETIC Melange (MLange) on-device AI SDK into Android (Kotlin\u002FJava) and iOS (Swift) mobile apps. Use this skill whenever the user mentions Zetic, MLange, Melange, ZeticMLangeModel, ZeticMLangeLLMModel, ZeticMLangeHFModel, on-device NPU inference for mobile, or deploying ML models to Android\u002FiOS with NPU acceleration. Also trigger when users ask about running LLMs on-device with GGUF quantization, mobile NPU model deployment, or converting PyTorch\u002FONNX models for mobile inference. Covers general model inference, LLM inference (streaming token generation), and HuggingFace model loading.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fzetic-mlange\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fzetic-mlange\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":18},"01M7AQNEJHD27NNF5PYQDSW8B9","youtube-downloader","Download videos, audio, playlists, and channels from YouTube and 1000+ websites using yt-dlp. Supports quality selection, format conversion, subtitle download, playlist filtering, metadata extraction, thumbnail download, and batch operations. Use when downloading YouTube videos in any quality (4K, 8K, HDR), extracting audio as MP3\u002FM4A\u002FFLAC, downloading entire playlists\u002Fchannels, getting subtitles in multiple languages, converting to specific formats, downloading live streams, archiving content, or batch processing multiple URLs. Optimized for reliability with automatic retries, rate limiting, and error handling.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fyoutube-downloader\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":18},"01M7AQJQSD2H04EE2EPNAQ8A3M","wordpress-plugin-core","This skill provides comprehensive knowledge for WordPress plugin development, covering core patterns, security best practices, database interactions, hooks\u002Ffilters, Settings API, custom post types, REST API, and AJAX. This skill should be used when creating WordPress plugins, troubleshooting security issues, implementing custom post types\u002Ftaxonomies, building admin interfaces, or working with the WordPress database.\n\nUse when: Creating new WordPress plugins, implementing nonces\u002Fsanitization\u002Fescaping, working with $wpdb and prepared statements, building Settings API pages, registering custom post types or taxonomies, implementing REST API endpoints, handling AJAX requests, debugging plugin activation\u002Fdeactivation issues, preventing SQL injection\u002FXSS\u002FCSRF vulnerabilities.\n\nKeywords: wordpress plugin development, wordpress security, wordpress hooks, wordpress filters, wordpress database, wpdb prepare, sanitize_text_field, esc_html, wp_nonce, custom post type, register_post_type, settings api, rest api, admin-ajax, wordpress sql injection, wordpress xss, wordpress csrf, plugin header, activation hook, deactivation hook, wordpress coding standards, wordpress plugin architecture","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fwordpress-plugin-core\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":93,"licenseFileUrl":94,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":18},"01M7AQJ91T970QCFMN9R1EHZXV","webapp-testing","Test local web applications with Playwright. Use when asked to verify frontend functionality, debug UI behavior, capture browser screenshots, or inspect browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":18},"01M7AQJ5E89MS8C5K3GZTY4B48","web-performance-audit","Audit web performance using Chrome DevTools MCP. Use when asked to audit, profile, debug, or optimize page load performance, Lighthouse scores, or site speed.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fweb-performance-audit\u002FSKILL.md",[],[]]