@sixb/client 0.1.7 → 0.1.8

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 (59) hide show
  1. package/dist/api.d.ts +5 -0
  2. package/dist/api.d.ts.map +1 -1
  3. package/dist/browser.d.ts +18 -1
  4. package/dist/browser.d.ts.map +1 -1
  5. package/dist/browser.js +180 -35
  6. package/dist/browser.js.map +3 -3
  7. package/dist/{chunk-dcebhkmz.js → chunk-0g4bg41z.js} +25 -5
  8. package/dist/chunk-0g4bg41z.js.map +17 -0
  9. package/dist/chunk-3gvmb0w6.js +23 -0
  10. package/dist/chunk-3gvmb0w6.js.map +10 -0
  11. package/dist/{chunk-h80qj1f8.js → chunk-cmfd585n.js} +17 -2
  12. package/dist/chunk-cmfd585n.js.map +10 -0
  13. package/dist/{chunk-r8p88mbg.js → chunk-n4160ht2.js} +103 -21
  14. package/dist/chunk-n4160ht2.js.map +19 -0
  15. package/dist/{chunk-p0xrjaz6.js → chunk-se1tydhh.js} +2 -2
  16. package/dist/{chunk-b3bfdm80.js → chunk-v8q8185t.js} +61 -6
  17. package/dist/chunk-v8q8185t.js.map +10 -0
  18. package/dist/{chunk-m4by7m5r.js → chunk-x6pk2xhn.js} +21 -4
  19. package/dist/chunk-x6pk2xhn.js.map +12 -0
  20. package/dist/client-authority.d.ts +6 -0
  21. package/dist/client-authority.d.ts.map +1 -0
  22. package/dist/events-builder.d.ts.map +1 -1
  23. package/dist/generated/@tanstack/react-query.gen.d.ts +395 -126
  24. package/dist/generated/@tanstack/react-query.gen.d.ts.map +1 -1
  25. package/dist/generated/index.d.ts +2 -2
  26. package/dist/generated/index.d.ts.map +1 -1
  27. package/dist/generated/sdk.gen.d.ts +25 -1
  28. package/dist/generated/sdk.gen.d.ts.map +1 -1
  29. package/dist/generated/types.gen.d.ts +362 -3
  30. package/dist/generated/types.gen.d.ts.map +1 -1
  31. package/dist/hooks.js +120 -6
  32. package/dist/hooks.js.map +3 -3
  33. package/dist/index.js +21 -6
  34. package/dist/index.js.map +1 -1
  35. package/dist/logs-builder.d.ts.map +1 -1
  36. package/dist/logs.js +5 -4
  37. package/dist/logs.js.map +1 -1
  38. package/dist/models.js +14 -2
  39. package/dist/models.js.map +1 -1
  40. package/dist/query.js +5 -4
  41. package/dist/query.js.map +1 -1
  42. package/dist/ws-socket.d.ts.map +1 -1
  43. package/package.json +2 -2
  44. package/src/api.ts +92 -3
  45. package/src/browser.ts +257 -48
  46. package/src/client-authority.ts +31 -0
  47. package/src/events-builder.ts +18 -1
  48. package/src/generated/@tanstack/react-query.gen.ts +229 -0
  49. package/src/generated/index.ts +36 -0
  50. package/src/generated/sdk.gen.ts +178 -12
  51. package/src/generated/types.gen.ts +402 -3
  52. package/src/logs-builder.ts +14 -1
  53. package/src/ws-socket.ts +11 -0
  54. package/dist/chunk-b3bfdm80.js.map +0 -10
  55. package/dist/chunk-dcebhkmz.js.map +0 -17
  56. package/dist/chunk-h80qj1f8.js.map +0 -10
  57. package/dist/chunk-m4by7m5r.js.map +0 -12
  58. package/dist/chunk-r8p88mbg.js.map +0 -19
  59. /package/dist/{chunk-p0xrjaz6.js.map → chunk-se1tydhh.js.map} +0 -0
package/src/browser.ts CHANGED
@@ -4,13 +4,27 @@ import {
4
4
  normalizeSixbApiBaseUrl,
5
5
  SIXB_CSRF_TOKEN_RESPONSE_HEADER_NAME,
6
6
  } from "./api"
7
+ import {
8
+ assertSharedAccessGrantId,
9
+ hasClientSharedAuthority,
10
+ markClientSharedAuthority,
11
+ } from "./client-authority"
7
12
  import { client } from "./generated/client.gen"
8
13
 
9
14
  export type { SixbApiErrorCode, SixbApiErrorInit } from "./api"
10
15
  export { isSixbApiError, SixbApiError } from "./api"
11
16
 
12
- import { getAuthSession } from "./generated/sdk.gen"
13
- import type { GetAuthSessionResponse } from "./generated/types.gen"
17
+ import {
18
+ exchangeSharedAccess,
19
+ getAuthSession,
20
+ getSharedAccessSession,
21
+ signOutSharedAccess,
22
+ } from "./generated/sdk.gen"
23
+ import type {
24
+ ExchangeSharedAccessResponse,
25
+ GetAuthSessionResponse,
26
+ SignOutSharedAccessResponse,
27
+ } from "./generated/types.gen"
14
28
 
15
29
  const SESSION_ACTIVITY_HEADER_NAME = "x-sixb-session-activity"
16
30
  const SESSION_ACTIVITY_HEADER_VALUE = "1"
@@ -45,6 +59,21 @@ export interface SixbBrowserClientOptions {
45
59
  readonly redirect?: (url: string) => void
46
60
  }
47
61
 
62
+ export interface SixbSharedBrowserClientOptions {
63
+ readonly grantId: string
64
+ readonly fetch?: typeof fetch
65
+ }
66
+
67
+ export type SixbSharedAccessSession = ExchangeSharedAccessResponse
68
+
69
+ export interface SixbSharedBrowserClientController extends SixbBrowserClientController {
70
+ readonly grantId: string
71
+ exchange(secret: string): Promise<SixbSharedAccessSession>
72
+ getSession(): Promise<SixbSharedAccessSession>
73
+ establish(secret: string | null): Promise<SixbSharedAccessSession>
74
+ signOut(): Promise<SignOutSharedAccessResponse>
75
+ }
76
+
48
77
  let activeBrowserController: SixbBrowserClientController | null = null
49
78
 
50
79
  declare global {
@@ -88,25 +117,6 @@ export function configureSixbBrowserClient(
88
117
  let csrfToken: string | null = null
89
118
  let disposed = false
90
119
  let redirectStarted = false
91
- const browserDocument = typeof document === "undefined" ? null : document
92
- let lastActivityAt = browserDocument?.visibilityState === "visible" ? Date.now() : null
93
-
94
- const recordVisibleActivity = () => {
95
- if (browserDocument?.visibilityState === "visible") {
96
- lastActivityAt = Date.now()
97
- }
98
- }
99
-
100
- if (browserDocument) {
101
- for (const type of SESSION_ACTIVITY_EVENT_TYPES) {
102
- browserDocument.addEventListener(
103
- type,
104
- recordVisibleActivity,
105
- SESSION_ACTIVITY_LISTENER_OPTIONS
106
- )
107
- }
108
- browserDocument.addEventListener("visibilitychange", recordVisibleActivity)
109
- }
110
120
 
111
121
  configureGeneratedSixbClient(client, {
112
122
  baseUrl: config.api.baseUrl,
@@ -115,21 +125,7 @@ export function configureSixbBrowserClient(
115
125
  csrfToken: () => csrfToken,
116
126
  },
117
127
  })
118
- const activityInterceptorId = client.interceptors.request.use((request) => {
119
- const activityAge =
120
- lastActivityAt === null ? Number.POSITIVE_INFINITY : Date.now() - lastActivityAt
121
- const hasRecentVisibleActivity =
122
- browserDocument?.visibilityState === "visible" &&
123
- activityAge >= 0 &&
124
- activityAge < SESSION_ACTIVITY_WINDOW_MS
125
-
126
- if (hasRecentVisibleActivity) {
127
- request.headers.set(SESSION_ACTIVITY_HEADER_NAME, SESSION_ACTIVITY_HEADER_VALUE)
128
- } else {
129
- request.headers.delete(SESSION_ACTIVITY_HEADER_NAME)
130
- }
131
- return request
132
- })
128
+ const disposeActivity = installVisibleSessionActivity()
133
129
  const authResponseInterceptorId = client.interceptors.response.use((response, request) => {
134
130
  const responseCsrfToken = response.headers.get(SIXB_CSRF_TOKEN_RESPONSE_HEADER_NAME)
135
131
  if (responseCsrfToken) {
@@ -185,19 +181,8 @@ export function configureSixbBrowserClient(
185
181
  if (disposed) return
186
182
  disposed = true
187
183
  csrfToken = null
188
- lastActivityAt = null
189
- client.interceptors.request.eject(activityInterceptorId)
184
+ disposeActivity()
190
185
  client.interceptors.response.eject(authResponseInterceptorId)
191
- if (browserDocument) {
192
- for (const type of SESSION_ACTIVITY_EVENT_TYPES) {
193
- browserDocument.removeEventListener(
194
- type,
195
- recordVisibleActivity,
196
- SESSION_ACTIVITY_LISTENER_OPTIONS
197
- )
198
- }
199
- browserDocument.removeEventListener("visibilitychange", recordVisibleActivity)
200
- }
201
186
  if (activeBrowserController === controller) {
202
187
  activeBrowserController = null
203
188
  client.setConfig({ auth: undefined, credentials: undefined })
@@ -209,6 +194,230 @@ export function configureSixbBrowserClient(
209
194
  return controller
210
195
  }
211
196
 
197
+ /**
198
+ * Configures the package singleton for one Share authority. Once established, ordinary generated
199
+ * SDK functions, object queries, and React hooks use the same client without a resource facade.
200
+ */
201
+ export function configureSixbSharedBrowserClient(
202
+ config: SixbBrowserRuntimeConfig,
203
+ options: SixbSharedBrowserClientOptions
204
+ ): SixbSharedBrowserClientController {
205
+ activeBrowserController?.dispose()
206
+ assertSharedAccessGrantId(options.grantId)
207
+
208
+ const previousConfig = client.getConfig()
209
+ const previousSharedAuthority = hasClientSharedAuthority(client)
210
+ let csrfToken: string | null = null
211
+ let disposed = false
212
+ configureGeneratedSixbClient(client, {
213
+ baseUrl: config.api.baseUrl,
214
+ auth: {
215
+ kind: "shared",
216
+ grantId: options.grantId,
217
+ csrfToken: () => csrfToken,
218
+ },
219
+ fetch: options.fetch,
220
+ })
221
+
222
+ const disposeActivity = installVisibleSessionActivity()
223
+ const responseInterceptorId = client.interceptors.response.use((response) => {
224
+ const responseCsrfToken = response.headers.get(SIXB_CSRF_TOKEN_RESPONSE_HEADER_NAME)
225
+ if (responseCsrfToken) csrfToken = responseCsrfToken
226
+ if (response.status === 401) csrfToken = null
227
+ return response
228
+ })
229
+
230
+ const acceptSession = (session: SixbSharedAccessSession): SixbSharedAccessSession => {
231
+ try {
232
+ assertSharedAccessSession(session, options.grantId)
233
+ } catch (error) {
234
+ csrfToken = null
235
+ throw error
236
+ }
237
+ csrfToken = session.csrfToken
238
+ return session
239
+ }
240
+
241
+ const controller: SixbSharedBrowserClientController = {
242
+ grantId: options.grantId,
243
+ setCsrfToken(token) {
244
+ csrfToken = token
245
+ },
246
+ getCsrfToken() {
247
+ return csrfToken
248
+ },
249
+ async exchange(secret) {
250
+ assertSharedSecret(secret)
251
+ csrfToken = null
252
+ return acceptSession(await exchangeSharedSession(options.grantId, secret))
253
+ },
254
+ async getSession() {
255
+ csrfToken = null
256
+ return acceptSession(await getSharedSession(options.grantId))
257
+ },
258
+ async establish(secret) {
259
+ return secret === null ? await controller.getSession() : await controller.exchange(secret)
260
+ },
261
+ async signOut() {
262
+ const result = await signOutSharedSession(options.grantId)
263
+ csrfToken = null
264
+ return result
265
+ },
266
+ dispose() {
267
+ if (disposed) return
268
+ disposed = true
269
+ csrfToken = null
270
+ disposeActivity()
271
+ client.interceptors.response.eject(responseInterceptorId)
272
+ if (activeBrowserController === controller) {
273
+ activeBrowserController = null
274
+ client.setConfig({
275
+ auth: previousConfig.auth,
276
+ baseUrl: previousConfig.baseUrl,
277
+ credentials: previousConfig.credentials,
278
+ fetch: previousConfig.fetch,
279
+ })
280
+ markClientSharedAuthority(client, previousSharedAuthority)
281
+ }
282
+ },
283
+ }
284
+
285
+ activeBrowserController = controller
286
+ return controller
287
+ }
288
+
289
+ function installVisibleSessionActivity(): () => void {
290
+ const browserDocument = typeof document === "undefined" ? null : document
291
+ let lastActivityAt = browserDocument?.visibilityState === "visible" ? Date.now() : null
292
+ const recordVisibleActivity = () => {
293
+ if (browserDocument?.visibilityState === "visible") lastActivityAt = Date.now()
294
+ }
295
+
296
+ if (browserDocument) {
297
+ for (const type of SESSION_ACTIVITY_EVENT_TYPES) {
298
+ browserDocument.addEventListener(
299
+ type,
300
+ recordVisibleActivity,
301
+ SESSION_ACTIVITY_LISTENER_OPTIONS
302
+ )
303
+ }
304
+ browserDocument.addEventListener("visibilitychange", recordVisibleActivity)
305
+ }
306
+
307
+ const interceptorId = client.interceptors.request.use((request) => {
308
+ const activityAge =
309
+ lastActivityAt === null ? Number.POSITIVE_INFINITY : Date.now() - lastActivityAt
310
+ const hasRecentVisibleActivity =
311
+ browserDocument?.visibilityState === "visible" &&
312
+ activityAge >= 0 &&
313
+ activityAge < SESSION_ACTIVITY_WINDOW_MS
314
+
315
+ if (hasRecentVisibleActivity) {
316
+ request.headers.set(SESSION_ACTIVITY_HEADER_NAME, SESSION_ACTIVITY_HEADER_VALUE)
317
+ } else {
318
+ request.headers.delete(SESSION_ACTIVITY_HEADER_NAME)
319
+ }
320
+ return request
321
+ })
322
+
323
+ return () => {
324
+ lastActivityAt = null
325
+ client.interceptors.request.eject(interceptorId)
326
+ if (!browserDocument) return
327
+ for (const type of SESSION_ACTIVITY_EVENT_TYPES) {
328
+ browserDocument.removeEventListener(
329
+ type,
330
+ recordVisibleActivity,
331
+ SESSION_ACTIVITY_LISTENER_OPTIONS
332
+ )
333
+ }
334
+ browserDocument.removeEventListener("visibilitychange", recordVisibleActivity)
335
+ }
336
+ }
337
+
338
+ async function exchangeSharedSession(
339
+ grantId: string,
340
+ secret: string
341
+ ): Promise<SixbSharedAccessSession> {
342
+ const { data } = await exchangeSharedAccess({
343
+ path: { grantId },
344
+ body: { secret },
345
+ throwOnError: true,
346
+ })
347
+ return data
348
+ }
349
+
350
+ async function getSharedSession(grantId: string): Promise<SixbSharedAccessSession> {
351
+ const { data } = await getSharedAccessSession({
352
+ path: { grantId },
353
+ throwOnError: true,
354
+ })
355
+ return data
356
+ }
357
+
358
+ async function signOutSharedSession(grantId: string): Promise<SignOutSharedAccessResponse> {
359
+ const { data } = await signOutSharedAccess({
360
+ path: { grantId },
361
+ throwOnError: true,
362
+ })
363
+ return data
364
+ }
365
+
366
+ function assertSharedSecret(secret: unknown): asserts secret is string {
367
+ if (typeof secret !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(secret)) {
368
+ throw new Error("[SixbClient] Shared access secret is invalid.")
369
+ }
370
+ }
371
+
372
+ function assertSharedAccessSession(
373
+ session: unknown,
374
+ expectedGrantId: string
375
+ ): asserts session is SixbSharedAccessSession {
376
+ if (
377
+ !isRecord(session) ||
378
+ session.grantId !== expectedGrantId ||
379
+ !isSameOriginDestinationPath(session.destinationPath) ||
380
+ typeof session.expiresAt !== "string" ||
381
+ !Number.isFinite(Date.parse(session.expiresAt)) ||
382
+ typeof session.absoluteExpiresAt !== "string" ||
383
+ !Number.isFinite(Date.parse(session.absoluteExpiresAt)) ||
384
+ typeof session.csrfToken !== "string" ||
385
+ !/^[A-Za-z0-9_-]{43}$/.test(session.csrfToken)
386
+ ) {
387
+ throw new Error("[SixbClient] Shared access session response is invalid.")
388
+ }
389
+ }
390
+
391
+ function isSameOriginDestinationPath(value: unknown): value is string {
392
+ if (
393
+ typeof value !== "string" ||
394
+ value.length === 0 ||
395
+ value.length > 4_096 ||
396
+ !value.startsWith("/") ||
397
+ value.includes("//") ||
398
+ value.includes("?") ||
399
+ value.includes("#") ||
400
+ value.includes("\\") ||
401
+ value.includes("\0")
402
+ ) {
403
+ return false
404
+ }
405
+
406
+ if (new URL(value, "https://sixb.invalid").pathname !== value) return false
407
+
408
+ let decoded: string
409
+ try {
410
+ decoded = decodeURIComponent(value).replaceAll("\\", "/")
411
+ } catch {
412
+ return false
413
+ }
414
+ return decoded !== "/shared" && !decoded.startsWith("/shared/")
415
+ }
416
+
417
+ function isRecord(value: unknown): value is Record<string, unknown> {
418
+ return typeof value === "object" && value !== null
419
+ }
420
+
212
421
  function isAuthRedirectExcludedRequest(
213
422
  config: SixbBrowserRuntimeConfig,
214
423
  request: Request
@@ -0,0 +1,31 @@
1
+ import type { Client } from "./generated/client"
2
+
3
+ const sharedAuthorityClients = new WeakSet<Client>()
4
+
5
+ export const SHARED_ACCESS_REALTIME_UNAVAILABLE =
6
+ "Live updates are unavailable during shared access."
7
+
8
+ export function assertSharedAccessGrantId(grantId: unknown): asserts grantId is string {
9
+ if (
10
+ typeof grantId !== "string" ||
11
+ grantId.length === 0 ||
12
+ grantId.length > 128 ||
13
+ grantId.trim() !== grantId ||
14
+ grantId.includes("\0")
15
+ ) {
16
+ throw new Error("[SixbClient] Shared access grant id is invalid.")
17
+ }
18
+ }
19
+
20
+ export function markClientSharedAuthority(client: Client, shared: boolean): void {
21
+ if (shared) {
22
+ sharedAuthorityClients.add(client)
23
+ return
24
+ }
25
+
26
+ sharedAuthorityClients.delete(client)
27
+ }
28
+
29
+ export function hasClientSharedAuthority(client: Client): boolean {
30
+ return sharedAuthorityClients.has(client)
31
+ }
@@ -36,9 +36,11 @@ import {
36
36
  events as selectEvents,
37
37
  } from "@sixb/core/events/selectors"
38
38
  import type { LinkToken, ObjectTypeWithTokens, Property, PropertyToken } from "@sixb/core/ontology"
39
+ import { hasClientSharedAuthority, SHARED_ACCESS_REALTIME_UNAVAILABLE } from "./client-authority"
39
40
  import type { SixbEvent, SixbEventOfTopic, SixbEventOfType, SixbEventTopic } from "./events-model"
40
41
  import { createEventSocket, type EventSocketState } from "./events-transport"
41
42
  import type { Client } from "./generated/client"
43
+ import { client as generatedClient } from "./generated/client.gen"
42
44
 
43
45
  /**
44
46
  * Conjunctive event-filter scope. Event subscriptions are a single flat scope
@@ -340,7 +342,22 @@ export interface EventSubscribeExecutor {
340
342
  * filtering an optimization rather than a correctness dependency.
341
343
  */
342
344
  export function createWsSubscribeExecutor(options?: { client?: Client }): EventSubscribeExecutor {
343
- const baseUrl = options?.client?.getConfig().baseUrl
345
+ const transportClient = options?.client ?? generatedClient
346
+ const baseUrl = transportClient.getConfig().baseUrl
347
+ if (hasClientSharedAuthority(transportClient)) {
348
+ return {
349
+ subscribe(_filter, _handler, subscribeOptions) {
350
+ subscribeOptions?.onError?.(SHARED_ACCESS_REALTIME_UNAVAILABLE)
351
+ subscribeOptions?.onStateChange?.({
352
+ connected: false,
353
+ reconnecting: false,
354
+ error: SHARED_ACCESS_REALTIME_UNAVAILABLE,
355
+ })
356
+ return () => undefined
357
+ },
358
+ }
359
+ }
360
+
344
361
  return {
345
362
  subscribe(filter, handler, subscribeOptions) {
346
363
  const matches = buildEventPredicate(filter)