{"_id":"@ainative/ai-kit-nextjs","_rev":"5-39b7e792decf002d4d9e4ab40be78de4","name":"@ainative/ai-kit-nextjs","dist-tags":{"alpha":"0.1.0-alpha.0","latest":"0.1.0-alpha.4"},"versions":{"0.1.0-alpha.0":{"name":"@ainative/ai-kit-nextjs","version":"0.1.0-alpha.0","keywords":["ainative","ai","llm","typescript","ai-agents","ai-primitives","ainative-developer","claude","claude-code","openai","anthropic","nextjs","react","framework","ssr","app-router","server-components"],"author":{"name":"AINative Studio"},"license":"MIT","_id":"@ainative/ai-kit-nextjs@0.1.0-alpha.0","maintainers":[{"name":"ainative-studio","email":"toby@rely.ventures"}],"homepage":"https://github.com/AINative-Studio/ai-kit#readme","bugs":{"url":"https://github.com/AINative-Studio/ai-kit/issues"},"dist":{"shasum":"6a8655471f3984f9c1b710b5e75b8eccbaa5ffa5","tarball":"https://registry.npmjs.org/@ainative/ai-kit-nextjs/-/ai-kit-nextjs-0.1.0-alpha.0.tgz","fileCount":9,"integrity":"sha512-nFfeP+HG29jWlcKwttYiwwcU/7m9TamI3xaDRUQuCFfh0lJq3RY9a398L6Qtzghb3lpC4AvoF8gQDit9bvtlAA==","signatures":[{"sig":"MEQCICjs9LCO9AP9icrouEgWSNi3IJPzR9Md2+XdF0o3JLhvAiACW7VOa3JXId26/wEKdwgd37dcNLxgK5EA8u6UUunjZg==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":120548},"main":"./dist/index.js","types":"./dist/index.d.ts","module":"./dist/index.mjs","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","require":"./dist/index.js"},"./middleware":{"types":"./dist/middleware/index.d.ts","import":"./dist/middleware/index.mjs","require":"./dist/middleware/index.js"}},"gitHead":"fc76d30b210657f175234126d6c0edbaa71d4140","scripts":{"dev":"tsup --watch","lint":"eslint src","test":"vitest","build":"tsup","clean":"rm -rf dist","type-check":"tsc --noEmit","test:coverage":"vitest --coverage"},"_npmUser":{"name":"ainative-studio","email":"toby@rely.ventures"},"repository":{"url":"git+https://github.com/AINative-Studio/ai-kit.git","type":"git","directory":"packages/nextjs"},"_npmVersion":"10.9.4","description":"AI Kit - Next.js utilities and helpers for AI-powered applications","directories":{},"_nodeVersion":"22.21.0","dependencies":{"@ainative/ai-kit-core":"workspace:*"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"next":"^14.0.0","tsup":"^8.0.1","vitest":"^1.0.0","typescript":"^5.3.0","@types/node":"^20.10.0","@vitest/coverage-v8":"^1.0.0"},"peerDependencies":{"next":"^13.0.0 || ^14.0.0 || ^15.0.0","react":"^18.0.0"},"_npmOperationalInternal":{"tmp":"tmp/ai-kit-nextjs_0.1.0-alpha.0_1763692606355_0.30450705370477804","host":"s3://npm-registry-packages-npm-production"}},"0.1.0-alpha.1":{"name":"@ainative/ai-kit-nextjs","version":"0.1.0-alpha.1","keywords":["ainative","ai","llm","typescript","ai-agents","ai-primitives","ainative-developer","claude","claude-code","openai","anthropic","nextjs","react","framework","ssr","app-router","server-components"],"author":{"name":"AINative Studio"},"license":"MIT","_id":"@ainative/ai-kit-nextjs@0.1.0-alpha.1","maintainers":[{"name":"ainative-studio","email":"toby@rely.ventures"}],"homepage":"https://github.com/AINative-Studio/ai-kit#readme","bugs":{"url":"https://github.com/AINative-Studio/ai-kit/issues"},"dist":{"shasum":"3ec5da7b7f5023302cd76b22b917ffab1ceba9c7","tarball":"https://registry.npmjs.org/@ainative/ai-kit-nextjs/-/ai-kit-nextjs-0.1.0-alpha.1.tgz","fileCount":9,"integrity":"sha512-rmCMoFEZ068nzenz+5I1hmmkhpaid7Chuj86bQrdrNYwNdYGrkMJvFhrIAvX+xKRk8KD9ge7PbR4pmY7u4j3XQ==","signatures":[{"sig":"MEUCIQCOd6LwkjL2pJdfytNTzK/Rk14Au6UpzDm/2bXyIJbY2QIgZyqRmlR3BsYhgSkVZg0UKW48R2jmjwcSAn919jA5ruM=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":120545},"main":"./dist/index.js","types":"./dist/index.d.ts","module":"./dist/index.mjs","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","require":"./dist/index.js"},"./middleware":{"types":"./dist/middleware/index.d.ts","import":"./dist/middleware/index.mjs","require":"./dist/middleware/index.js"}},"gitHead":"dc8dc4a4951e8951a407b2c28d26fcda12bf373d","scripts":{"dev":"tsup --watch","lint":"eslint src","test":"vitest","build":"tsup","clean":"rm -rf dist","type-check":"tsc --noEmit","test:coverage":"vitest --coverage"},"_npmUser":{"name":"ainative-studio","email":"toby@rely.ventures"},"repository":{"url":"git+https://github.com/AINative-Studio/ai-kit.git","type":"git","directory":"packages/nextjs"},"_npmVersion":"10.9.4","description":"AI Kit - Next.js utilities and helpers for AI-powered applications","directories":{},"_nodeVersion":"22.21.0","dependencies":{"@ainative/ai-kit-core":"^0.1.2"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"next":"^14.0.0","tsup":"^8.0.1","vitest":"^1.0.0","typescript":"^5.3.0","@types/node":"^20.10.0","@vitest/coverage-v8":"^1.0.0"},"peerDependencies":{"next":"^13.0.0 || ^14.0.0 || ^15.0.0","react":"^18.0.0"},"_npmOperationalInternal":{"tmp":"tmp/ai-kit-nextjs_0.1.0-alpha.1_1763767418533_0.05066717200380677","host":"s3://npm-registry-packages-npm-production"}},"0.1.0-alpha.2":{"name":"@ainative/ai-kit-nextjs","version":"0.1.0-alpha.2","keywords":["ainative","ai","llm","typescript","ai-agents","ai-primitives","ainative-developer","claude","claude-code","openai","anthropic","nextjs","react","framework","ssr","app-router","server-components"],"author":{"name":"AINative Studio"},"license":"MIT","_id":"@ainative/ai-kit-nextjs@0.1.0-alpha.2","maintainers":[{"name":"ainative-studio","email":"toby@rely.ventures"}],"homepage":"https://github.com/AINative-Studio/ai-kit#readme","bugs":{"url":"https://github.com/AINative-Studio/ai-kit/issues"},"dist":{"shasum":"b548f41ea56e950e974906635647f3dd5fee2ce0","tarball":"https://registry.npmjs.org/@ainative/ai-kit-nextjs/-/ai-kit-nextjs-0.1.0-alpha.2.tgz","fileCount":9,"integrity":"sha512-krZFqVu/KX/2VS83lZaWTNDgfTsKgzRaAZ5Sj3/Ntxgp8gxrB5iI7IZwHx2yA9N5TTuVUVZzKNf2ciCZeNDZfQ==","signatures":[{"sig":"MEUCIQD18Qu1WH9m+12vqhzCWRALk42PPDR4cVNUPcQ+a4LRBAIgCgvHmNI0lVM6E0Brf3xUsKFEMdGacMGnUrVVEorwjoc=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":120551},"main":"./dist/index.js","types":"./dist/index.d.ts","module":"./dist/index.mjs","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","require":"./dist/index.js"},"./middleware":{"types":"./dist/middleware/index.d.ts","import":"./dist/middleware/index.mjs","require":"./dist/middleware/index.js"}},"gitHead":"dc8dc4a4951e8951a407b2c28d26fcda12bf373d","scripts":{"dev":"tsup --watch","lint":"eslint src","test":"vitest","build":"tsup","clean":"rm -rf dist","type-check":"tsc --noEmit","test:coverage":"vitest --coverage"},"_npmUser":{"name":"ainative-studio","email":"toby@rely.ventures"},"repository":{"url":"git+https://github.com/AINative-Studio/ai-kit.git","type":"git","directory":"packages/nextjs"},"_npmVersion":"10.9.4","description":"AI Kit - Next.js utilities and helpers for AI-powered applications","directories":{},"_nodeVersion":"22.21.0","dependencies":{"@ainative-studio/aikit-core":"^0.1.3"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"next":"^14.0.0","tsup":"^8.0.1","vitest":"^1.0.0","typescript":"^5.3.0","@types/node":"^20.10.0","@vitest/coverage-v8":"^1.0.0"},"peerDependencies":{"next":"^13.0.0 || ^14.0.0 || ^15.0.0","react":"^18.0.0"},"_npmOperationalInternal":{"tmp":"tmp/ai-kit-nextjs_0.1.0-alpha.2_1763779321195_0.12140129198602567","host":"s3://npm-registry-packages-npm-production"}},"0.1.0-alpha.3":{"name":"@ainative/ai-kit-nextjs","version":"0.1.0-alpha.3","keywords":["ainative","ai","llm","typescript","ai-agents","ai-primitives","ainative-developer","claude","claude-code","openai","anthropic","nextjs","react","framework","ssr","app-router","server-components"],"author":{"name":"AINative Studio"},"license":"MIT","_id":"@ainative/ai-kit-nextjs@0.1.0-alpha.3","maintainers":[{"name":"ainative-studio","email":"toby@rely.ventures"}],"homepage":"https://ainative.studio/ai-kit","bugs":{"url":"https://github.com/AINative-Studio/ai-kit/issues"},"dist":{"shasum":"b86a8145a22f105eff8ecec2cbeb611d95b46fa7","tarball":"https://registry.npmjs.org/@ainative/ai-kit-nextjs/-/ai-kit-nextjs-0.1.0-alpha.3.tgz","fileCount":9,"integrity":"sha512-bsgoLF6eumEZOF+0Gowr08mM5w/y9l76rgPivXc0XX73Ta5vSlbeNfkV8rBIV5ZNs7EHmLdlByidDo1U2Y6tMw==","signatures":[{"sig":"MEYCIQCXJJYlpzGiPbo2+EGzxVGJ3Uy4vHsTW5q7/b5phGoRLgIhAI+KrViapcVfBsezfJUwa6JHUiYRzweVlcDwpv66Dd48","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":120551},"main":"./dist/index.js","types":"./dist/index.d.ts","module":"./dist/index.mjs","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","require":"./dist/index.js"},"./middleware":{"types":"./dist/middleware/index.d.ts","import":"./dist/middleware/index.mjs","require":"./dist/middleware/index.js"}},"gitHead":"d6b72c3dc5155c1f9ed5cf03652ec41ab173eeda","scripts":{"dev":"tsup --watch","lint":"eslint src","test":"vitest run","build":"tsup","clean":"rm -rf dist","type-check":"tsc --noEmit","test:coverage":"vitest --coverage"},"_npmUser":{"name":"ainative-studio","email":"toby@rely.ventures"},"repository":{"url":"git+https://github.com/AINative-Studio/ai-kit.git","type":"git","directory":"packages/nextjs"},"_npmVersion":"10.9.4","description":"AI Kit - Next.js utilities and helpers for AI-powered applications","directories":{},"_nodeVersion":"22.21.0","dependencies":{"@ainative/ai-kit-core":"workspace:*"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"next":"^14.0.0","tsup":"^8.0.1","vitest":"^1.0.0","typescript":"^5.3.0","@types/node":"^20.10.0","@vitest/coverage-v8":"^1.0.0"},"peerDependencies":{"next":"^13.0.0 || ^14.0.0 || ^15.0.0","react":"^18.0.0 || ^19.0.0"},"_npmOperationalInternal":{"tmp":"tmp/ai-kit-nextjs_0.1.0-alpha.3_1765567498203_0.8226594102471556","host":"s3://npm-registry-packages-npm-production"}},"0.1.0-alpha.4":{"name":"@ainative/ai-kit-nextjs","version":"0.1.0-alpha.4","description":"AI Kit - Next.js utilities and helpers for AI-powered applications","main":"./dist/index.js","module":"./dist/index.mjs","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","require":"./dist/index.js"},"./middleware":{"types":"./dist/middleware/index.d.ts","import":"./dist/middleware/index.mjs","require":"./dist/middleware/index.js"}},"scripts":{"build":"tsup","dev":"tsup --watch","test":"vitest run","test:coverage":"vitest --coverage","type-check":"tsc --noEmit","lint":"eslint src","clean":"rm -rf dist","prepublishOnly":"tsx ../../scripts/check-no-workspace-protocol.ts"},"keywords":["ainative","ai","llm","typescript","ai-agents","ai-primitives","ainative-developer","claude","claude-code","openai","anthropic","nextjs","react","framework","ssr","app-router","server-components"],"author":{"name":"AINative Studio"},"license":"MIT","homepage":"https://ainative.studio/ai-kit","repository":{"type":"git","url":"git+https://github.com/AINative-Studio/ai-kit.git","directory":"packages/nextjs"},"bugs":{"url":"https://github.com/AINative-Studio/ai-kit/issues"},"peerDependencies":{"next":"^13.0.0 || ^14.0.0 || ^15.0.0 || ^16.0.0","react":"^18.0.0 || ^19.0.0"},"dependencies":{"@ainative/ai-kit-core":"0.2.0"},"devDependencies":{"@types/node":"^20.10.0","@vitest/coverage-v8":"^4.0.18","next":"^16.1.6","tsup":"^8.0.1","typescript":"^5.3.0","vitest":"^4.0.18"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"engines":{"node":">=18.0.0","npm":">=8.0.0"},"_id":"@ainative/ai-kit-nextjs@0.1.0-alpha.4","gitHead":"669962f093747eaa3f6013c614fdba2f0e5be431","_nodeVersion":"22.21.0","_npmVersion":"10.9.4","dist":{"integrity":"sha512-U2lBTbouYD/mPekwuWOB2qDUhpKzyGTYOeUshZ1ASB2T1ufGHZEATJVTCWn/CSXEy44cRQLErORvzIgykWrVMw==","shasum":"ab2ba302083def448907e106077ec604f8ef5192","tarball":"https://registry.npmjs.org/@ainative/ai-kit-nextjs/-/ai-kit-nextjs-0.1.0-alpha.4.tgz","fileCount":7,"unpackedSize":103802,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIGc4CraN2Wbfbn1qhQvncirzdSVDyIafknsGORrrXOpQAiEA0CWl949U9OgcbAv3SRb9Da6jOymXebqBEbyXCX0g+dY="}]},"_npmUser":{"name":"ainative-studio","email":"toby@rely.ventures"},"directories":{},"maintainers":[{"name":"ainative-studio","email":"toby@rely.ventures"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/ai-kit-nextjs_0.1.0-alpha.4_1789350194410_0.27289057952061646"},"_hasShrinkwrap":false}},"time":{"created":"2025-11-21T02:36:46.248Z","modified":"2026-09-14T01:43:14.713Z","0.1.0-alpha.0":"2025-11-21T02:36:46.551Z","0.1.0-alpha.1":"2025-11-21T23:23:38.733Z","0.1.0-alpha.2":"2025-11-22T02:42:01.419Z","0.1.0-alpha.3":"2025-12-12T19:24:58.340Z","0.1.0-alpha.4":"2026-09-14T01:43:14.546Z"},"bugs":{"url":"https://github.com/AINative-Studio/ai-kit/issues"},"author":{"name":"AINative Studio"},"license":"MIT","homepage":"https://ainative.studio/ai-kit","keywords":["ainative","ai","llm","typescript","ai-agents","ai-primitives","ainative-developer","claude","claude-code","openai","anthropic","nextjs","react","framework","ssr","app-router","server-components"],"repository":{"type":"git","url":"git+https://github.com/AINative-Studio/ai-kit.git","directory":"packages/nextjs"},"description":"AI Kit - Next.js utilities and helpers for AI-powered applications","maintainers":[{"name":"ainative-studio","email":"toby@rely.ventures"}],"readme":"# @ainative/ai-kit-nextjs\n\n> Next.js route helpers for building AI-powered streaming APIs\n\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![TypeScript](https://img.shields.io/badge/TypeScript-5.3-blue)](https://www.typescriptlang.org/)\n[![Next.js](https://img.shields.io/badge/Next.js-13%20%7C%2014%20%7C%2015%20%7C%2016-black)](https://nextjs.org/)\n\nNext.js-specific utilities for AI Kit, providing powerful route helpers for both **App Router** (Next.js 13+) and **Pages Router** with built-in support for:\n\n- ✅ Server-Sent Events (SSE) streaming\n- ✅ CORS configuration\n- ✅ Request validation\n- ✅ Error handling\n- ✅ Edge runtime compatibility\n- ✅ TypeScript type safety\n- ✅ Heartbeat support for long connections\n\n---\n\n## Version Compatibility\n\n| Next.js Version | Support Status | Tested |\n|----------------|----------------|--------|\n| 16.x           | Full Support   | Yes    |\n| 15.x           | Full Support   | Yes    |\n| 14.x           | Full Support   | Yes    |\n| 13.x           | Full Support   | Yes    |\n\n**Requirements:**\n- Next.js: ^13.0.0 || ^14.0.0 || ^15.0.0 || ^16.0.0\n- React: ^18.0.0 || ^19.0.0\n- Node.js: >=18.0.0 (>=20.9.0 recommended for Next.js 16+)\n\n## Installation\n\n```bash\nnpm install @ainative/ai-kit-nextjs\n# or\npnpm add @ainative/ai-kit-nextjs\n# or\nyarn add @ainative/ai-kit-nextjs\n```\n\n## Quick Start\n\n### App Router (Next.js 13+)\n\n```typescript\n// app/api/chat/route.ts\nimport { createStreamingRoute, createSSEStream } from '@ainative/ai-kit-nextjs'\n\nexport const POST = createStreamingRoute(\n  async ({ request, body }) => {\n    const { stream, sendToken, sendUsage, end } = createSSEStream()\n\n    // Send tokens as they arrive\n    sendToken('Hello')\n    sendToken(' ')\n    sendToken('world')\n\n    // Send usage information\n    sendUsage({\n      promptTokens: 10,\n      completionTokens: 5,\n      totalTokens: 15,\n    })\n\n    // End the stream\n    end()\n\n    return stream\n  },\n  {\n    cors: { allowedOrigins: '*' },\n    validation: {\n      required: ['message'],\n    },\n  }\n)\n```\n\n### Pages Router\n\n```typescript\n// pages/api/chat.ts\nimport { createAPIRoute } from '@ainative/ai-kit-nextjs'\n\nexport default createAPIRoute(\n  async ({ req, res, body }) => {\n    // Set up SSE headers\n    res.writeHead(200, {\n      'Content-Type': 'text/event-stream',\n      'Cache-Control': 'no-cache',\n      'Connection': 'keep-alive',\n    })\n\n    // Send events\n    res.write(`event: token\\ndata: {\"token\":\"Hello\"}\\n\\n`)\n    res.write(`event: token\\ndata: {\"token\":\" world\"}\\n\\n`)\n    res.write(`event: done\\ndata: {\"timestamp\":\"${new Date().toISOString()}\"}\\n\\n`)\n\n    res.end()\n  },\n  {\n    cors: { allowedOrigins: '*' },\n  }\n)\n```\n\n## Features\n\n### Route Helpers\n\n#### `createStreamingRoute(handler, config)`\n\nCreates a streaming route handler for Next.js App Router with automatic SSE formatting.\n\n**Features:**\n- Automatic SSE protocol formatting\n- CORS handling with preflight support\n- Request body parsing and validation\n- Error handling with custom error handlers\n- Timeout support\n- Heartbeat for long-lived connections\n- Edge runtime compatible\n\n#### `createAPIRoute(handler, config)`\n\nCreates an API route handler for Next.js Pages Router.\n\n**Features:**\n- CORS handling\n- Request validation\n- Error handling\n- Timeout support\n\n#### `createSSEStream()`\n\nCreates a ReadableStream with helper functions for sending SSE events.\n\n**Returns:**\n- `stream`: ReadableStream to return from handler\n- `sendToken(token, index?)`: Send text token\n- `sendUsage(usage)`: Send token usage info\n- `sendError(error)`: Send error event\n- `sendMetadata(metadata)`: Send custom metadata\n- `sendEvent(event, data)`: Send custom event\n- `end()`: Close the stream\n\n### Utilities\n\n- `formatSSE(message)`: Format SSE message\n- `sendSSEMessage(controller, message)`: Send SSE via controller\n- `parseRequestBody(request)`: Parse NextRequest body\n- `createErrorResponse(message, status, cors)`: Create error response\n- `createSuccessResponse(data, status, cors)`: Create success response\n\n## Configuration Options\n\n### StreamingRouteConfig\n\n```typescript\ninterface StreamingRouteConfig {\n  cors?: {\n    allowedOrigins?: string[] | '*'\n    allowedMethods?: string[]\n    allowedHeaders?: string[]\n    exposedHeaders?: string[]\n    maxAge?: number\n    credentials?: boolean\n  }\n  validation?: {\n    required?: string[]\n    optional?: Record<string, 'string' | 'number' | 'boolean' | 'object' | 'array'>\n    validate?: (data: any) => { valid: boolean; error?: string }\n  }\n  headers?: Record<string, string>\n  timeout?: number\n  enableHeartbeat?: boolean\n  heartbeatInterval?: number\n  onError?: (error: Error) => void\n  logging?: boolean\n  metadata?: Record<string, any>\n}\n```\n\n## Complete Example with OpenAI\n\n```typescript\n// app/api/chat/openai/route.ts\nimport { createStreamingRoute, createSSEStream } from '@ainative/ai-kit-nextjs'\nimport OpenAI from 'openai'\n\nconst openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY })\n\nexport const POST = createStreamingRoute(\n  async ({ body }) => {\n    const { stream, sendToken, sendUsage, sendMetadata, sendError, end } = createSSEStream()\n\n    try {\n      // Send initial metadata\n      sendMetadata({\n        model: body.model || 'gpt-4',\n        requestId: crypto.randomUUID(),\n      })\n\n      // Create streaming completion\n      const completion = await openai.chat.completions.create({\n        model: body.model || 'gpt-4',\n        messages: body.messages,\n        temperature: body.temperature || 0.7,\n        stream: true,\n      })\n\n      // Stream the response\n      for await (const chunk of completion) {\n        const content = chunk.choices[0]?.delta?.content\n        if (content) {\n          sendToken(content)\n        }\n      }\n\n      // Send final usage\n      if (completion.usage) {\n        sendUsage({\n          promptTokens: completion.usage.prompt_tokens,\n          completionTokens: completion.usage.completion_tokens,\n          totalTokens: completion.usage.total_tokens,\n        })\n      }\n\n      end()\n    } catch (error) {\n      sendError({\n        error: error instanceof Error ? error.message : 'Unknown error',\n        code: 'OPENAI_ERROR',\n      })\n      end()\n    }\n\n    return stream\n  },\n  {\n    cors: {\n      allowedOrigins: process.env.ALLOWED_ORIGINS?.split(',') || ['http://localhost:3000'],\n      credentials: true,\n    },\n    validation: {\n      required: ['messages'],\n      optional: {\n        model: 'string',\n        temperature: 'number',\n        max_tokens: 'number',\n      },\n      validate: (data) => {\n        if (!Array.isArray(data.messages) || data.messages.length === 0) {\n          return { valid: false, error: 'Messages must be a non-empty array' }\n        }\n        return { valid: true }\n      },\n    },\n    enableHeartbeat: true,\n    timeout: 60000,\n    logging: true,\n  }\n)\n```\n\n## Next.js 16 Compatibility Notes\n\nNext.js 16 introduces several breaking changes. This package is fully compatible with all of them:\n\n- **Async Request APIs**: Next.js 16 requires fully async access to `params`, `searchParams`, `cookies()`, `headers()`, and `draftMode()`. Our route helpers handle requests synchronously at the API level, which remains fully compatible.\n- **Proxy.ts replaces Middleware.ts**: Our middleware utilities (CORS, Auth, Rate Limiting, etc.) work seamlessly with both the old `middleware.ts` and new `proxy.ts` approach.\n- **Parallel Routes require explicit default.js**: This doesn't affect our route helpers.\n- **No AMP Support**: We don't rely on any AMP-specific features.\n- **Node.js 20.9.0+ Required**: Ensure your runtime meets this requirement.\n\n## Documentation\n\nFor complete documentation, see:\n- [Route Helpers Guide](../../docs/nextjs/route-helpers.md)\n- [API Reference](../../docs/api/nextjs.md)\n\n## TypeScript Support\n\nThis package is written in TypeScript and provides full type definitions.\n\n```typescript\nimport type {\n  StreamingRouteConfig,\n  RouteConfig,\n  AppRouterContext,\n  PagesRouterContext,\n  StreamingRouteHandler,\n  APIRouteHandler,\n  CORSConfig,\n  ValidationSchema,\n  SSEMessage,\n  TokenEvent,\n  UsageEvent,\n  ErrorEvent,\n  MetadataEvent,\n} from '@ainative/ai-kit-nextjs'\n```\n\n## Testing\n\nThe package includes comprehensive tests with >95% coverage.\n\n```bash\npnpm test\npnpm test:coverage\n```\n\n## License\n\nMIT\n\n## Contributing\n\nContributions are welcome! Please read our [Contributing Guide](../../CONTRIBUTING.md) for details.\n\n## Support\n\n- GitHub: https://github.com/AINative-Studio/ai-kit\n- Documentation: https://ainative.studio/ai-kit\n- Issues: https://github.com/AINative-Studio/ai-kit/issues\n","readmeFilename":"README.md"}