@cslug/realtime 0.0.0-stage → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/vue.ts ADDED
@@ -0,0 +1,157 @@
1
+ /**
2
+ * @cslug/realtime/vue: `useChat()` for a chatbot (POST a message, stream the reply) and `useChannel()` for pushes.
3
+ * Both are safe to call during server rendering: they connect only in the browser, and clean up with their
4
+ * component (or effect scope).
5
+ */
6
+ import { getCurrentScope, onScopeDispose, type Ref, ref, shallowRef } from 'vue'
7
+ import {
8
+ type ChannelMessage,
9
+ type ConnectOptions,
10
+ connect,
11
+ type RealtimeClient,
12
+ type Status,
13
+ streamPost,
14
+ } from './client'
15
+
16
+ const inBrowser = typeof window !== 'undefined'
17
+
18
+ // ── useChat ─────────────────────────────────────────────────────────────────────────────────────────
19
+
20
+ export type ChatMessage = { id: string; role: 'user' | 'assistant'; content: string }
21
+
22
+ export type UseChatOptions = {
23
+ /** The route that answers with server-sent events (`return sse(agent.stream({ input }))`). */
24
+ url: string
25
+ /** Messages already there (a conversation loaded with the page). */
26
+ initial?: ChatMessage[]
27
+ /** The JSON posted for a message (default `{ message }`): add a conversation id, options… */
28
+ body?: (message: string, messages: ChatMessage[]) => unknown
29
+ /** For tests and other runtimes. */
30
+ fetch?: typeof fetch
31
+ }
32
+
33
+ let n = 0
34
+ const newId = () => `m${Date.now().toString(36)}${(n++).toString(36)}`
35
+
36
+ /**
37
+ * A chat: `send()` posts the input and appends the reply as it streams (`data` tokens; `done` ends it; `error`
38
+ * sets `error`). `stop()` aborts the request, which ends the stream on the server (the model run stops too).
39
+ */
40
+ export function useChat(options: UseChatOptions) {
41
+ const messages: Ref<ChatMessage[]> = ref([...(options.initial ?? [])])
42
+ const input = ref('')
43
+ const status = ref<'idle' | 'streaming' | 'error'>('idle')
44
+ const error = ref<string | null>(null)
45
+ let controller: AbortController | undefined
46
+
47
+ async function send(text?: string): Promise<void> {
48
+ const content = (text ?? input.value).trim()
49
+ if (!content || status.value === 'streaming') return
50
+ input.value = ''
51
+ error.value = null
52
+ messages.value.push({ id: newId(), role: 'user', content })
53
+ const reply: ChatMessage = { id: newId(), role: 'assistant', content: '' }
54
+ messages.value.push(reply)
55
+ // the reactive copy, so appending tokens updates the view
56
+ const live = messages.value[messages.value.length - 1] as ChatMessage
57
+ const body = options.body ? options.body(content, messages.value.slice(0, -1)) : { message: content }
58
+ controller = new AbortController()
59
+ status.value = 'streaming'
60
+ try {
61
+ for await (const e of streamPost(options.url, body, { signal: controller.signal, fetch: options.fetch })) {
62
+ if (e.event === 'error') {
63
+ error.value = String((e.data as { message?: string })?.message ?? 'The reply failed')
64
+ status.value = 'error'
65
+ return
66
+ }
67
+ if (e.event === 'done') break
68
+ if (e.event === 'message' || e.event === 'token')
69
+ live.content += typeof e.data === 'string' ? e.data : JSON.stringify(e.data)
70
+ }
71
+ status.value = 'idle'
72
+ } catch (err) {
73
+ if (controller.signal.aborted) {
74
+ status.value = 'idle'
75
+ return
76
+ }
77
+ error.value = err instanceof Error ? err.message : String(err)
78
+ status.value = 'error'
79
+ } finally {
80
+ controller = undefined
81
+ }
82
+ }
83
+
84
+ function stop(): void {
85
+ controller?.abort()
86
+ }
87
+
88
+ if (getCurrentScope()) onScopeDispose(stop)
89
+ return { messages, input, status, error, send, stop }
90
+ }
91
+
92
+ // ── useChannel ──────────────────────────────────────────────────────────────────────────────────────
93
+
94
+ const clients = new Map<string, RealtimeClient>()
95
+
96
+ /** The page's shared client for these options (one connection per transport and URL). */
97
+ export function sharedClient(options: ConnectOptions = {}): RealtimeClient {
98
+ const key = `${options.transport ?? 'sse'} ${options.url ?? '/realtime'}`
99
+ let client = clients.get(key)
100
+ if (!client) {
101
+ client = connect(options)
102
+ clients.set(key, client)
103
+ }
104
+ return client
105
+ }
106
+
107
+ /**
108
+ * Join a channel for as long as the component lives: `const chat = useChannel(`chats.${id}`)`, then
109
+ * `chat.on('message', (data) => …)`. `last` is the latest message; `status` the connection's; `denied` the reason
110
+ * when the server refused this channel.
111
+ */
112
+ export function useChannel(name: string, options: ConnectOptions = {}) {
113
+ const status = ref<Status>('connecting')
114
+ const last = shallowRef<ChannelMessage | null>(null)
115
+ const denied = ref<string | null>(null)
116
+ const offs: (() => void)[] = []
117
+ let channel: ReturnType<RealtimeClient['channel']> | undefined
118
+
119
+ if (inBrowser) {
120
+ const client = sharedClient(options)
121
+ channel = client.channel(name)
122
+ status.value = client.status
123
+ offs.push(
124
+ client.onStatus((s) => {
125
+ status.value = s
126
+ }),
127
+ )
128
+ offs.push(
129
+ channel.on('*', (_data, message) => {
130
+ last.value = message
131
+ }),
132
+ )
133
+ offs.push(
134
+ channel.onState((state, reason) => {
135
+ denied.value = state === 'denied' ? (reason ?? 'denied') : null
136
+ }),
137
+ )
138
+ }
139
+
140
+ function on(event: string, handler: (data: unknown, message: ChannelMessage) => void): () => void {
141
+ if (!channel) return () => {} // server rendering: nothing to listen to
142
+ const off = channel.on(event, handler)
143
+ offs.push(off)
144
+ return off
145
+ }
146
+
147
+ function whisper(event: string, data?: unknown): void {
148
+ channel?.whisper(event, data)
149
+ }
150
+
151
+ if (getCurrentScope())
152
+ onScopeDispose(() => {
153
+ for (const off of offs) off()
154
+ channel?.leave()
155
+ })
156
+ return { status, last, denied, on, whisper }
157
+ }