@sixb/client 0.2.1 → 0.2.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 (84) hide show
  1. package/dist/artifact-live.d.ts +31 -0
  2. package/dist/artifact-live.d.ts.map +1 -0
  3. package/dist/artifact-live.js +67 -0
  4. package/dist/artifact-live.js.map +10 -0
  5. package/dist/browser.d.ts +5 -0
  6. package/dist/browser.d.ts.map +1 -1
  7. package/dist/browser.js +38 -17
  8. package/dist/browser.js.map +3 -3
  9. package/dist/{chunk-j9t5h44d.js → chunk-15ynvne0.js} +40 -28
  10. package/dist/{chunk-j9t5h44d.js.map → chunk-15ynvne0.js.map} +4 -4
  11. package/dist/{chunk-0p42gyb5.js → chunk-90q7wa43.js} +30 -21
  12. package/dist/chunk-90q7wa43.js.map +17 -0
  13. package/dist/{chunk-rrexv1gk.js → chunk-bgpzb1fn.js} +6 -6
  14. package/dist/{chunk-rrexv1gk.js.map → chunk-bgpzb1fn.js.map} +1 -1
  15. package/dist/{chunk-hkn0keqj.js → chunk-br10prhs.js} +4 -4
  16. package/dist/{chunk-hkn0keqj.js.map → chunk-br10prhs.js.map} +1 -1
  17. package/dist/chunk-hj4h6hw6.js +827 -0
  18. package/dist/chunk-hj4h6hw6.js.map +18 -0
  19. package/dist/{chunk-3kfn00we.js → chunk-ktqfenfd.js} +43 -11
  20. package/dist/chunk-ktqfenfd.js.map +10 -0
  21. package/dist/{chunk-r50kxqa5.js → chunk-seeyb9k9.js} +8 -6
  22. package/dist/{chunk-r50kxqa5.js.map → chunk-seeyb9k9.js.map} +2 -2
  23. package/dist/{chunk-m2rmbshc.js → chunk-y9mhb8x4.js} +3 -1
  24. package/dist/chunk-y9mhb8x4.js.map +10 -0
  25. package/dist/{chunk-k2na62sa.js → chunk-zerhr00d.js} +155 -832
  26. package/dist/chunk-zerhr00d.js.map +10 -0
  27. package/dist/client-authority.d.ts +11 -0
  28. package/dist/client-authority.d.ts.map +1 -1
  29. package/dist/connectors/connection.d.ts +8 -3
  30. package/dist/connectors/connection.d.ts.map +1 -1
  31. package/dist/connectors/mutations.d.ts +4 -0
  32. package/dist/connectors/mutations.d.ts.map +1 -1
  33. package/dist/connectors/queries.d.ts +98 -0
  34. package/dist/connectors/queries.d.ts.map +1 -1
  35. package/dist/events-builder.d.ts +2 -0
  36. package/dist/events-builder.d.ts.map +1 -1
  37. package/dist/events-provider.d.ts.map +1 -1
  38. package/dist/events-transport.d.ts.map +1 -1
  39. package/dist/file.d.ts +8 -0
  40. package/dist/file.d.ts.map +1 -1
  41. package/dist/generated/@tanstack/react-query.gen.d.ts +1439 -234
  42. package/dist/generated/@tanstack/react-query.gen.d.ts.map +1 -1
  43. package/dist/generated/index.d.ts +2 -2
  44. package/dist/generated/index.d.ts.map +1 -1
  45. package/dist/generated/sdk.gen.d.ts +85 -5
  46. package/dist/generated/sdk.gen.d.ts.map +1 -1
  47. package/dist/generated/types.gen.d.ts +2717 -128
  48. package/dist/generated/types.gen.d.ts.map +1 -1
  49. package/dist/hooks.js +306 -57
  50. package/dist/hooks.js.map +7 -7
  51. package/dist/index.js +88 -56
  52. package/dist/index.js.map +1 -1
  53. package/dist/logs.js +6 -5
  54. package/dist/logs.js.map +1 -1
  55. package/dist/models.d.ts +5 -2
  56. package/dist/models.d.ts.map +1 -1
  57. package/dist/models.js +36 -6
  58. package/dist/models.js.map +1 -1
  59. package/dist/query.js +6 -5
  60. package/dist/query.js.map +1 -1
  61. package/dist/users-hooks.d.ts.map +1 -1
  62. package/dist/ws-socket.d.ts +17 -2
  63. package/dist/ws-socket.d.ts.map +1 -1
  64. package/package.json +8 -2
  65. package/src/artifact-live.ts +97 -0
  66. package/src/browser.ts +43 -5
  67. package/src/client-authority.ts +21 -0
  68. package/src/connectors/connection.ts +34 -12
  69. package/src/connectors/mutations.ts +8 -2
  70. package/src/connectors/queries.ts +6 -2
  71. package/src/events-builder.ts +9 -8
  72. package/src/events-provider.ts +13 -0
  73. package/src/events-transport.ts +3 -0
  74. package/src/file.ts +17 -0
  75. package/src/generated/@tanstack/react-query.gen.ts +458 -16
  76. package/src/generated/index.ts +90 -6
  77. package/src/generated/sdk.gen.ts +360 -11
  78. package/src/generated/types.gen.ts +3009 -227
  79. package/src/models.ts +6 -2
  80. package/src/ws-socket.ts +64 -10
  81. package/dist/chunk-0p42gyb5.js.map +0 -17
  82. package/dist/chunk-3kfn00we.js.map +0 -10
  83. package/dist/chunk-k2na62sa.js.map +0 -19
  84. package/dist/chunk-m2rmbshc.js.map +0 -10
@@ -0,0 +1,97 @@
1
+ /**
2
+ * React-free transport for `/ws/artifacts`, where artifacts are edited live: one reconnecting
3
+ * socket that carries the messages of every artifact a page holds. What each artifact does with
4
+ * them, its Yjs document and its awareness, is the caller's: this only connects, says when the
5
+ * server is ready for `join`, and hands each message on.
6
+ */
7
+ import {
8
+ ARTIFACT_LIVE_ROUTE,
9
+ type ArtifactLiveClientMessage,
10
+ type ArtifactLiveServerMessage,
11
+ } from "@sixb/core/artifacts/live/protocol"
12
+ import type { Client } from "./generated/client"
13
+ import {
14
+ createReconnectingSocket,
15
+ createSixbWebSocketUrl,
16
+ type ReconnectingSocketState,
17
+ } from "./ws-socket"
18
+
19
+ /** The first wait before a reconnect, and the longest: it doubles until a connection is ready. */
20
+ const RECONNECT_DELAY_MS = 500
21
+ const MAX_RECONNECT_DELAY_MS = 10_000
22
+
23
+ export interface ArtifactLiveSocketOptions {
24
+ /** The client whose API and credential the socket uses. Defaults to the package's shared client. */
25
+ readonly client?: Client
26
+ readonly reconnectDelayMs?: number
27
+ readonly maxReconnectDelayMs?: number
28
+ /**
29
+ * The server said `connected`: it takes `join` now. Called again after every reconnect, where
30
+ * every artifact held has to join again.
31
+ */
32
+ readonly onConnected: () => void
33
+ readonly onMessage: (message: ArtifactLiveServerMessage) => void
34
+ readonly onStateChange?: (state: ReconnectingSocketState) => void
35
+ readonly onError?: (message: string) => void
36
+ }
37
+
38
+ export interface ArtifactLiveSocket {
39
+ /** Sends a message on the connection open now; false while there is none. */
40
+ send(message: ArtifactLiveClientMessage): boolean
41
+ close(): void
42
+ }
43
+
44
+ /** Opens `/ws/artifacts`, and keeps it open, reconnecting with backoff, until it is closed. */
45
+ export function createArtifactLiveSocket(options: ArtifactLiveSocketOptions): ArtifactLiveSocket {
46
+ const socket = createReconnectingSocket({
47
+ url: createSixbWebSocketUrl(ARTIFACT_LIVE_ROUTE, options.client?.getConfig().baseUrl),
48
+ client: options.client,
49
+ // A shared link's guest watches the artifacts its objects hold.
50
+ sharedAccess: true,
51
+ reconnectDelayMs: options.reconnectDelayMs ?? RECONNECT_DELAY_MS,
52
+ maxReconnectDelayMs: options.maxReconnectDelayMs ?? MAX_RECONNECT_DELAY_MS,
53
+ readyWhen: (data) => parseArtifactLiveMessage(data)?.type === "connected",
54
+ readyTimeoutMessage: "[SixbClient] The live artifacts socket did not say it was connected.",
55
+ connectionErrorMessage: "[SixbClient] The live artifacts socket could not connect.",
56
+ onMessage: (data) => {
57
+ const message = parseArtifactLiveMessage(data)
58
+ if (!message) return
59
+
60
+ if (message.type === "connected") options.onConnected()
61
+ else options.onMessage(message)
62
+ },
63
+ ...(options.onError ? { onError: options.onError } : {}),
64
+ ...(options.onStateChange ? { onStateChange: options.onStateChange } : {}),
65
+ })
66
+
67
+ return { send: (message) => socket.send(message), close: () => socket.close() }
68
+ }
69
+
70
+ const SERVER_MESSAGES: ReadonlySet<string> = new Set([
71
+ "connected",
72
+ "joined",
73
+ "sync",
74
+ "awareness",
75
+ "status",
76
+ "access",
77
+ "left",
78
+ "error",
79
+ ])
80
+
81
+ /** A message the server sent; null for one that is not JSON, or of a type it never sends. */
82
+ function parseArtifactLiveMessage(data: unknown): ArtifactLiveServerMessage | null {
83
+ if (typeof data !== "string") return null
84
+
85
+ let parsed: unknown
86
+ try {
87
+ parsed = JSON.parse(data)
88
+ } catch {
89
+ return null
90
+ }
91
+
92
+ if (typeof parsed !== "object" || parsed === null) return null
93
+ const type = (parsed as { type?: unknown }).type
94
+ return typeof type === "string" && SERVER_MESSAGES.has(type)
95
+ ? (parsed as ArtifactLiveServerMessage)
96
+ : null
97
+ }
package/src/browser.ts CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  assertSharedAccessGrantId,
10
10
  getClientSharedGrantId,
11
11
  markClientSharedAuthority,
12
+ onClientSharedAccessEnded,
12
13
  } from "./client-authority"
13
14
  import { client } from "./generated/client.gen"
14
15
 
@@ -34,6 +35,11 @@ const SESSION_ACTIVITY_HEADER_VALUE = "1"
34
35
  const SESSION_ACTIVITY_WINDOW_MS = 5 * 60_000
35
36
  const SESSION_ACTIVITY_EVENT_TYPES = ["pointerdown", "keydown", "touchstart"] as const
36
37
  const SESSION_ACTIVITY_LISTENER_OPTIONS = { capture: true, passive: true } as const
38
+ /**
39
+ * How often an open, visible shared page renews its session: well within the server's inactivity
40
+ * window, so a visitor who only watches, through a meeting, keeps it.
41
+ */
42
+ const SHARED_SESSION_KEEPALIVE_MS = 2 * 60_000
37
43
 
38
44
  export interface SixbBrowserRuntimeConfig {
39
45
  readonly api: {
@@ -63,6 +69,11 @@ export interface SixbBrowserClientOptions {
63
69
  export interface SixbSharedBrowserClientOptions {
64
70
  readonly grantId: string
65
71
  readonly fetch?: typeof fetch
72
+ /**
73
+ * Called when the session ends while the page is open: a request refused as unauthenticated, or
74
+ * a live socket closed because the link was revoked or the session expired.
75
+ */
76
+ readonly onEnded?: () => void
66
77
  }
67
78
 
68
79
  export type SixbSharedAccessSession = ExchangeSharedAccessResponse
@@ -226,14 +237,21 @@ export function configureSixbSharedBrowserClient(
226
237
  fetch: options.fetch,
227
238
  })
228
239
 
229
- const disposeActivity = installVisibleSessionActivity()
240
+ // A shared link's visitor may only watch, as a canvas reviewed live through a meeting: the page
241
+ // open and visible is their activity. A hidden page lets the session lapse.
242
+ const disposeActivity = installVisibleSessionActivity({ visibleIsActivity: true })
230
243
  const responseInterceptorId = client.interceptors.response.use((response) => {
231
244
  const responseCsrfToken = response.headers.get(SIXB_CSRF_TOKEN_RESPONSE_HEADER_NAME)
232
245
  if (responseCsrfToken) csrfToken = responseCsrfToken
233
- if (response.status === 401) csrfToken = null
246
+ if (response.status === 401) {
247
+ csrfToken = null
248
+ options.onEnded?.()
249
+ }
234
250
  return response
235
251
  })
252
+ onClientSharedAccessEnded(client, options.onEnded ?? null)
236
253
 
254
+ let established = false
237
255
  const acceptSession = (session: SixbSharedAccessSession): SixbSharedAccessSession => {
238
256
  try {
239
257
  assertSharedAccessSession(session, options.grantId)
@@ -242,9 +260,17 @@ export function configureSixbSharedBrowserClient(
242
260
  throw error
243
261
  }
244
262
  csrfToken = session.csrfToken
263
+ established = true
245
264
  return session
246
265
  }
247
266
 
267
+ // A page that sends nothing still renews its session while visible. Its CSRF token stays meanwhile,
268
+ // so nothing in flight goes without it.
269
+ const keepAlive = setInterval(() => {
270
+ if (!established || browserDocumentVisibility() !== "visible") return
271
+ void getSharedSession(options.grantId).then(acceptSession, () => undefined)
272
+ }, SHARED_SESSION_KEEPALIVE_MS)
273
+
248
274
  const controller: SixbSharedBrowserClientController = {
249
275
  grantId: options.grantId,
250
276
  setCsrfToken(token) {
@@ -275,8 +301,10 @@ export function configureSixbSharedBrowserClient(
275
301
  disposed = true
276
302
  stopSixbActivityCapture()
277
303
  csrfToken = null
304
+ clearInterval(keepAlive)
278
305
  disposeActivity()
279
306
  client.interceptors.response.eject(responseInterceptorId)
307
+ onClientSharedAccessEnded(client, null)
280
308
  if (activeBrowserController === controller) {
281
309
  activeBrowserController = null
282
310
  client.setConfig({
@@ -294,7 +322,18 @@ export function configureSixbSharedBrowserClient(
294
322
  return controller
295
323
  }
296
324
 
297
- function installVisibleSessionActivity(): () => void {
325
+ function browserDocumentVisibility(): DocumentVisibilityState | null {
326
+ return typeof document === "undefined" ? null : document.visibilityState
327
+ }
328
+
329
+ /**
330
+ * Marks the requests a person's activity makes: those sent within five minutes of their last
331
+ * pointer, key or touch on the visible page, or, with `visibleIsActivity`, any sent while it is
332
+ * visible.
333
+ */
334
+ function installVisibleSessionActivity(
335
+ options: { readonly visibleIsActivity?: boolean } = {}
336
+ ): () => void {
298
337
  const browserDocument = typeof document === "undefined" ? null : document
299
338
  let lastActivityAt = browserDocument?.visibilityState === "visible" ? Date.now() : null
300
339
  const recordVisibleActivity = () => {
@@ -317,8 +356,7 @@ function installVisibleSessionActivity(): () => void {
317
356
  lastActivityAt === null ? Number.POSITIVE_INFINITY : Date.now() - lastActivityAt
318
357
  const hasRecentVisibleActivity =
319
358
  browserDocument?.visibilityState === "visible" &&
320
- activityAge >= 0 &&
321
- activityAge < SESSION_ACTIVITY_WINDOW_MS
359
+ (options.visibleIsActivity || (activityAge >= 0 && activityAge < SESSION_ACTIVITY_WINDOW_MS))
322
360
 
323
361
  if (hasRecentVisibleActivity) {
324
362
  request.headers.set(SESSION_ACTIVITY_HEADER_NAME, SESSION_ACTIVITY_HEADER_VALUE)
@@ -2,11 +2,21 @@ import type { Client } from "./generated/client"
2
2
  import type { SixbSessionOptions } from "./session"
3
3
 
4
4
  const sharedAuthorityClients = new WeakMap<Client, string>()
5
+ const sharedEndedHandlers = new WeakMap<Client, () => void>()
5
6
  const sessionAuthorityClients = new WeakMap<Client, SixbSessionOptions>()
6
7
 
7
8
  export const SHARED_ACCESS_REALTIME_UNAVAILABLE =
8
9
  "Live updates are unavailable during shared access."
9
10
 
11
+ /** Why a shared link's live socket closed for good: the link was revoked, or its session ended. */
12
+ export const SHARED_ACCESS_ENDED = "This shared link has ended."
13
+
14
+ /**
15
+ * The code the server closes a shared link's socket with once its session ended. Reconnecting
16
+ * would be refused, so the socket stops.
17
+ */
18
+ export const SHARED_ACCESS_ENDED_CLOSE_CODE = 4401
19
+
10
20
  export function assertSharedAccessGrantId(grantId: unknown): asserts grantId is string {
11
21
  if (
12
22
  typeof grantId !== "string" ||
@@ -53,3 +63,14 @@ export function markClientSessionAuthority(
53
63
  export function getClientSessionAuthority(client: Client): SixbSessionOptions | null {
54
64
  return sessionAuthorityClients.get(client) ?? null
55
65
  }
66
+
67
+ /** Who hears that a shared client's session ended while the page was open; `null` stops it. */
68
+ export function onClientSharedAccessEnded(client: Client, handler: (() => void) | null): void {
69
+ if (handler) sharedEndedHandlers.set(client, handler)
70
+ else sharedEndedHandlers.delete(client)
71
+ }
72
+
73
+ /** Says that a shared client's session ended: its link was revoked, or the session expired. */
74
+ export function endClientSharedAccess(client: Client): void {
75
+ sharedEndedHandlers.get(client)?.()
76
+ }
@@ -32,8 +32,13 @@ interface ConnectorConnectionCallback {
32
32
 
33
33
  export interface UseConnectorConnectionOptions {
34
34
  readonly connectorId: string
35
- /** Stable application-defined role filled by this connection, for example `organic` or `ads`. */
36
- readonly slot: string
35
+ /**
36
+ * `"project"` (the default) for an account the project shares, `"me"` for the signed-in user's
37
+ * own account on a connector whose owners include `"user"`.
38
+ */
39
+ readonly owner?: "project" | "me"
40
+ /** Stable application-defined role filled by this connection. Defaults to `"default"`. */
41
+ readonly slot?: string
37
42
  /** Defaults to the current page while preserving unrelated query parameters and the hash. */
38
43
  readonly returnTo?: string
39
44
  }
@@ -90,7 +95,8 @@ export interface UseConnectorConnectionResult {
90
95
  */
91
96
  export function useConnectorConnection({
92
97
  connectorId,
93
- slot,
98
+ owner = "project",
99
+ slot = "default",
94
100
  returnTo,
95
101
  }: UseConnectorConnectionOptions): UseConnectorConnectionResult {
96
102
  const [callback, setCallback] = useState(readConnectorConnectionCallback)
@@ -106,13 +112,23 @@ export function useConnectorConnection({
106
112
  })
107
113
  const recoveryPending = callbackRunId === null && pendingRunsQuery.isPending
108
114
  const recoveryError = callbackRunId === null ? pendingRunsQuery.error : null
109
- const connectionsQuery = useConnectorConnections({ connectorId })
115
+ const ownerType = owner === "me" ? "user" : "project"
116
+ const fillsSlot = useCallback(
117
+ (candidate: { readonly owner: { readonly type: string }; readonly slot: string }) =>
118
+ candidate.owner.type === ownerType && candidate.slot === slot,
119
+ [ownerType, slot]
120
+ )
121
+ // A manager also sees other people's connections, so "me" asks the server for the caller's own.
122
+ const connectionsQuery = useConnectorConnections({
123
+ connectorId,
124
+ ...(owner === "me" ? { owner } : {}),
125
+ })
110
126
  const connection = useMemo(
111
- () => connectionsQuery.data?.find((candidate) => candidate.slot === slot),
112
- [connectionsQuery.data, slot]
127
+ () => connectionsQuery.data?.find(fillsSlot),
128
+ [connectionsQuery.data, fillsSlot]
113
129
  )
114
130
  const pendingRun = pendingRunsQuery.data?.find(
115
- (run) => run.slot === slot && !dismissedRunIds.includes(run.id)
131
+ (run) => fillsSlot(run) && !dismissedRunIds.includes(run.id)
116
132
  )
117
133
  useEffect(() => {
118
134
  if (
@@ -128,10 +144,15 @@ export function useConnectorConnection({
128
144
  runId: callbackRunId,
129
145
  refetchInterval: (query) => (isRunInProgress(query.state.data) ? RUN_POLL_INTERVAL_MS : false),
130
146
  })
131
- const resumedRun = runQuery.data?.slot === slot ? runQuery.data : undefined
147
+ const resumedRun = runQuery.data && fillsSlot(runQuery.data) ? runQuery.data : undefined
132
148
  const resolvedReturnTo = returnTo ?? connectorConnectionReturnTo()
133
149
 
134
- const connectMutation = useConnectConnector({ connectorId, slot, returnTo: resolvedReturnTo })
150
+ const connectMutation = useConnectConnector({
151
+ connectorId,
152
+ ...(owner === "me" ? { owner } : {}),
153
+ slot,
154
+ returnTo: resolvedReturnTo,
155
+ })
135
156
  const reauthorizeMutation = useReauthorizeConnector({
136
157
  connectorId,
137
158
  connectionId: connection?.id ?? "",
@@ -157,7 +178,7 @@ export function useConnectorConnection({
157
178
  ): Promise<void> => {
158
179
  const result = await connectionsQuery.refetch()
159
180
  if (result.error || !expectedCallback || !canConsume()) return
160
- if (!result.data?.some((candidate) => candidate.slot === slot)) return
181
+ if (!result.data?.some(fillsSlot)) return
161
182
 
162
183
  await queryClient.invalidateQueries({
163
184
  queryKey: listPendingConnectorConnectionRunsQueryKey({
@@ -172,7 +193,7 @@ export function useConnectorConnection({
172
193
  sameConnectorConnectionCallback(current, expectedCallback) ? null : current
173
194
  )
174
195
  },
175
- [connectionsQuery.refetch, slot, queryClient, connectorId, providerClient]
196
+ [connectionsQuery.refetch, fillsSlot, queryClient, connectorId, providerClient]
176
197
  )
177
198
 
178
199
  const completedRunId = resumedRun?.status === "succeeded" ? resumedRun.id : null
@@ -239,7 +260,8 @@ export function useConnectorConnection({
239
260
  const runResult = await runQuery.refetch()
240
261
  if (
241
262
  !runResult.error &&
242
- runResult.data?.slot === slot &&
263
+ runResult.data !== undefined &&
264
+ fillsSlot(runResult.data) &&
243
265
  runResult.data.status === "succeeded" &&
244
266
  sameConnectorConnectionCallback(callback, {
245
267
  connectorId,
@@ -36,6 +36,8 @@ export interface AddConnectorConnectionOptions<TContext = unknown>
36
36
  > {
37
37
  readonly connectorId: string
38
38
  readonly fromConnectionId: string
39
+ /** `"me"` adds the account as the signed-in user's own connection. Defaults to `"project"`. */
40
+ readonly owner?: "project" | "me"
39
41
  readonly slot: string
40
42
  /** hey-api client override. Defaults to the nearest SixbProvider client, then the global client. */
41
43
  readonly client?: Client
@@ -49,6 +51,7 @@ export function addConnectorConnectionMutationOptions<TContext = unknown>(
49
51
  const {
50
52
  connectorId,
51
53
  fromConnectionId,
54
+ owner,
52
55
  slot,
53
56
  client,
54
57
  queryClient,
@@ -67,7 +70,7 @@ export function addConnectorConnectionMutationOptions<TContext = unknown>(
67
70
  const { data } = await addConnectorConnection<true>({
68
71
  client,
69
72
  path,
70
- body: { slot: nonblank(slot, "slot") },
73
+ body: { ...(owner === undefined ? {} : { owner }), slot: nonblank(slot, "slot") },
71
74
  throwOnError: true,
72
75
  })
73
76
  return data
@@ -104,6 +107,8 @@ export interface ConnectConnectorOptions<TContext = unknown>
104
107
  "mutationFn"
105
108
  > {
106
109
  readonly connectorId: string
110
+ /** `"me"` connects the signed-in user's own account. Defaults to `"project"`. */
111
+ readonly owner?: "project" | "me"
107
112
  readonly slot: string
108
113
  readonly returnTo: string
109
114
  /** hey-api client override. Defaults to the nearest SixbProvider client, then the global client. */
@@ -113,7 +118,7 @@ export interface ConnectConnectorOptions<TContext = unknown>
113
118
  export function connectConnectorMutationOptions<TContext = unknown>(
114
119
  options: ConnectConnectorOptions<TContext>
115
120
  ): UseMutationOptions<StartConnectorConnectionRunResponse, Error, void, TContext> {
116
- const { connectorId, slot, returnTo, client, ...mutationOptions } = options
121
+ const { connectorId, owner, slot, returnTo, client, ...mutationOptions } = options
117
122
  const normalizedConnectorId = nonblank(connectorId, "connectorId")
118
123
  const normalizedSlot = nonblank(slot, "slot")
119
124
 
@@ -124,6 +129,7 @@ export function connectConnectorMutationOptions<TContext = unknown>(
124
129
  client,
125
130
  path: { connectorId: normalizedConnectorId },
126
131
  body: {
132
+ ...(owner === undefined ? {} : { owner }),
127
133
  slot: normalizedSlot,
128
134
  returnTo: resolveReturnTo(returnTo),
129
135
  },
@@ -33,13 +33,16 @@ export interface ConnectorConnectionsOptions
33
33
  "queryKey" | "queryFn"
34
34
  > {
35
35
  readonly connectorId: string
36
+ /** Only the project's connections, or only the signed-in user's own. Omitted, all the caller sees. */
37
+ readonly owner?: "project" | "me"
36
38
  /** hey-api client override. Defaults to the nearest SixbProvider client, then the global client. */
37
39
  readonly client?: Client
38
40
  }
39
41
 
40
42
  export function connectorConnectionsQueryOptions(options: ConnectorConnectionsOptions) {
41
- const { connectorId, client, ...queryOptionsInput } = options
43
+ const { connectorId, owner, client, ...queryOptionsInput } = options
42
44
  const path = { connectorId: nonblank(connectorId, "connectorId") }
45
+ const query = owner === undefined ? undefined : { owner }
43
46
 
44
47
  return queryOptions<
45
48
  ListConnectorConnectionsResponse,
@@ -48,11 +51,12 @@ export function connectorConnectionsQueryOptions(options: ConnectorConnectionsOp
48
51
  ConnectorConnectionsQueryKey
49
52
  >({
50
53
  ...queryOptionsInput,
51
- queryKey: listConnectorConnectionsQueryKey({ path }),
54
+ queryKey: listConnectorConnectionsQueryKey({ path, query }),
52
55
  queryFn: async ({ signal }) => {
53
56
  const { data } = await listConnectorConnections<true>({
54
57
  client,
55
58
  path,
59
+ query,
56
60
  signal,
57
61
  throwOnError: true,
58
62
  })
@@ -315,9 +315,11 @@ export interface EventSubscribeExecutor {
315
315
  */
316
316
  export function createWsSubscribeExecutor(options?: { client?: Client }): EventSubscribeExecutor {
317
317
  const transportClient = options?.client ?? generatedClient
318
- if (hasClientSharedAuthority(transportClient)) {
319
- return {
320
- subscribe(_filter, _handler, subscribeOptions) {
318
+
319
+ return {
320
+ subscribe(filter, handler, subscribeOptions) {
321
+ // A shared link's session follows its artifacts live, and nothing else.
322
+ if (hasClientSharedAuthority(transportClient) && filter.topic !== "artifacts") {
321
323
  subscribeOptions?.onError?.(SHARED_ACCESS_REALTIME_UNAVAILABLE)
322
324
  subscribeOptions?.onStateChange?.({
323
325
  connected: false,
@@ -325,12 +327,8 @@ export function createWsSubscribeExecutor(options?: { client?: Client }): EventS
325
327
  error: SHARED_ACCESS_REALTIME_UNAVAILABLE,
326
328
  })
327
329
  return () => undefined
328
- },
329
- }
330
- }
330
+ }
331
331
 
332
- return {
333
- subscribe(filter, handler, subscribeOptions) {
334
332
  const matches = buildEventPredicate(filter)
335
333
  const socket = createEventSocket({
336
334
  topic: filter.topic,
@@ -655,6 +653,8 @@ export interface SixbEventsApi {
655
653
  syncs(options?: SixbEventsClientOptions): EventsRunBuilder<SixbEventOfTopic<"syncs">>
656
654
  /** Member events. Reading them requires `can.view(project.users)`. */
657
655
  users(options?: SixbEventsClientOptions): EventsUsersBuilder<SixbEventOfTopic<"users">>
656
+ /** An artifact changed: each goes to whoever may read that artifact. */
657
+ artifacts(options?: SixbEventsClientOptions): EventsTopicBuilder<SixbEventOfTopic<"artifacts">>
658
658
  }
659
659
 
660
660
  function topicBuilder<TEvent extends SixbEvent>(
@@ -710,6 +710,7 @@ eventsApi.pipeline = (pipeline, options) => {
710
710
  eventsApi.schedules = (options) => topicBuilder("schedules", options)
711
711
  eventsApi.rules = (options) => topicBuilder("rules", options)
712
712
  eventsApi.datasets = (options) => topicBuilder("datasets", options)
713
+ eventsApi.artifacts = (options) => topicBuilder("artifacts", options)
713
714
  eventsApi.workflows = (options) => runBuilder("workflows", options)
714
715
  eventsApi.pipelines = (options) => runBuilder("pipelines", options)
715
716
  eventsApi.syncs = (options) => runBuilder("syncs", options)
@@ -9,9 +9,11 @@
9
9
  * back to a per-builder socket otherwise.
10
10
  */
11
11
  import { createContext, createElement, type ReactNode, useContext, useEffect, useMemo } from "react"
12
+ import { hasClientSharedAuthority, SHARED_ACCESS_REALTIME_UNAVAILABLE } from "./client-authority"
12
13
  import type { SixbEvent } from "./events"
13
14
  import { buildEventPredicate, type EventsFilterSpec } from "./events-builder"
14
15
  import { createEventSocket, type EventSocket, type EventSocketState } from "./events-transport"
16
+ import { client as generatedClient } from "./generated/client.gen"
15
17
 
16
18
  const DISCONNECTED: EventSocketState = { connected: false, reconnecting: false, error: null }
17
19
 
@@ -109,6 +111,17 @@ export function createEventsRegistry(
109
111
 
110
112
  return {
111
113
  register(filter, handler, registrationOptions) {
114
+ // A shared link's session follows its artifacts live, and nothing else.
115
+ if (hasClientSharedAuthority(generatedClient) && filter.topic !== "artifacts") {
116
+ registrationOptions?.onError?.(SHARED_ACCESS_REALTIME_UNAVAILABLE)
117
+ registrationOptions?.onStateChange?.({
118
+ connected: false,
119
+ reconnecting: false,
120
+ error: SHARED_ACCESS_REALTIME_UNAVAILABLE,
121
+ })
122
+ return () => undefined
123
+ }
124
+
112
125
  cancelPendingClose()
113
126
  const subscriber: Subscriber = {
114
127
  matches: buildEventPredicate(filter),
@@ -84,6 +84,9 @@ export function createEventSocket(options: EventSocketOptions): EventSocket {
84
84
  return createReconnectingSocket({
85
85
  url: createSixbEventsWebSocketUrl(options.baseUrl ?? options.client?.getConfig().baseUrl),
86
86
  client: options.client,
87
+ // A shared link's session receives its artifacts' events, and nothing else: its callers open
88
+ // the stream for those alone.
89
+ sharedAccess: true,
87
90
  reconnect: options.reconnect,
88
91
  reconnectDelayMs: options.reconnectDelayMs,
89
92
  readyTimeoutMs: options.handshakeTimeoutMs,
package/src/file.ts CHANGED
@@ -55,6 +55,23 @@ export function objectFileContentUrl(input: ObjectFileContentUrlInput): string {
55
55
  })
56
56
  }
57
57
 
58
+ /**
59
+ * A file's content URL, or a board preview's, as an `<img>`, a `<video>` or a download link loads
60
+ * it without the client: a shared client names its grant in the query, as `objectFileContentUrl`
61
+ * does, because such a request cannot send the header. The grant's HttpOnly session cookie stays
62
+ * the credential. Only those routes read the grant from the query: any other URL passed here is
63
+ * still refused to a shared link's visitor. Any other client's URL is unchanged.
64
+ */
65
+ export function withSharedAccess(url: string, client: SixbClient = sharedClient): string {
66
+ const grantId = getClientSharedGrantId(client)
67
+ if (grantId === null) return url
68
+
69
+ const absolute = /^[a-z][a-z0-9+.-]*:/i.test(url)
70
+ const shared = new URL(url, "http://sixb.invalid")
71
+ shared.searchParams.set("shareGrant", grantId)
72
+ return absolute ? shared.toString() : `${shared.pathname}${shared.search}${shared.hash}`
73
+ }
74
+
58
75
  export type SixbFileUploadStage =
59
76
  | "hash"
60
77
  | "create"