@sixb/client 0.1.1 → 0.1.3

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 (77) hide show
  1. package/README.md +2 -2
  2. package/dist/agent-streams.d.ts +26 -3
  3. package/dist/agent-streams.d.ts.map +1 -1
  4. package/dist/api.d.ts +6 -2
  5. package/dist/api.d.ts.map +1 -1
  6. package/dist/browser.d.ts +1 -1
  7. package/dist/browser.d.ts.map +1 -1
  8. package/dist/browser.js +2 -2
  9. package/dist/browser.js.map +1 -1
  10. package/dist/{chunk-2vsyqn32.js → chunk-6esh0dxx.js} +1 -1
  11. package/dist/{chunk-hkrfakyt.js → chunk-7ts981a8.js} +2 -2
  12. package/dist/{chunk-h8bd95xf.js → chunk-eyd61e4t.js} +55 -2
  13. package/dist/chunk-eyd61e4t.js.map +19 -0
  14. package/dist/{chunk-1mnf48s9.js → chunk-heqezbjc.js} +2 -2
  15. package/dist/{chunk-dkd2wgva.js → chunk-hfk246y4.js} +40 -28
  16. package/dist/{chunk-dkd2wgva.js.map → chunk-hfk246y4.js.map} +3 -3
  17. package/dist/{chunk-w527w02k.js → chunk-mpgzkmwc.js} +2 -74
  18. package/dist/chunk-mpgzkmwc.js.map +10 -0
  19. package/dist/{chunk-6w5w9e75.js → chunk-yjank04c.js} +27 -12
  20. package/dist/chunk-yjank04c.js.map +10 -0
  21. package/dist/client-provider.d.ts +8 -0
  22. package/dist/client-provider.d.ts.map +1 -0
  23. package/dist/connectors/connection.d.ts +50 -0
  24. package/dist/connectors/connection.d.ts.map +1 -0
  25. package/dist/connectors/index.d.ts +4 -0
  26. package/dist/connectors/index.d.ts.map +1 -0
  27. package/dist/connectors/mutations.d.ts +62 -0
  28. package/dist/connectors/mutations.d.ts.map +1 -0
  29. package/dist/connectors/queries.d.ts +536 -0
  30. package/dist/connectors/queries.d.ts.map +1 -0
  31. package/dist/generated/@tanstack/react-query.gen.d.ts +5679 -809
  32. package/dist/generated/@tanstack/react-query.gen.d.ts.map +1 -1
  33. package/dist/generated/index.d.ts +2 -2
  34. package/dist/generated/index.d.ts.map +1 -1
  35. package/dist/generated/sdk.gen.d.ts +41 -1
  36. package/dist/generated/sdk.gen.d.ts.map +1 -1
  37. package/dist/generated/types.gen.d.ts +2330 -218
  38. package/dist/generated/types.gen.d.ts.map +1 -1
  39. package/dist/hooks.d.ts +2 -0
  40. package/dist/hooks.d.ts.map +1 -1
  41. package/dist/hooks.js +1180 -360
  42. package/dist/hooks.js.map +11 -6
  43. package/dist/index.js +29 -11
  44. package/dist/index.js.map +1 -1
  45. package/dist/logs.js +3 -3
  46. package/dist/models.d.ts +0 -31
  47. package/dist/models.d.ts.map +1 -1
  48. package/dist/models.js +23 -7
  49. package/dist/models.js.map +1 -1
  50. package/dist/query-hooks.d.ts +2 -6
  51. package/dist/query-hooks.d.ts.map +1 -1
  52. package/dist/query.js +3 -3
  53. package/dist/useAgentActivityStream.d.ts +14 -0
  54. package/dist/useAgentActivityStream.d.ts.map +1 -0
  55. package/package.json +6 -2
  56. package/src/agent-streams.ts +68 -45
  57. package/src/api.ts +26 -2
  58. package/src/browser.ts +1 -1
  59. package/src/client-provider.ts +12 -0
  60. package/src/connectors/connection.ts +443 -0
  61. package/src/connectors/index.ts +12 -0
  62. package/src/connectors/mutations.ts +417 -0
  63. package/src/connectors/queries.ts +150 -0
  64. package/src/generated/@tanstack/react-query.gen.ts +346 -0
  65. package/src/generated/index.ts +60 -0
  66. package/src/generated/sdk.gen.ts +189 -0
  67. package/src/generated/types.gen.ts +3048 -254
  68. package/src/hooks.ts +6 -0
  69. package/src/models.ts +0 -103
  70. package/src/query-hooks.ts +8 -14
  71. package/src/useAgentActivityStream.ts +48 -0
  72. package/dist/chunk-6w5w9e75.js.map +0 -10
  73. package/dist/chunk-h8bd95xf.js.map +0 -19
  74. package/dist/chunk-w527w02k.js.map +0 -10
  75. /package/dist/{chunk-2vsyqn32.js.map → chunk-6esh0dxx.js.map} +0 -0
  76. /package/dist/{chunk-hkrfakyt.js.map → chunk-7ts981a8.js.map} +0 -0
  77. /package/dist/{chunk-1mnf48s9.js.map → chunk-heqezbjc.js.map} +0 -0
@@ -0,0 +1,443 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react"
2
+ import { isSixbApiError } from "../api"
3
+ import {
4
+ useConnectConnector,
5
+ useDisconnectConnector,
6
+ useReauthorizeConnector,
7
+ useRevokeConnector,
8
+ useSelectConnectorAccount,
9
+ } from "./mutations"
10
+ import {
11
+ type ConnectorAccount,
12
+ type ConnectorConnection,
13
+ type ConnectorConnectionRun,
14
+ useConnectorConnectionRun,
15
+ useConnectorConnections,
16
+ } from "./queries"
17
+
18
+ const CONNECTOR_CALLBACK_CONNECTOR_PARAM = "connectionConnectorId"
19
+ const CONNECTOR_CALLBACK_RUN_PARAM = "connectionRunId"
20
+ const RUN_POLL_INTERVAL_MS = 1_000
21
+
22
+ interface ConnectorConnectionCallback {
23
+ readonly connectorId: string
24
+ readonly runId: string
25
+ }
26
+
27
+ export interface UseConnectorConnectionOptions {
28
+ readonly connectorId: string
29
+ /** Stable application-defined role filled by this connection, for example `organic` or `ads`. */
30
+ readonly slot: string
31
+ /** Defaults to the current page while preserving unrelated query parameters and the hash. */
32
+ readonly returnTo?: string
33
+ }
34
+
35
+ export type ConnectorConnectionStatus =
36
+ | "loading"
37
+ | "disconnected"
38
+ | "authorizing"
39
+ | "selecting_account"
40
+ | "connected"
41
+ | "needs_reauthorization"
42
+ | "error"
43
+
44
+ export type ConnectorConnectionOperation =
45
+ | "load"
46
+ | "resume"
47
+ | "connect"
48
+ | "select_account"
49
+ | "disconnect"
50
+ | "revoke"
51
+
52
+ export interface ConnectorConnectionFailure {
53
+ readonly operation: ConnectorConnectionOperation
54
+ readonly cause: unknown
55
+ }
56
+
57
+ export interface ConnectorAccountSelectionOptions {
58
+ readonly replace?: boolean
59
+ }
60
+
61
+ export interface UseConnectorConnectionResult {
62
+ readonly status: ConnectorConnectionStatus
63
+ readonly connection: ConnectorConnection | undefined
64
+ readonly accounts: readonly ConnectorAccount[]
65
+ readonly error: ConnectorConnectionFailure | null
66
+ /** Whether a new authorization or reauthorization can start from the current state. */
67
+ readonly canConnect: boolean
68
+ readonly isPending: boolean
69
+ readonly selectedAccountId: string | undefined
70
+ connect(): Promise<void>
71
+ selectAccount(accountId: string, options?: ConnectorAccountSelectionOptions): Promise<void>
72
+ disconnect(): Promise<void>
73
+ revoke(): Promise<void>
74
+ refresh(): Promise<void>
75
+ dismiss(): void
76
+ resetError(): void
77
+ }
78
+
79
+ /**
80
+ * Headless OAuth connection flow for one application-defined connector slot.
81
+ *
82
+ * The hook owns browser redirection, durable run resumption and cache convergence. The application
83
+ * owns presentation, including account selection and replacement confirmation.
84
+ */
85
+ export function useConnectorConnection({
86
+ connectorId,
87
+ slot,
88
+ returnTo,
89
+ }: UseConnectorConnectionOptions): UseConnectorConnectionResult {
90
+ const [callback, setCallback] = useState(readConnectorConnectionCallback)
91
+ const connectInFlightRef = useRef<Promise<void> | null>(null)
92
+ const callbackRunId = callback?.connectorId === connectorId ? callback.runId : null
93
+ const connectionsQuery = useConnectorConnections({ connectorId })
94
+ const connection = useMemo(
95
+ () => connectionsQuery.data?.find((candidate) => candidate.slot === slot),
96
+ [connectionsQuery.data, slot]
97
+ )
98
+ const runQuery = useConnectorConnectionRun({
99
+ connectorId,
100
+ runId: callbackRunId,
101
+ refetchInterval: (query) => (isRunInProgress(query.state.data) ? RUN_POLL_INTERVAL_MS : false),
102
+ })
103
+ const resumedRun = runQuery.data?.slot === slot ? runQuery.data : undefined
104
+ const resolvedReturnTo = returnTo ?? connectorConnectionReturnTo()
105
+
106
+ const connectMutation = useConnectConnector({ connectorId, slot, returnTo: resolvedReturnTo })
107
+ const reauthorizeMutation = useReauthorizeConnector({
108
+ connectorId,
109
+ connectionId: connection?.id ?? "",
110
+ returnTo: resolvedReturnTo,
111
+ })
112
+ const selectMutation = useSelectConnectorAccount({
113
+ connectorId,
114
+ runId: resumedRun?.id ?? "",
115
+ })
116
+ const disconnectMutation = useDisconnectConnector({
117
+ connectorId,
118
+ connectionId: connection?.id ?? "",
119
+ })
120
+ const revokeMutation = useRevokeConnector({
121
+ connectorId,
122
+ connectionId: connection?.id ?? "",
123
+ })
124
+
125
+ const refreshConnectionsAndConsumeCallback = useCallback(
126
+ async (
127
+ expectedCallback?: ConnectorConnectionCallback,
128
+ canConsume: () => boolean = () => true
129
+ ): Promise<void> => {
130
+ const result = await connectionsQuery.refetch()
131
+ if (result.error || !expectedCallback || !canConsume()) return
132
+ if (!result.data?.some((candidate) => candidate.slot === slot)) return
133
+
134
+ clearConnectorConnectionCallback(expectedCallback)
135
+ setCallback((current) =>
136
+ sameConnectorConnectionCallback(current, expectedCallback) ? null : current
137
+ )
138
+ },
139
+ [connectionsQuery.refetch, slot]
140
+ )
141
+
142
+ const completedRunId = resumedRun?.status === "succeeded" ? resumedRun.id : null
143
+ useEffect(() => {
144
+ if (!completedRunId || !callback) return
145
+ let active = true
146
+
147
+ void refreshConnectionsAndConsumeCallback(callback, () => active)
148
+
149
+ return () => {
150
+ active = false
151
+ }
152
+ }, [callback, completedRunId, refreshConnectionsAndConsumeCallback])
153
+
154
+ function connect(): Promise<void> {
155
+ if (connectInFlightRef.current) return connectInFlightRef.current
156
+ if (!canConnect) return Promise.resolve()
157
+
158
+ resetError()
159
+ const operation = (async () => {
160
+ const started =
161
+ resumedRun?.kind === "reauthorize" || connection?.status === "needs_reauthorization"
162
+ ? await reauthorizeMutation.mutateAsync()
163
+ : await connectMutation.mutateAsync()
164
+ redirectToAuthorization(started.authorizationUrl)
165
+ })()
166
+ connectInFlightRef.current = operation
167
+ operation.then(clearConnectInFlight, clearConnectInFlight)
168
+ return operation
169
+
170
+ function clearConnectInFlight(): void {
171
+ if (connectInFlightRef.current === operation) connectInFlightRef.current = null
172
+ }
173
+ }
174
+
175
+ async function selectAccount(
176
+ accountId: string,
177
+ options: ConnectorAccountSelectionOptions = {}
178
+ ): Promise<void> {
179
+ if (resumedRun?.status !== "waiting" || resumedRun.waitingFor !== "account_selection") {
180
+ throw new Error("[SixbClient] No connector account selection is currently pending.")
181
+ }
182
+ await selectMutation.mutateAsync({ accountId, replace: options.replace })
183
+ }
184
+
185
+ async function disconnect(): Promise<void> {
186
+ if (!connection) {
187
+ throw new Error("[SixbClient] Connector connection is unavailable.")
188
+ }
189
+ await disconnectMutation.mutateAsync()
190
+ }
191
+
192
+ async function revoke(): Promise<void> {
193
+ if (!connection) {
194
+ throw new Error("[SixbClient] Connector connection is unavailable.")
195
+ }
196
+ await revokeMutation.mutateAsync()
197
+ }
198
+
199
+ async function refresh(): Promise<void> {
200
+ let completedCallback: ConnectorConnectionCallback | undefined
201
+ if (callbackRunId !== null) {
202
+ const runResult = await runQuery.refetch()
203
+ if (
204
+ !runResult.error &&
205
+ runResult.data?.slot === slot &&
206
+ runResult.data.status === "succeeded" &&
207
+ sameConnectorConnectionCallback(callback, {
208
+ connectorId,
209
+ runId: runResult.data.id,
210
+ })
211
+ ) {
212
+ completedCallback = callback ?? undefined
213
+ }
214
+ }
215
+ await refreshConnectionsAndConsumeCallback(completedCallback)
216
+ }
217
+
218
+ function dismiss(): void {
219
+ if (!callback) return
220
+ clearConnectorConnectionCallback(callback)
221
+ setCallback(null)
222
+ resetError()
223
+ }
224
+
225
+ function resetError(): void {
226
+ connectMutation.reset()
227
+ reauthorizeMutation.reset()
228
+ selectMutation.reset()
229
+ disconnectMutation.reset()
230
+ revokeMutation.reset()
231
+ }
232
+
233
+ const status = connectionStatus({
234
+ callbackRunId,
235
+ connectionsPending: connectionsQuery.isPending,
236
+ connectionsError: connectionsQuery.error,
237
+ runPending: runQuery.isPending,
238
+ runError: runQuery.error,
239
+ run: resumedRun,
240
+ connection,
241
+ })
242
+ const mutationPending =
243
+ connectMutation.isPending ||
244
+ reauthorizeMutation.isPending ||
245
+ selectMutation.isPending ||
246
+ disconnectMutation.isPending ||
247
+ revokeMutation.isPending
248
+ const canConnect = connectorCanConnect({
249
+ status,
250
+ connectionsError: connectionsQuery.error,
251
+ runError: runQuery.error,
252
+ run: resumedRun,
253
+ connection,
254
+ mutationPending,
255
+ })
256
+
257
+ return {
258
+ status,
259
+ connection,
260
+ accounts: accountSelection(resumedRun),
261
+ error:
262
+ mutationFailure("connect", connectMutation.error) ??
263
+ mutationFailure("connect", reauthorizeMutation.error) ??
264
+ mutationFailure("select_account", selectMutation.error) ??
265
+ mutationFailure("disconnect", disconnectMutation.error) ??
266
+ mutationFailure("revoke", revokeMutation.error) ??
267
+ runFailure(callbackRunId, resumedRun, runQuery.error) ??
268
+ mutationFailure("load", connectionsQuery.error),
269
+ canConnect,
270
+ isPending: status === "loading" || status === "authorizing" || mutationPending,
271
+ selectedAccountId: selectMutation.variables?.accountId,
272
+ connect,
273
+ selectAccount,
274
+ disconnect,
275
+ revoke,
276
+ refresh,
277
+ dismiss,
278
+ resetError,
279
+ }
280
+ }
281
+
282
+ export function isConnectorReplacementRequired(error: unknown): boolean {
283
+ if (isSixbApiError(error)) return error.code === "connector.replacement_required"
284
+ return (
285
+ typeof error === "object" &&
286
+ error !== null &&
287
+ "code" in error &&
288
+ error.code === "connector.replacement_required"
289
+ )
290
+ }
291
+
292
+ function connectorCanConnect(input: {
293
+ readonly status: ConnectorConnectionStatus
294
+ readonly connectionsError: Error | null
295
+ readonly runError: Error | null
296
+ readonly run: ConnectorConnectionRun | undefined
297
+ readonly connection: ConnectorConnection | undefined
298
+ readonly mutationPending: boolean
299
+ }): boolean {
300
+ if (input.mutationPending || input.connectionsError || input.runError) return false
301
+ if (input.status === "disconnected" || input.status === "needs_reauthorization") return true
302
+ const run = input.run
303
+ if (input.status !== "error" || !run || !isRunTerminal(run)) return false
304
+ if (run.kind === "reauthorize") return input.connection !== undefined
305
+ return input.connection?.status !== "connected"
306
+ }
307
+
308
+ function connectionStatus(input: {
309
+ readonly callbackRunId: string | null
310
+ readonly connectionsPending: boolean
311
+ readonly connectionsError: Error | null
312
+ readonly runPending: boolean
313
+ readonly runError: Error | null
314
+ readonly run: ConnectorConnectionRun | undefined
315
+ readonly connection: ConnectorConnection | undefined
316
+ }): ConnectorConnectionStatus {
317
+ const { run } = input
318
+ if (run?.status === "waiting" && run.waitingFor === "account_selection") {
319
+ return "selecting_account"
320
+ }
321
+ if (input.callbackRunId !== null) {
322
+ if (
323
+ input.runError ||
324
+ run?.status === "failed" ||
325
+ run?.status === "cancelled" ||
326
+ run?.status === "expired"
327
+ ) {
328
+ return "error"
329
+ }
330
+ if (
331
+ input.runPending ||
332
+ run?.status === "waiting" ||
333
+ run?.status === "running" ||
334
+ run?.status === "succeeded"
335
+ ) {
336
+ return "authorizing"
337
+ }
338
+ }
339
+ if (input.connectionsError) return "error"
340
+ if (input.connectionsPending) return "loading"
341
+ if (input.connection?.status === "connected") return "connected"
342
+ if (input.connection?.status === "needs_reauthorization") return "needs_reauthorization"
343
+ return "disconnected"
344
+ }
345
+
346
+ function accountSelection(run: ConnectorConnectionRun | undefined): readonly ConnectorAccount[] {
347
+ if (run?.status !== "waiting" || run.waitingFor !== "account_selection") return []
348
+ return run.accounts
349
+ }
350
+
351
+ function mutationFailure(
352
+ operation: ConnectorConnectionOperation,
353
+ cause: unknown
354
+ ): ConnectorConnectionFailure | null {
355
+ return cause ? { operation, cause } : null
356
+ }
357
+
358
+ function runFailure(
359
+ callbackRunId: string | null,
360
+ run: ConnectorConnectionRun | undefined,
361
+ queryError: Error | null
362
+ ): ConnectorConnectionFailure | null {
363
+ if (callbackRunId === null) return null
364
+ if (queryError) return { operation: "resume", cause: queryError }
365
+ if (run?.status === "failed") return { operation: "resume", cause: run.error }
366
+ if (run?.status === "cancelled") {
367
+ return {
368
+ operation: "resume",
369
+ cause: new Error("[SixbClient] Connector authorization was cancelled."),
370
+ }
371
+ }
372
+ if (run?.status === "expired") {
373
+ return {
374
+ operation: "resume",
375
+ cause: new Error("[SixbClient] Connector authorization expired before completion."),
376
+ }
377
+ }
378
+ return null
379
+ }
380
+
381
+ function isRunInProgress(run: ConnectorConnectionRun | undefined): boolean {
382
+ return (
383
+ run?.status === "running" ||
384
+ (run?.status === "waiting" && run.waitingFor === "provider_authorization")
385
+ )
386
+ }
387
+
388
+ function isRunTerminal(run: ConnectorConnectionRun | undefined): boolean {
389
+ return run?.status === "failed" || run?.status === "cancelled" || run?.status === "expired"
390
+ }
391
+
392
+ function sameConnectorConnectionCallback(
393
+ left: ConnectorConnectionCallback | null,
394
+ right: ConnectorConnectionCallback
395
+ ): boolean {
396
+ return left?.connectorId === right.connectorId && left.runId === right.runId
397
+ }
398
+
399
+ export function readConnectorConnectionCallback(
400
+ href: string | undefined = globalThis.location?.href
401
+ ): ConnectorConnectionCallback | null {
402
+ if (!href) return null
403
+ const url = new URL(href)
404
+ const connectorId = url.searchParams.get(CONNECTOR_CALLBACK_CONNECTOR_PARAM)?.trim()
405
+ const runId = url.searchParams.get(CONNECTOR_CALLBACK_RUN_PARAM)?.trim()
406
+ return connectorId && runId ? { connectorId, runId } : null
407
+ }
408
+
409
+ export function connectorConnectionReturnTo(
410
+ href: string | undefined = globalThis.location?.href
411
+ ): string {
412
+ if (!href) return ""
413
+ return withoutConnectorConnectionCallback(href).toString()
414
+ }
415
+
416
+ function clearConnectorConnectionCallback(expected: ConnectorConnectionCallback): void {
417
+ const href = globalThis.location?.href
418
+ if (!href || !globalThis.history) return
419
+ const current = readConnectorConnectionCallback(href)
420
+ if (current?.connectorId !== expected.connectorId || current.runId !== expected.runId) {
421
+ return
422
+ }
423
+ const url = withoutConnectorConnectionCallback(href)
424
+ globalThis.history.replaceState(
425
+ globalThis.history.state,
426
+ "",
427
+ `${url.pathname}${url.search}${url.hash}`
428
+ )
429
+ }
430
+
431
+ function withoutConnectorConnectionCallback(href: string): URL {
432
+ const url = new URL(href)
433
+ url.searchParams.delete(CONNECTOR_CALLBACK_CONNECTOR_PARAM)
434
+ url.searchParams.delete(CONNECTOR_CALLBACK_RUN_PARAM)
435
+ return url
436
+ }
437
+
438
+ function redirectToAuthorization(authorizationUrl: string): void {
439
+ if (!globalThis.location) {
440
+ throw new Error("[SixbClient] Connector authorization requires a browser.")
441
+ }
442
+ globalThis.location.assign(authorizationUrl)
443
+ }
@@ -0,0 +1,12 @@
1
+ export {
2
+ type ConnectorAccountSelectionOptions,
3
+ type ConnectorConnectionFailure,
4
+ type ConnectorConnectionOperation,
5
+ type ConnectorConnectionStatus,
6
+ isConnectorReplacementRequired,
7
+ type UseConnectorConnectionOptions,
8
+ type UseConnectorConnectionResult,
9
+ useConnectorConnection,
10
+ } from "./connection"
11
+ export * from "./mutations"
12
+ export * from "./queries"