@sixb/client 0.0.1

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.
Files changed (155) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +193 -0
  3. package/dist/actions.d.ts +61 -0
  4. package/dist/actions.d.ts.map +1 -0
  5. package/dist/agent-streams.d.ts +72 -0
  6. package/dist/agent-streams.d.ts.map +1 -0
  7. package/dist/api.d.ts +54 -0
  8. package/dist/api.d.ts.map +1 -0
  9. package/dist/browser.d.ts +41 -0
  10. package/dist/browser.d.ts.map +1 -0
  11. package/dist/browser.js +174 -0
  12. package/dist/browser.js.map +10 -0
  13. package/dist/chunk-05yz32g0.js +240 -0
  14. package/dist/chunk-05yz32g0.js.map +10 -0
  15. package/dist/chunk-2d7239yx.js +1181 -0
  16. package/dist/chunk-2d7239yx.js.map +17 -0
  17. package/dist/chunk-3g6ad4jc.js +147 -0
  18. package/dist/chunk-3g6ad4jc.js.map +10 -0
  19. package/dist/chunk-aw8rcsq3.js +145 -0
  20. package/dist/chunk-aw8rcsq3.js.map +10 -0
  21. package/dist/chunk-ctsdm59b.js +1477 -0
  22. package/dist/chunk-ctsdm59b.js.map +19 -0
  23. package/dist/chunk-fxrh83wy.js +180 -0
  24. package/dist/chunk-fxrh83wy.js.map +12 -0
  25. package/dist/chunk-pey7nh0d.js +123 -0
  26. package/dist/chunk-pey7nh0d.js.map +10 -0
  27. package/dist/chunk-trpg18dp.js +3 -0
  28. package/dist/chunk-trpg18dp.js.map +9 -0
  29. package/dist/events-builder.d.ts +218 -0
  30. package/dist/events-builder.d.ts.map +1 -0
  31. package/dist/events-hooks.d.ts +50 -0
  32. package/dist/events-hooks.d.ts.map +1 -0
  33. package/dist/events-model.d.ts +12 -0
  34. package/dist/events-model.d.ts.map +1 -0
  35. package/dist/events-provider.d.ts +56 -0
  36. package/dist/events-provider.d.ts.map +1 -0
  37. package/dist/events-transport.d.ts +62 -0
  38. package/dist/events-transport.d.ts.map +1 -0
  39. package/dist/events.d.ts +5 -0
  40. package/dist/events.d.ts.map +1 -0
  41. package/dist/file.d.ts +27 -0
  42. package/dist/file.d.ts.map +1 -0
  43. package/dist/generated/@tanstack/react-query.gen.d.ts +17064 -0
  44. package/dist/generated/@tanstack/react-query.gen.d.ts.map +1 -0
  45. package/dist/generated/client/client.gen.d.ts +3 -0
  46. package/dist/generated/client/client.gen.d.ts.map +1 -0
  47. package/dist/generated/client/index.d.ts +9 -0
  48. package/dist/generated/client/index.d.ts.map +1 -0
  49. package/dist/generated/client/types.gen.d.ts +118 -0
  50. package/dist/generated/client/types.gen.d.ts.map +1 -0
  51. package/dist/generated/client/utils.gen.d.ts +34 -0
  52. package/dist/generated/client/utils.gen.d.ts.map +1 -0
  53. package/dist/generated/client.gen.d.ts +13 -0
  54. package/dist/generated/client.gen.d.ts.map +1 -0
  55. package/dist/generated/core/auth.gen.d.ts +19 -0
  56. package/dist/generated/core/auth.gen.d.ts.map +1 -0
  57. package/dist/generated/core/bodySerializer.gen.d.ts +26 -0
  58. package/dist/generated/core/bodySerializer.gen.d.ts.map +1 -0
  59. package/dist/generated/core/params.gen.d.ts +44 -0
  60. package/dist/generated/core/params.gen.d.ts.map +1 -0
  61. package/dist/generated/core/pathSerializer.gen.d.ts +34 -0
  62. package/dist/generated/core/pathSerializer.gen.d.ts.map +1 -0
  63. package/dist/generated/core/queryKeySerializer.gen.d.ts +19 -0
  64. package/dist/generated/core/queryKeySerializer.gen.d.ts.map +1 -0
  65. package/dist/generated/core/serverSentEvents.gen.d.ts +72 -0
  66. package/dist/generated/core/serverSentEvents.gen.d.ts.map +1 -0
  67. package/dist/generated/core/types.gen.d.ts +79 -0
  68. package/dist/generated/core/types.gen.d.ts.map +1 -0
  69. package/dist/generated/core/utils.gen.d.ts +20 -0
  70. package/dist/generated/core/utils.gen.d.ts.map +1 -0
  71. package/dist/generated/index.d.ts +3 -0
  72. package/dist/generated/index.d.ts.map +1 -0
  73. package/dist/generated/sdk.gen.d.ts +464 -0
  74. package/dist/generated/sdk.gen.d.ts.map +1 -0
  75. package/dist/generated/types.gen.d.ts +7672 -0
  76. package/dist/generated/types.gen.d.ts.map +1 -0
  77. package/dist/hooks.d.ts +123 -0
  78. package/dist/hooks.d.ts.map +1 -0
  79. package/dist/hooks.js +3179 -0
  80. package/dist/hooks.js.map +16 -0
  81. package/dist/index.d.ts +11 -0
  82. package/dist/index.d.ts.map +1 -0
  83. package/dist/index.js +329 -0
  84. package/dist/index.js.map +9 -0
  85. package/dist/logs-builder.d.ts +59 -0
  86. package/dist/logs-builder.d.ts.map +1 -0
  87. package/dist/logs-hooks.d.ts +30 -0
  88. package/dist/logs-hooks.d.ts.map +1 -0
  89. package/dist/logs-transport.d.ts +38 -0
  90. package/dist/logs-transport.d.ts.map +1 -0
  91. package/dist/logs.d.ts +7 -0
  92. package/dist/logs.d.ts.map +1 -0
  93. package/dist/logs.js +22 -0
  94. package/dist/logs.js.map +9 -0
  95. package/dist/models.d.ts +126 -0
  96. package/dist/models.d.ts.map +1 -0
  97. package/dist/models.js +252 -0
  98. package/dist/models.js.map +9 -0
  99. package/dist/query-hooks.d.ts +365 -0
  100. package/dist/query-hooks.d.ts.map +1 -0
  101. package/dist/query.d.ts +27 -0
  102. package/dist/query.d.ts.map +1 -0
  103. package/dist/query.js +15 -0
  104. package/dist/query.js.map +9 -0
  105. package/dist/sha256.d.ts +15 -0
  106. package/dist/sha256.d.ts.map +1 -0
  107. package/dist/telemetry-events.d.ts +25 -0
  108. package/dist/telemetry-events.d.ts.map +1 -0
  109. package/dist/tsconfig.json +5 -0
  110. package/dist/useAgentRunStream.d.ts +21 -0
  111. package/dist/useAgentRunStream.d.ts.map +1 -0
  112. package/dist/ws-socket.d.ts +45 -0
  113. package/dist/ws-socket.d.ts.map +1 -0
  114. package/package.json +105 -0
  115. package/src/actions.ts +310 -0
  116. package/src/agent-streams.ts +275 -0
  117. package/src/api.ts +229 -0
  118. package/src/browser.ts +267 -0
  119. package/src/events-builder.ts +735 -0
  120. package/src/events-hooks.ts +233 -0
  121. package/src/events-model.ts +40 -0
  122. package/src/events-provider.ts +161 -0
  123. package/src/events-transport.ts +193 -0
  124. package/src/events.ts +6 -0
  125. package/src/file.ts +367 -0
  126. package/src/generated/@tanstack/react-query.gen.ts +3876 -0
  127. package/src/generated/client/client.gen.ts +288 -0
  128. package/src/generated/client/index.ts +25 -0
  129. package/src/generated/client/types.gen.ts +209 -0
  130. package/src/generated/client/utils.gen.ts +316 -0
  131. package/src/generated/client.gen.ts +18 -0
  132. package/src/generated/core/auth.gen.ts +41 -0
  133. package/src/generated/core/bodySerializer.gen.ts +84 -0
  134. package/src/generated/core/params.gen.ts +169 -0
  135. package/src/generated/core/pathSerializer.gen.ts +171 -0
  136. package/src/generated/core/queryKeySerializer.gen.ts +117 -0
  137. package/src/generated/core/serverSentEvents.gen.ts +243 -0
  138. package/src/generated/core/types.gen.ts +104 -0
  139. package/src/generated/core/utils.gen.ts +140 -0
  140. package/src/generated/index.ts +672 -0
  141. package/src/generated/sdk.gen.ts +1984 -0
  142. package/src/generated/types.gen.ts +9049 -0
  143. package/src/hooks.ts +404 -0
  144. package/src/index.ts +18 -0
  145. package/src/logs-builder.ts +171 -0
  146. package/src/logs-hooks.ts +112 -0
  147. package/src/logs-transport.ts +112 -0
  148. package/src/logs.ts +15 -0
  149. package/src/models.ts +420 -0
  150. package/src/query-hooks.ts +1021 -0
  151. package/src/query.ts +175 -0
  152. package/src/sha256.ts +159 -0
  153. package/src/telemetry-events.ts +71 -0
  154. package/src/useAgentRunStream.ts +62 -0
  155. package/src/ws-socket.ts +202 -0
@@ -0,0 +1,233 @@
1
+ /**
2
+ * React hooks over the `events.object(Type)` builder (`@sixb/client/hooks`).
3
+ *
4
+ * Each hook takes a built builder as its first argument — the same
5
+ * `hook(builder())` shape as `useObjectsQuery(objects(Type).query())` — and
6
+ * subscribes through the builder's transport. `@tanstack/react-query` and
7
+ * `react` are optional peers, so these hooks live behind the `./hooks` subpath
8
+ * and never the root barrel.
9
+ */
10
+ import { useQueryClient } from "@tanstack/react-query"
11
+ import { startTransition, useCallback, useEffect, useRef, useState } from "react"
12
+ import type { SixbEvent, SixbEventOfType } from "./events"
13
+ import type { SubscribableEvents } from "./events-builder"
14
+ import { useEventsRegistry } from "./events-provider"
15
+ import type { EventSocketState } from "./events-transport"
16
+ import { type TelemetryUpdate, telemetryUpdateFromEvent } from "./telemetry-events"
17
+
18
+ const DISCONNECTED: EventSocketState = { connected: false, reconnecting: false, error: null }
19
+
20
+ export interface UseEventsOptions {
21
+ readonly enabled?: boolean
22
+ readonly afterCursor?: string
23
+ readonly limit?: number
24
+ readonly reconnect?: boolean
25
+ readonly reconnectDelayMs?: number
26
+ readonly handshakeTimeoutMs?: number
27
+ readonly onError?: (error: string) => void
28
+ }
29
+
30
+ /**
31
+ * Subscribe to a builder's events. `onEvent` is kept in a ref so changing the
32
+ * handler never tears down the socket, and the subscription is rebuilt only when
33
+ * the filter spec (or transport options) change.
34
+ */
35
+ export function useEvents<TEvent extends SixbEvent>(
36
+ builder: SubscribableEvents<TEvent>,
37
+ onEvent: (event: TEvent) => void,
38
+ options?: UseEventsOptions
39
+ ): EventSocketState {
40
+ const builderRef = useRef(builder)
41
+ builderRef.current = builder
42
+ const onEventRef = useRef(onEvent)
43
+ onEventRef.current = onEvent
44
+ const onErrorRef = useRef(options?.onError)
45
+ onErrorRef.current = options?.onError
46
+
47
+ const [state, setState] = useState<EventSocketState>(DISCONNECTED)
48
+ const registry = useEventsRegistry()
49
+
50
+ const enabled = options?.enabled ?? true
51
+ const afterCursor = options?.afterCursor
52
+ const limit = options?.limit
53
+ const reconnect = options?.reconnect
54
+ const reconnectDelayMs = options?.reconnectDelayMs
55
+ const handshakeTimeoutMs = options?.handshakeTimeoutMs
56
+ const irKey = JSON.stringify(builder.ir)
57
+
58
+ // Re-subscribe only when the serialized filter spec (or a transport option)
59
+ // changes; the builder and handler are read through refs, so identity churn
60
+ // on every render never tears the socket down.
61
+ // biome-ignore lint/correctness/useExhaustiveDependencies: irKey is the reactive proxy for builder.ir, read via builderRef
62
+ useEffect(() => {
63
+ if (!enabled) {
64
+ setState(DISCONNECTED)
65
+ return
66
+ }
67
+
68
+ const handler = (event: SixbEvent) => onEventRef.current(event as TEvent)
69
+ const onError = (message: string) => onErrorRef.current?.(message)
70
+
71
+ // With a provider, delegate to the shared socket; otherwise open a
72
+ // per-builder socket. The transport options apply only to the standalone
73
+ // socket — the shared socket manages its own lifecycle.
74
+ if (registry) {
75
+ return registry.register(builderRef.current.ir, handler, { onError, onStateChange: setState })
76
+ }
77
+
78
+ return builderRef.current.subscribe((event) => onEventRef.current(event), {
79
+ afterCursor,
80
+ limit,
81
+ reconnect,
82
+ reconnectDelayMs,
83
+ handshakeTimeoutMs,
84
+ onError,
85
+ onStateChange: setState,
86
+ })
87
+ }, [
88
+ enabled,
89
+ irKey,
90
+ afterCursor,
91
+ limit,
92
+ reconnect,
93
+ reconnectDelayMs,
94
+ handshakeTimeoutMs,
95
+ registry,
96
+ ])
97
+
98
+ return state
99
+ }
100
+
101
+ /** Telemetry builder accepted by the latest-value hooks. */
102
+ type TelemetryEvents = SubscribableEvents<SixbEventOfType<"telemetry.appended">>
103
+
104
+ /**
105
+ * Track the latest telemetry update per property. The keying is by `propertyId`,
106
+ * so scope the builder to a single object (`events.object(Type).byId(key).telemetry()`)
107
+ * for a per-object view, or use `useLatestByObject` to bucket by object.
108
+ */
109
+ export function useLatest(
110
+ builder: TelemetryEvents,
111
+ options?: UseEventsOptions
112
+ ): { values: Record<string, TelemetryUpdate>; connected: boolean } {
113
+ const [values, setValues] = useState<Record<string, TelemetryUpdate>>({})
114
+ const irKey = JSON.stringify(builder.ir)
115
+ const enabled = options?.enabled ?? true
116
+
117
+ // Drop the accumulator when the scope changes or the hook is disabled, so a
118
+ // re-scoped builder never shows stale "live" values from the previous scope.
119
+ // biome-ignore lint/correctness/useExhaustiveDependencies: irKey is the reactive proxy for builder.ir
120
+ useEffect(() => {
121
+ setValues({})
122
+ }, [irKey, enabled])
123
+
124
+ const { connected } = useEvents(
125
+ builder,
126
+ (event) => {
127
+ const update = telemetryUpdateFromEvent(event)
128
+ setValues((prev) => ({ ...prev, [update.propertyId]: update }))
129
+ },
130
+ options
131
+ )
132
+
133
+ return { values, connected }
134
+ }
135
+
136
+ /** Track the latest telemetry update per property, bucketed by object id. */
137
+ export function useLatestByObject(
138
+ builder: TelemetryEvents,
139
+ options?: UseEventsOptions
140
+ ): { byObject: Record<string, Record<string, TelemetryUpdate>>; connected: boolean } {
141
+ const [byObject, setByObject] = useState<Record<string, Record<string, TelemetryUpdate>>>({})
142
+ const irKey = JSON.stringify(builder.ir)
143
+ const enabled = options?.enabled ?? true
144
+
145
+ // Drop the accumulator when the scope changes or the hook is disabled; without
146
+ // this `byObject` grows unbounded across navigation and keeps stale objects.
147
+ // biome-ignore lint/correctness/useExhaustiveDependencies: irKey is the reactive proxy for builder.ir
148
+ useEffect(() => {
149
+ setByObject({})
150
+ }, [irKey, enabled])
151
+
152
+ const { connected } = useEvents(
153
+ builder,
154
+ (event) => {
155
+ const update = telemetryUpdateFromEvent(event)
156
+ setByObject((prev) => ({
157
+ ...prev,
158
+ [update.objectId]: { ...prev[update.objectId], [update.propertyId]: update },
159
+ }))
160
+ },
161
+ options
162
+ )
163
+
164
+ return { byObject, connected }
165
+ }
166
+
167
+ export interface UseInvalidateOnEventOptions extends UseEventsOptions {
168
+ /** Coalesce invalidations into one flush after this many ms (default: 0). */
169
+ readonly debounceMs?: number
170
+ }
171
+
172
+ type QueryKeyInput = readonly unknown[]
173
+
174
+ /**
175
+ * Invalidate query keys when matching events arrive. `resolveKeys` maps an event
176
+ * to the keys to invalidate; keys are de-duplicated and, with `debounceMs`,
177
+ * coalesced into a single flush — the live-update pattern apps reimplement by
178
+ * hand. Invalidation runs inside `startTransition` to keep refetches off the
179
+ * critical render path.
180
+ */
181
+ export function useInvalidateOnEvent<TEvent extends SixbEvent>(
182
+ builder: SubscribableEvents<TEvent>,
183
+ resolveKeys: (event: TEvent) => readonly QueryKeyInput[],
184
+ options?: UseInvalidateOnEventOptions
185
+ ): EventSocketState {
186
+ const queryClient = useQueryClient()
187
+ const resolveKeysRef = useRef(resolveKeys)
188
+ resolveKeysRef.current = resolveKeys
189
+ const pendingRef = useRef(new Map<string, QueryKeyInput>())
190
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
191
+ const debounceMs = options?.debounceMs ?? 0
192
+
193
+ const flush = useCallback(() => {
194
+ if (timerRef.current) {
195
+ clearTimeout(timerRef.current)
196
+ timerRef.current = null
197
+ }
198
+ const keys = Array.from(pendingRef.current.values())
199
+ pendingRef.current.clear()
200
+ if (keys.length === 0) return
201
+
202
+ startTransition(() => {
203
+ for (const queryKey of keys) {
204
+ void queryClient.invalidateQueries({ queryKey })
205
+ }
206
+ })
207
+ }, [queryClient])
208
+ const flushRef = useRef(flush)
209
+ flushRef.current = flush
210
+
211
+ const state = useEvents(
212
+ builder,
213
+ (event) => {
214
+ for (const key of resolveKeysRef.current(event)) {
215
+ pendingRef.current.set(JSON.stringify(key), key)
216
+ }
217
+ if (debounceMs > 0) {
218
+ if (!timerRef.current) timerRef.current = setTimeout(flush, debounceMs)
219
+ } else {
220
+ flush()
221
+ }
222
+ },
223
+ options
224
+ )
225
+
226
+ // Flush the pending batch on unmount so an in-flight debounce window does not
227
+ // silently drop its last invalidations (`flush` also clears the timer).
228
+ useEffect(() => {
229
+ return () => flushRef.current()
230
+ }, [])
231
+
232
+ return state
233
+ }
@@ -0,0 +1,40 @@
1
+ import type { DomainEvent } from "@sixb/core"
2
+
3
+ type StoredEvent<TEvent extends DomainEvent> = TEvent extends DomainEvent
4
+ ? TEvent & { readonly cursor: string }
5
+ : never
6
+
7
+ export type SixbEvent = StoredEvent<DomainEvent>
8
+ export type SixbEventTopic = SixbEvent["topic"]
9
+ export type SixbEventType = SixbEvent["type"]
10
+ export type SixbEventOfType<TType extends SixbEventType> = DomainEvent extends infer TEvent
11
+ ? TEvent extends DomainEvent
12
+ ? TEvent["type"] extends TType
13
+ ? StoredEvent<TEvent>
14
+ : never
15
+ : never
16
+ : never
17
+ export type SixbEventOfTopic<TTopic extends SixbEventTopic> = DomainEvent extends infer TEvent
18
+ ? TEvent extends DomainEvent
19
+ ? TEvent["topic"] extends TTopic
20
+ ? StoredEvent<TEvent>
21
+ : never
22
+ : never
23
+ : never
24
+
25
+ export function isSixbEvent(value: unknown): value is SixbEvent {
26
+ return (
27
+ isRecord(value) &&
28
+ typeof value.id === "string" &&
29
+ typeof value.cursor === "string" &&
30
+ typeof value.projectId === "string" &&
31
+ typeof value.occurredAt === "string" &&
32
+ typeof value.type === "string" &&
33
+ typeof value.topic === "string" &&
34
+ typeof value.partitionKey === "string"
35
+ )
36
+ }
37
+
38
+ function isRecord(value: unknown): value is Record<string, unknown> {
39
+ return typeof value === "object" && value !== null
40
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Shared event socket for the `events.object(Type)` hooks (`@sixb/client/hooks`).
3
+ *
4
+ * Without a provider, each hook opens its own WebSocket. `SixbEventsProvider`
5
+ * multiplexes them onto a single socket: it subscribes broadly and fans each
6
+ * event out to the registered handlers whose filter predicate matches, opening
7
+ * on the first subscription and closing on the last. The hooks' public surface
8
+ * is unchanged — they delegate to the registry when one is present and fall
9
+ * back to a per-builder socket otherwise.
10
+ */
11
+ import { createContext, createElement, type ReactNode, useContext, useEffect, useMemo } from "react"
12
+ import type { SixbEvent } from "./events"
13
+ import { buildEventPredicate, type EventsFilterSpec } from "./events-builder"
14
+ import { createEventSocket, type EventSocket, type EventSocketState } from "./events-transport"
15
+
16
+ const DISCONNECTED: EventSocketState = { connected: false, reconnecting: false, error: null }
17
+
18
+ /**
19
+ * How long to keep an idle shared socket alive after the last subscriber leaves.
20
+ * A quick unmount→remount (route change, StrictMode double-invoke) reuses the
21
+ * live socket instead of dropping and reopening it.
22
+ */
23
+ const DEFAULT_CLOSE_DELAY_MS = 3000
24
+
25
+ export interface EventsRegistrationOptions {
26
+ readonly onError?: (error: string) => void
27
+ readonly onStateChange?: (state: EventSocketState) => void
28
+ }
29
+
30
+ export interface EventsRegistry {
31
+ /** Register a filtered handler on the shared socket; returns an unregister fn. */
32
+ register(
33
+ filter: EventsFilterSpec,
34
+ handler: (event: SixbEvent) => void,
35
+ options?: EventsRegistrationOptions
36
+ ): () => void
37
+ }
38
+
39
+ interface Subscriber {
40
+ readonly matches: (event: SixbEvent) => boolean
41
+ readonly handler: (event: SixbEvent) => void
42
+ readonly options?: EventsRegistrationOptions
43
+ }
44
+
45
+ export interface ManagedRegistry extends EventsRegistry {
46
+ /** Close the shared socket and drop every registration. */
47
+ close(): void
48
+ }
49
+
50
+ /**
51
+ * Build a registry backed by one lazily-opened socket. The socket subscribes
52
+ * broadly (no topic/type/scope) so adding or removing a subscriber never forces
53
+ * a re-subscribe — which would otherwise drop events across the reconnect — and
54
+ * each subscriber's predicate narrows the shared stream client-side.
55
+ *
56
+ * Trade-off: a broad subscription means the server-side object-scope filtering
57
+ * (by `objectTypeId`/`primaryId`) is bypassed under the provider — the socket
58
+ * receives the full authorized stream and filters in the browser. Per-event
59
+ * visibility is still enforced server-side (`canViewEvent`); only the
60
+ * coarse-scope narrowing moves client-side. The standalone path (no provider)
61
+ * still pushes object scope to the server. Per-subscription server-side scoping
62
+ * on the shared socket is not implemented.
63
+ */
64
+ export function createEventsRegistry(
65
+ options: { baseUrl?: string; closeDelayMs?: number } = {}
66
+ ): ManagedRegistry {
67
+ const subscribers = new Set<Subscriber>()
68
+ const closeDelayMs = options.closeDelayMs ?? DEFAULT_CLOSE_DELAY_MS
69
+ let socket: EventSocket | null = null
70
+ let state: EventSocketState = DISCONNECTED
71
+ // Carried across a true close→reopen so the new socket resumes after the last
72
+ // event seen instead of restarting from "now" and losing the gap.
73
+ let latestCursor: string | undefined
74
+ let closeTimer: ReturnType<typeof setTimeout> | null = null
75
+
76
+ const cancelPendingClose = () => {
77
+ if (closeTimer) {
78
+ clearTimeout(closeTimer)
79
+ closeTimer = null
80
+ }
81
+ }
82
+
83
+ const teardown = () => {
84
+ socket?.close()
85
+ socket = null
86
+ state = DISCONNECTED
87
+ }
88
+
89
+ const open = () => {
90
+ if (socket) return
91
+ socket = createEventSocket({
92
+ baseUrl: options.baseUrl,
93
+ afterCursor: latestCursor,
94
+ onEvent: (event) => {
95
+ latestCursor = event.cursor
96
+ for (const subscriber of subscribers) {
97
+ if (subscriber.matches(event)) subscriber.handler(event)
98
+ }
99
+ },
100
+ onError: (message) => {
101
+ for (const subscriber of subscribers) subscriber.options?.onError?.(message)
102
+ },
103
+ onStateChange: (next) => {
104
+ state = next
105
+ for (const subscriber of subscribers) subscriber.options?.onStateChange?.(next)
106
+ },
107
+ })
108
+ }
109
+
110
+ return {
111
+ register(filter, handler, registrationOptions) {
112
+ cancelPendingClose()
113
+ const subscriber: Subscriber = {
114
+ matches: buildEventPredicate(filter),
115
+ handler,
116
+ options: registrationOptions,
117
+ }
118
+ subscribers.add(subscriber)
119
+ // Sync a late subscriber to the socket's current status immediately.
120
+ registrationOptions?.onStateChange?.(state)
121
+ open()
122
+
123
+ return () => {
124
+ subscribers.delete(subscriber)
125
+ if (subscribers.size === 0) {
126
+ // Defer teardown: a quick unmount→remount reuses the live socket.
127
+ cancelPendingClose()
128
+ closeTimer = setTimeout(() => {
129
+ closeTimer = null
130
+ teardown()
131
+ }, closeDelayMs)
132
+ }
133
+ }
134
+ },
135
+ close() {
136
+ cancelPendingClose()
137
+ subscribers.clear()
138
+ teardown()
139
+ },
140
+ }
141
+ }
142
+
143
+ const EventsSocketContext = createContext<EventsRegistry | null>(null)
144
+
145
+ /** The active shared-socket registry, or `null` when no provider is mounted. */
146
+ export function useEventsRegistry(): EventsRegistry | null {
147
+ return useContext(EventsSocketContext)
148
+ }
149
+
150
+ /**
151
+ * Multiplex every `events.object(Type)` hook beneath it onto one shared WebSocket.
152
+ * Optional: hooks work without it (one socket each). `baseUrl` defaults to the
153
+ * global client config.
154
+ */
155
+ export function SixbEventsProvider(props: { baseUrl?: string; children?: ReactNode }) {
156
+ const registry = useMemo(() => createEventsRegistry({ baseUrl: props.baseUrl }), [props.baseUrl])
157
+
158
+ useEffect(() => () => registry.close(), [registry])
159
+
160
+ return createElement(EventsSocketContext.Provider, { value: registry }, props.children)
161
+ }
@@ -0,0 +1,193 @@
1
+ /**
2
+ * React-free event stream transport (exported via `@sixb/client` and `/hooks`).
3
+ *
4
+ * `createEventSocket` owns the full WebSocket lifecycle: connect, subscribe,
5
+ * advance the cursor, reconnect, and tear down.
6
+ * It surfaces connection status through an `onStateChange` callback instead of
7
+ * React state, so the same transport backs the builder's `.subscribe()` terminal
8
+ * and the hooks alike. React is an optional peer of `@sixb/client`; nothing here
9
+ * may import it.
10
+ */
11
+ import {
12
+ isSixbEvent,
13
+ type SixbEvent,
14
+ type SixbEventTopic,
15
+ type SixbEventType,
16
+ } from "./events-model"
17
+ import {
18
+ createReconnectingSocket,
19
+ createSixbWebSocketUrl,
20
+ type ReconnectingSocketState,
21
+ } from "./ws-socket"
22
+
23
+ /** Event-level state: `connected` becomes true only after the subscription is acknowledged. */
24
+ export type EventSocketState = ReconnectingSocketState
25
+
26
+ export interface EventSocketOptions {
27
+ readonly topic?: SixbEventTopic
28
+ readonly types?: readonly SixbEventType[]
29
+ /** Object-type scope; the server narrows the stream when set. */
30
+ readonly objectTypeId?: string
31
+ /** Object-instance scope; the server narrows the stream when set. */
32
+ readonly primaryId?: string
33
+ /** Action id scope; the server narrows the stream when set. */
34
+ readonly actionId?: string
35
+ /** Run id scope; the server narrows run/action streams when set. */
36
+ readonly runId?: string
37
+ readonly afterCursor?: string
38
+ readonly limit?: number
39
+ readonly reconnect?: boolean
40
+ readonly reconnectDelayMs?: number
41
+ /** Maximum time to complete the event protocol handshake. */
42
+ readonly handshakeTimeoutMs?: number
43
+ /** Override the API base url. Defaults to the global client config. */
44
+ readonly baseUrl?: string
45
+ readonly onEvent: (event: SixbEvent) => void
46
+ readonly onError?: (error: string) => void
47
+ readonly onStateChange?: (state: EventSocketState) => void
48
+ }
49
+
50
+ export interface EventSocket {
51
+ /** Stop reconnecting and close the underlying WebSocket. */
52
+ close(): void
53
+ }
54
+
55
+ type EventStreamServerMessage =
56
+ | { readonly type: "connected" | "subscribed" | "unsubscribed" }
57
+ | { readonly type: "error"; readonly message: string }
58
+ | { readonly type: "event"; readonly event: SixbEvent }
59
+
60
+ /**
61
+ * Open a subscribing WebSocket to `/ws/events` and stream matching events to
62
+ * `onEvent`. The socket tracks the latest cursor across reconnects so no event
63
+ * is replayed, and matches `topic`/`types` client-side (the server filters by
64
+ * the same fields when they are sent on the subscribe message).
65
+ */
66
+ export function createEventSocket(options: EventSocketOptions): EventSocket {
67
+ const { topic, types, objectTypeId, primaryId, actionId, runId, limit } = options
68
+ let latestCursor = options.afterCursor
69
+ let transportState: ReconnectingSocketState = {
70
+ connected: false,
71
+ reconnecting: false,
72
+ error: null,
73
+ }
74
+ let subscribed = false
75
+
76
+ const publishState = () => {
77
+ options.onStateChange?.({
78
+ ...transportState,
79
+ connected: transportState.connected && subscribed,
80
+ })
81
+ }
82
+
83
+ return createReconnectingSocket({
84
+ url: createSixbEventsWebSocketUrl(options.baseUrl),
85
+ reconnect: options.reconnect,
86
+ reconnectDelayMs: options.reconnectDelayMs,
87
+ readyTimeoutMs: options.handshakeTimeoutMs,
88
+ readyTimeoutMessage: "Event websocket handshake timed out.",
89
+ connectionErrorMessage: "Event websocket connection failed.",
90
+ onError: options.onError,
91
+ onStateChange: (state) => {
92
+ transportState = state
93
+ if (!state.connected) subscribed = false
94
+ publishState()
95
+ },
96
+ subscribeMessage: () => ({
97
+ type: "subscribe",
98
+ ...(topic ? { topic } : {}),
99
+ ...(types && types.length > 0 ? { types } : {}),
100
+ ...(objectTypeId ? { objectTypeId } : {}),
101
+ ...(primaryId ? { primaryId } : {}),
102
+ ...(actionId ? { actionId } : {}),
103
+ ...(runId ? { runId } : {}),
104
+ ...(latestCursor ? { afterCursor: latestCursor } : {}),
105
+ ...(limit ? { limit } : {}),
106
+ }),
107
+ // The event server resolves its initial cursor before announcing readiness.
108
+ // Waiting for that frame prevents subscribe from racing server-side state setup.
109
+ subscribeWhen: (data) => parseEventStreamMessage(data)?.type === "connected",
110
+ readyWhen: (data) => parseEventStreamMessage(data)?.type === "subscribed",
111
+ onMessage: (data, sink) => {
112
+ const message = parseEventStreamMessage(data)
113
+ if (!message) return
114
+
115
+ if (message.type === "event") {
116
+ latestCursor = message.event.cursor
117
+ if (matchesSubscription(message.event, topic, types)) {
118
+ options.onEvent(message.event)
119
+ }
120
+ return
121
+ }
122
+
123
+ if (message.type === "subscribed") {
124
+ subscribed = true
125
+ publishState()
126
+ return
127
+ }
128
+
129
+ if (message.type === "error") {
130
+ sink.reportError(message.message)
131
+ }
132
+ },
133
+ })
134
+ }
135
+
136
+ export function createSixbEventsWebSocketUrl(baseUrl?: string): string {
137
+ return createSixbWebSocketUrl("/ws/events", baseUrl)
138
+ }
139
+
140
+ export function parseEventStreamMessage(value: unknown): EventStreamServerMessage | null {
141
+ if (typeof value !== "string") {
142
+ return null
143
+ }
144
+
145
+ let parsed: unknown
146
+ try {
147
+ parsed = JSON.parse(value)
148
+ } catch {
149
+ return null
150
+ }
151
+
152
+ if (!isRecord(parsed) || typeof parsed.type !== "string") {
153
+ return null
154
+ }
155
+
156
+ if (parsed.type === "event" && isSixbEvent(parsed.event)) {
157
+ return { type: "event", event: parsed.event }
158
+ }
159
+
160
+ if (parsed.type === "error") {
161
+ return { type: "error", message: String(parsed.message ?? "Event stream error.") }
162
+ }
163
+
164
+ if (
165
+ parsed.type === "connected" ||
166
+ parsed.type === "subscribed" ||
167
+ parsed.type === "unsubscribed"
168
+ ) {
169
+ return { type: parsed.type }
170
+ }
171
+
172
+ return null
173
+ }
174
+
175
+ export function matchesSubscription(
176
+ event: SixbEvent,
177
+ topic: SixbEventTopic | undefined,
178
+ types: readonly SixbEventType[] | undefined
179
+ ): boolean {
180
+ if (topic && event.topic !== topic) {
181
+ return false
182
+ }
183
+
184
+ if (types && types.length > 0 && !types.includes(event.type)) {
185
+ return false
186
+ }
187
+
188
+ return true
189
+ }
190
+
191
+ function isRecord(value: unknown): value is Record<string, unknown> {
192
+ return typeof value === "object" && value !== null
193
+ }
package/src/events.ts ADDED
@@ -0,0 +1,6 @@
1
+ // The shared event model, fluent builder, React-free transport, and telemetry helpers.
2
+
3
+ export * from "./events-builder"
4
+ export * from "./events-model"
5
+ export * from "./events-transport"
6
+ export * from "./telemetry-events"