river-ts-streaming
БесплатноЗапускает вложенные скриптыНе проверенType-safe Server-Sent Events (SSE) and WebSocket communication using river.ts library. Use when working with this codebase to: (1) Define typed event schemas…
от Bewinxed★ 109 звёзд на GitHubОб этом скилле
Quick Reference
river.ts provides three main components:
RiverEvents- Type-safe event schema builderRiverEmitter- Server-side SSE streamingRiverClient- Client-side SSE consumptionRiverSocketAdapter- WebSocket message handling with request/response support
Event Definition
Define events using the builder pattern:
import { RiverEvents } from 'river.ts';
const events = new RiverEvents()
.defineEvent('message', { message: 'Hello' })
.defineEvent('data', { data: {} as { id: number; name: string } })
.defineEvent('stream', { data: [] as string[], stream: true, chunkSize: 100 })
// Request/response pattern with explicit response type
.defineEvent('rpc.call', {
data: {} as { method: string; params: unknown },
response: {} as { result: unknown; error?: string }
})
// Runtime validation: `data` is inferred from the schema's output
.defineEvent('job.run', {
schema: z.object({ id: z.string(), priority: z.number() }),
responseSchema: z.object({ ok: z.boolean() }) // optional, for request()
})
.build();
Reserved event types: close, error - do not define these.
schema and responseSchema accept any Standard Schema (zod, valibot, arktype; https://standardschema.dev). Events without one are type-checked only.
Server-Side SSE (RiverEmitter)
import { RiverEmitter } from 'river.ts/server';
const emitter = RiverEmitter.init(events);
// Create SSE stream for HTTP response
const stream = emitter.stream({
callback: async (emit, clientId) => {
await emit('message', { message: 'Connected' });
await emit('data', { data: { id: 1, name: 'test' } });
},
clientId: 'optional-custom-id',
ondisconnect: (clientId) => console.log(`${clientId} disconnected`)
});
return new Response(stream, { headers: emitter.headers() });
// Broadcast to all clients
await emitter.broadcast('message', { message: 'Update' });
// Send to specific client
await emitter.sendToClient('client-id', 'data', { data: { id: 2, name: 'specific' } });
Resumable streams. All options are optional:
const stream = emitter.stream({
retry: 3000, // ms; written once as `retry:` when the stream opens
keepAlive: 15_000, // ms; writes a `: keep-alive` comment so proxies keep the connection
lastEventId: request.headers.get('Last-Event-ID'), // read it from the request yourself
signal: request.signal,
callback: async (emit, clientId, lastEventId) => {
// lastEventId is undefined on a first connection; replay everything after it
for (const entry of log.after(lastEventId)) {
await emit('message', { message: entry.text }, entry.id); // 3rd arg = event id
}
}
});
await emitter.broadcast('message', { message: 'Update' }, 42); // optional id
await emitter.sendToClient('client-id', 'message', { message: 'x' }, 43); // optional id
Event ids are string | number and may be non-ASCII: stream() decodes the Last-Event-ID header as UTF-8, so the callback gets the id as it was emitted. For stream: true events the id is written after the last chunk.
Client-Side SSE (RiverClient)
import { RiverClient } from 'river.ts/client';
const client = RiverClient.init(events, { reconnect: true });
client
.prepare('http://localhost:3000/events', { method: 'GET' })
.on('message', (data) => console.log(data.message))
.on('data', (data) => console.log(data.id, data.name))
.stream();
// Close connection
client.close();
// stream() can be called again after close()
Client options (all optional; reconnect is off by default):
const client = RiverClient.init(events, {
reconnect: true, // or { initialDelay: 1000, maxDelay: 30_000 }
lastEventId: savedId, // sent as Last-Event-ID on the first connection
onInvalid: (type, issues, raw) => {}, // events that fail their schema; never dispatched
fetchFn: fetch,
headers: { Authorization: 'Bearer ...' }
});
client.lastEventId; // read-only: id of the last event received; persist it to resume later
client.addEventListener('open', () => {}); // each successful connection
client.addEventListener('reconnect', (e) => {}); // (e as CustomEvent).detail = { attempt, delay, error }
client.addEventListener('close', () => {}); // stopped for good
Reconnect rules:
- Retries: network errors, 5xx, 429, and a stream that ends without a
closeevent. - Stops for good: HTTP 204, other 4xx,
client.close(), the server'scloseevent. - Delay:
Retry-After(429/503), else the server'sretry:value, else exponential backoff with jitter, capped atmaxDelay. - Every reconnect sends
Last-Event-ID(fetch path). A GET with no headers at all (none ininit(), none inprepare()) uses the browserEventSource, which reconnects and resumes by itself; any header, another method or an initiallastEventIdselectsfetch.
The parser follows the WHATWG event-str
Установить river-ts-streaming в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл river-ts-streaming?
Type-safe Server-Sent Events (SSE) and WebSocket communication using river.ts library. Use when working with this codebase to: (1) Define typed event schemas with RiverEvents builder, (2) Implement SSE streaming on server with RiverEmitter, (3) Consume SSE streams on client with RiverClient, (4) Handle WebSocket communication with RiverSocketAdapter, (5) Implement request/response RPC patterns over WebSocket, (6) Work with chunked/streamed data events.
Как установить скилл river-ts-streaming?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл river-ts-streaming запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic