@durable-streams/tanstack-ai-transport

中文文档
0.0.10发布于 2026/09/11Apache-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 1.2万

TanStack AI adapters for Durable Streams

原始使用文档
文档目录20 节
  1. What this package does
  2. Install
  3. Quick start
  4. Client: create a durable session connection
  5. Server: write model chunks to durable stream
  6. Integration guide (recommended chat session flow)
  7. 1) Client connection
  8. 2) POST route ( /api/chat )
  9. 3) GET proxy route ( /api/chat-stream )
  10. 4) SSR hydrate + resume
  11. API reference
  12. Client APIs
  13. Server APIs
  14. Shared types
  15. Response contract
  16. toDurableStreamResponse(..., { mode: "immediate" })
  17. toDurableStreamResponse(..., { mode: "await" })
  18. toDurableChatSessionResponse(..., { mode: "immediate" })
  19. toDurableChatSessionResponse(..., { mode: "await" })
  20. waitUntil usage

@durable-streams/tanstack-ai-transport

TanStack AI adapters for Durable Streams.

What this package does

This package gives you:

  • A TanStack-compatible client connection (subscribe + send)
  • Server helpers to write TanStack chunks into Durable Streams
  • Chat-session helpers for echoing user prompts and enforcing JSON stream format
  • Snapshot materialization helpers for SSR hydration + resume offsets

Use this when you want chat sessions that survive refreshes/reconnects and can be shared across multiple clients.

Install

pnpm add @durable-streams/tanstack-ai-transport @durable-streams/client

Quick start

Client: create a durable session connection

import { durableStreamConnection } from "@durable-streams/tanstack-ai-transport"

const connection = durableStreamConnection({
  sendUrl: "/api/chat?id=chat_123",
  readUrl: "/api/chat-stream?id=chat_123",
  initialOffset: undefined,
})

Pass this connection to useChat from @tanstack/ai-react.

Server: write model chunks to durable stream

import { toDurableChatSessionResponse } from "@durable-streams/tanstack-ai-transport"

return toDurableChatSessionResponse({
  stream: {
    writeUrl,
    headers,
  },
  newMessages: [latestUserMessage],
  responseStream, // AsyncIterable<TanStackChunk>
})

This appends the new user message to the durable stream, pipes AI response chunks, and returns an empty success response.

1) Client connection

const connection = durableStreamConnection({
  sendUrl: `/api/chat?id=${chatId}`,
  readUrl: `/api/chat-stream?id=${encodeURIComponent(chatId)}`,
  initialOffset: resumeOffsetFromSSR,
})

Use with useChat({ id: chatId, connection, live: true }).

2) POST route (/api/chat)

  • Validate chat id
  • Build durable stream write URL
  • Keep newMessages explicit (usually latest user message)
  • Start your model stream (responseStream)
  • Return toDurableChatSessionResponse(...)

3) GET proxy route (/api/chat-stream)

  • Accept a chat id query param
  • Build upstream durable read URL on the server from that id
  • Forward query params like offset, live, etc.
  • Add durable read auth headers on the server
  • Return upstream body/headers to client

4) SSR hydrate + resume

For chat page loaders:

  • materializeSnapshotFromDurableStream({ readUrl, headers })
  • send messages + offset to client
  • use that offset as initialOffset on durableStreamConnection

This avoids replaying entire history on first subscribe.

API reference

Client APIs

durableStreamConnection(options)

Creates a TanStack-compatible connection object with:

  • subscribe(abortSignal?) => AsyncIterable<TanStackChunk>
  • send(messages, data?, abortSignal?) => Promise<void>

DurableStreamConnectionOptions:

  • sendUrl: string (required) - where send(...) POSTs
  • readUrl?: string - where subscribe(...) reads from (defaults to sendUrl)
  • initialOffset?: string - initial durable offset for resuming
  • emitSnapshotOnSubscribe?: boolean (default true) - emit synthetic MESSAGES_SNAPSHOT on initial catch-up
  • headers?: HeadersInit - applied to both read and write requests
  • fetchClient?: typeof fetch - custom fetch implementation

Behavior:

  • send(...) POSTs { messages, data } to sendUrl
  • subscribe(...) reads durable JSON stream batches and yields TanStack chunks
  • internal offset is updated as batches arrive, so later subscribes continue from the latest seen offset

materializeSnapshotFromDurableStream(options)

Reads a non-live durable stream and materializes TanStack message state.

Input:

  • readUrl: string
  • headers?: HeadersInit
  • offset?: string

Returns:

  • { messages: Array<any>; offset?: string }

sanitizeChunkForStorage(chunk)

Removes duplicated content on TEXT_MESSAGE_CONTENT chunks (keeps delta) to reduce stored payload size.

Server APIs

toDurableChatSessionResponse(options)

High-level helper for chat session writes.

ToDurableChatSessionResponseOptions:

  • stream: DurableChatSessionStreamTarget (writeUrl, headers, createIfMissing)
  • newMessages: DurableSessionMessage[] - explicitly appended prompt messages
  • responseStream: AsyncIterable<TanStackChunk> - model chunk source
  • mode?: "immediate" | "await" (default immediate)
  • waitUntil?: (promise: Promise<unknown>) => void

Notes:

  • chat session streams are always application/json
  • appends newMessages using toMessageEchoChunks(...)
  • sanitizes chunks before writing

toDurableStreamResponse(source, options)

Lower-level generic writer for arbitrary async chunk sources.

ToDurableStreamResponseOptions:

  • stream: DurableStreamTarget
  • mode?: "immediate" | "await"
  • waitUntil?: (promise: Promise<unknown>) => void
  • exposeLocationHeader?: boolean

ensureDurableChatSessionStream(streamTarget)

Ensures a durable stream exists for chat-session usage, enforcing application/json.

toMessageEchoChunks(message)

Converts a user/system/assistant message into:

  • TEXT_MESSAGE_START
  • TEXT_MESSAGE_CONTENT (if text exists)
  • TEXT_MESSAGE_END

This preserves explicit message IDs when provided.

appendSanitizedChunksToStream(stream, chunks, contentType?)

Appends chunk array with sanitizeChunkForStorage applied.

pipeSanitizedChunksToStream(source, stream, contentType?)

Pipes async chunk source with sanitizeChunkForStorage applied.

Shared types

  • TanStackChunk
  • DurableSessionConnection
  • DurableStreamConnection (alias)
  • DurableStreamConnectionOptions
  • DurableChatSessionStreamTarget
  • DurableStreamTarget
  • ToDurableStreamResponseMode
  • ToDurableStreamResponseOptions
  • ToDurableChatSessionResponseOptions
  • DurableSessionMessage
  • DurableSessionMessagePart
  • WaitUntil

Response contract

toDurableStreamResponse(..., { mode: "immediate" })

  • Status: 201
  • Header: Location: <read-url>
  • Body: { "streamUrl": "<read-url>" }

toDurableStreamResponse(..., { mode: "await" })

  • Status: 200
  • Header: Location: <read-url>
  • Body: { "streamUrl": "<read-url>", "finalOffset": "<offset>" }

toDurableChatSessionResponse(..., { mode: "immediate" })

  • Status: 202
  • Body: empty

toDurableChatSessionResponse(..., { mode: "await" })

  • Status: 200
  • Body: empty

waitUntil usage

return toDurableChatSessionResponse({
  stream: { writeUrl, headers },
  newMessages,
  responseStream,
  waitUntil: ctx.waitUntil.bind(ctx),
})

Use waitUntil in worker-style runtimes so background writes continue after the pointer response is returned.

版本与发布记录

@durable-streams/tanstack-ai-transport 共发布 10 个版本,首次发布于 2026/03/24;过去 12 个月发布了 10 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.0.10latest2026/09/112 个月前
0.0.92026/07/173 个月前
0.0.82026/06/015 个月前
0.0.72026/05/285 个月前
0.0.62026/05/205 个月前
0.0.52026/05/195 个月前

关于 @durable-streams/tanstack-ai-transport 的常见问题

@durable-streams/tanstack-ai-transport 是什么?

TanStack AI adapters for Durable Streams

如何安装 @durable-streams/tanstack-ai-transport?

在项目目录运行 npm install @durable-streams/tanstack-ai-transport,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 intent,可以用 npx intent 直接运行。

@durable-streams/tanstack-ai-transport 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@durable-streams/tanstack-ai-transport 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@durable-streams/tanstack-ai-transport 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@durable-streams/tanstack-ai-transport 可以商用吗?

@durable-streams/tanstack-ai-transport 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@durable-streams/tanstack-ai-transport 的下载量有多少?

根据 npm 官方下载统计,@durable-streams/tanstack-ai-transport 在 2026/10/13 – 2026/11/11 这 30 天内被下载 12,217 次,日均约 407 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@durable-streams/tanstack-ai-transport 还在维护吗?

最新版本 0.0.10 发布于 2026/09/11(2 个月前);至今共发布 10 个版本,其中过去 12 个月发布了 10 个;首次发布于 2026/03/24。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。