@sixb/client 0.1.19 → 0.1.21

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 (55) hide show
  1. package/README.md +5 -8
  2. package/dist/activity-attribution.d.ts +29 -0
  3. package/dist/activity-attribution.d.ts.map +1 -0
  4. package/dist/activity-tracker.d.ts +105 -0
  5. package/dist/activity-tracker.d.ts.map +1 -0
  6. package/dist/browser.d.ts +3 -4
  7. package/dist/browser.d.ts.map +1 -1
  8. package/dist/browser.js +514 -14
  9. package/dist/browser.js.map +6 -4
  10. package/dist/{chunk-j512cs3e.js → chunk-3b154p8n.js} +5 -6
  11. package/dist/{chunk-j512cs3e.js.map → chunk-3b154p8n.js.map} +4 -4
  12. package/dist/{chunk-tkjkrcdt.js → chunk-3f2pjdzk.js} +155 -2
  13. package/dist/chunk-3f2pjdzk.js.map +19 -0
  14. package/dist/{chunk-awbb496e.js → chunk-9wd8x2em.js} +1 -1
  15. package/dist/{chunk-3aa3m9z6.js → chunk-ana8rtgb.js} +2 -2
  16. package/dist/{chunk-jh4ts8mt.js → chunk-m2rmbshc.js} +3 -2
  17. package/dist/{chunk-jh4ts8mt.js.map → chunk-m2rmbshc.js.map} +3 -3
  18. package/dist/{chunk-95bnb04n.js → chunk-qdq5gfqx.js} +1 -1
  19. package/dist/{chunk-12s8gbwj.js → chunk-s5zamywm.js} +2 -2
  20. package/dist/connectors/queries.d.ts.map +1 -1
  21. package/dist/file.d.ts +1 -3
  22. package/dist/file.d.ts.map +1 -1
  23. package/dist/generated/@tanstack/react-query.gen.d.ts +2250 -572
  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 +89 -1
  28. package/dist/generated/sdk.gen.d.ts.map +1 -1
  29. package/dist/generated/types.gen.d.ts +1910 -734
  30. package/dist/generated/types.gen.d.ts.map +1 -1
  31. package/dist/hooks.js +300 -7
  32. package/dist/hooks.js.map +3 -3
  33. package/dist/index.js +41 -7
  34. package/dist/index.js.map +1 -1
  35. package/dist/logs.js +3 -3
  36. package/dist/models.d.ts.map +1 -1
  37. package/dist/models.js +37 -3
  38. package/dist/models.js.map +1 -1
  39. package/dist/query.js +3 -3
  40. package/package.json +2 -2
  41. package/src/activity-attribution.ts +211 -0
  42. package/src/activity-tracker.ts +527 -0
  43. package/src/agent-streams.ts +1 -1
  44. package/src/browser.ts +15 -7
  45. package/src/file.ts +1 -4
  46. package/src/generated/@tanstack/react-query.gen.ts +580 -0
  47. package/src/generated/index.ts +101 -0
  48. package/src/generated/sdk.gen.ts +389 -0
  49. package/src/generated/types.gen.ts +1947 -677
  50. package/src/models.ts +5 -3
  51. package/dist/chunk-tkjkrcdt.js.map +0 -19
  52. /package/dist/{chunk-awbb496e.js.map → chunk-9wd8x2em.js.map} +0 -0
  53. /package/dist/{chunk-3aa3m9z6.js.map → chunk-ana8rtgb.js.map} +0 -0
  54. /package/dist/{chunk-95bnb04n.js.map → chunk-qdq5gfqx.js.map} +0 -0
  55. /package/dist/{chunk-12s8gbwj.js.map → chunk-s5zamywm.js.map} +0 -0
@@ -0,0 +1,527 @@
1
+ import { clearActivityArrival, takeActivityArrival } from "./activity-attribution"
2
+ import { captureActivity, getActivityCaptureConfig } from "./generated/sdk.gen"
3
+ import type { CaptureActivityData, GetActivityCaptureConfigResponse } from "./generated/types.gen"
4
+
5
+ type EventInput = CaptureActivityData["body"]["events"][number]
6
+ type VisitEventInput = Exclude<EventInput, { readonly type: "ui.interaction" }>
7
+ export type ActivityAttribution = NonNullable<VisitEventInput["attribution"]>
8
+
9
+ interface QueuedEvent {
10
+ readonly event: EventInput
11
+ readonly queuedAt: number
12
+ }
13
+
14
+ /** A response that refused a batch: its status, and the wait a 429 asked for. */
15
+ export class ActivityDeliveryError extends Error {
16
+ readonly name = "ActivityDeliveryError"
17
+
18
+ constructor(
19
+ readonly status: number,
20
+ readonly retryAfterMs?: number
21
+ ) {
22
+ super(`[SixbClient] Activity delivery was refused with status ${status}.`)
23
+ }
24
+ }
25
+
26
+ export interface ActivityTrackerOptions {
27
+ readonly document: Pick<
28
+ Document,
29
+ "visibilityState" | "addEventListener" | "removeEventListener"
30
+ > | null
31
+ readonly load: (signal: AbortSignal) => Promise<GetActivityCaptureConfigResponse>
32
+ /** Rejects with an `ActivityDeliveryError` when the API answers, with anything else when not. */
33
+ readonly send: (events: EventInput[], signal: AbortSignal) => Promise<void>
34
+ /** How this document was reached; sent once, with its first event. */
35
+ readonly attribution?: ActivityAttribution
36
+ readonly now?: () => number
37
+ readonly warn?: (message: string) => void
38
+ }
39
+
40
+ const MAX_QUEUE = 100
41
+ const MAX_BATCH = 20
42
+ const MAX_AGE_MS = 60_000
43
+ const MAX_ATTEMPTS = 3
44
+ const REQUEST_TIMEOUT_MS = 10_000
45
+ const FLUSH_DELAY_MS = 500
46
+ const PULSE_INTERVAL_MS = 30_000
47
+ const INPUT_EVENTS = ["pointerdown", "keydown", "touchstart", "scroll"] as const
48
+ const TRACK_ATTRIBUTE = "data-sixb-track"
49
+ /** The same name again within this long is the same interaction: a double click, a burst. */
50
+ const COALESCE_MS = 1_000
51
+ const MAX_REPORTED_NAMES = 20
52
+ const REPORTED_NAME_LENGTH = 40
53
+
54
+ // The server's rule, from the activity policy: lowercase dotted segments, each starting with a
55
+ // letter, at most 40 characters and without a run of four digits, 100 in all.
56
+ export const INTERACTION_NAME_PATTERN =
57
+ /^(?!.*\d{4})[a-z][a-z0-9_-]{0,39}(?:\.[a-z][a-z0-9_-]{0,39})*$/
58
+ export const INTERACTION_NAME_MAX_LENGTH = 100
59
+
60
+ /**
61
+ * Sends page views, foreground activity and marked interactions for one authority. Events live in
62
+ * memory only: they are never persisted, and never carried across a sign-in or another shared link.
63
+ */
64
+ export class ActivityTracker {
65
+ private readonly abort = new AbortController()
66
+ private readonly now: () => number
67
+ private readonly warn: (message: string) => void
68
+ private enabled = false
69
+ private idleTimeoutMs = 30 * 60_000
70
+ private route: string | null = null
71
+ private queue: QueuedEvent[] = []
72
+ private flushTimer: ReturnType<typeof setTimeout> | undefined
73
+ private pulseTimer: ReturnType<typeof setInterval> | undefined
74
+ private pending: Promise<void> | undefined
75
+ private failedAttempts = 0
76
+ /** Epoch milliseconds before which a 429 asked not to send again. */
77
+ private throttledUntil = 0
78
+ /** Input since the last event: the next pulse reports it. */
79
+ private active = false
80
+ /** A navigation happened while hidden; it counts once the tab is visible. */
81
+ private hiddenNavigation = false
82
+ private lastInputAt = 0
83
+ private arrivalSent = false
84
+ /** Invalid names already reported, so a misnamed button warns once; at most twenty. */
85
+ private readonly invalidNames = new Set<string>()
86
+ private moreInvalidNames = false
87
+ private lastInteraction: { readonly name: string; readonly at: number } | undefined
88
+
89
+ constructor(private readonly options: ActivityTrackerOptions) {
90
+ this.now = options.now ?? Date.now
91
+ this.warn = options.warn ?? ((message) => console.warn(message))
92
+ void this.start()
93
+ }
94
+
95
+ /** The route pattern now shown, or `null` on a page that is not recorded. */
96
+ page(route: string | null): void {
97
+ this.route = route
98
+ this.hiddenNavigation = route !== null
99
+ if (!this.enabled || !this.visible() || route === null) {
100
+ return
101
+ }
102
+
103
+ this.hiddenNavigation = false
104
+ this.active = false
105
+ this.lastInputAt = this.now()
106
+ this.enqueue("page.view")
107
+ }
108
+
109
+ /**
110
+ * An interaction code reports, on the page now shown. A call is not the person's input: once
111
+ * they have been idle for the idle timeout it is dropped, so background code cannot keep their
112
+ * visit going.
113
+ */
114
+ interaction(name: string): void {
115
+ if (this.now() - this.lastInputAt >= this.idleTimeoutMs) {
116
+ return
117
+ }
118
+
119
+ this.record(name)
120
+ }
121
+
122
+ dispose(): void {
123
+ this.enabled = false
124
+ this.abort.abort()
125
+ clearTimeout(this.flushTimer)
126
+ clearInterval(this.pulseTimer)
127
+
128
+ for (const type of INPUT_EVENTS) {
129
+ this.options.document?.removeEventListener(type, this.onInput, { capture: true })
130
+ }
131
+ this.options.document?.removeEventListener("click", this.onClick, { capture: true })
132
+ this.options.document?.removeEventListener("visibilitychange", this.onVisibility)
133
+
134
+ this.queue = []
135
+ }
136
+
137
+ /** Sends the next batch. Concurrent calls share one request; tests call it directly. */
138
+ flush(): Promise<void> {
139
+ clearTimeout(this.flushTimer)
140
+ this.flushTimer = undefined
141
+
142
+ if (this.pending) {
143
+ return this.pending
144
+ }
145
+
146
+ this.pending = this.sendBatch().finally(() => {
147
+ this.pending = undefined
148
+ if (this.queue.length > 0 && !this.abort.signal.aborted) {
149
+ this.schedule(this.nextDelay())
150
+ }
151
+ })
152
+ return this.pending
153
+ }
154
+
155
+ private nextDelay(): number {
156
+ const throttled = this.throttledUntil - this.now()
157
+ if (throttled > 0) {
158
+ return throttled
159
+ }
160
+ return this.failedAttempts > 0 ? retryDelay(this.failedAttempts) : FLUSH_DELAY_MS
161
+ }
162
+
163
+ private async start(): Promise<void> {
164
+ let config: GetActivityCaptureConfigResponse
165
+ try {
166
+ config = await this.request((signal) => this.options.load(signal))
167
+ } catch {
168
+ if (!this.abort.signal.aborted) {
169
+ this.warn(
170
+ "[SixbClient] Activity capture settings are unavailable; this visit is not recorded."
171
+ )
172
+ }
173
+ return
174
+ }
175
+
176
+ if (this.abort.signal.aborted || !config.enabled) {
177
+ return
178
+ }
179
+
180
+ this.enabled = true
181
+ this.idleTimeoutMs = config.idleTimeoutMs
182
+
183
+ for (const type of INPUT_EVENTS) {
184
+ this.options.document?.addEventListener(type, this.onInput, { capture: true, passive: true })
185
+ }
186
+ // One listener for every marked element, present or rendered later.
187
+ this.options.document?.addEventListener("click", this.onClick, { capture: true, passive: true })
188
+ this.options.document?.addEventListener("visibilitychange", this.onVisibility)
189
+ this.pulseTimer = setInterval(this.onPulse, PULSE_INTERVAL_MS)
190
+
191
+ if (this.route !== null) {
192
+ this.page(this.route)
193
+ }
194
+ }
195
+
196
+ private onPulse = (): void => {
197
+ if (this.active && this.visible()) {
198
+ this.active = false
199
+ this.enqueue("visit.activity")
200
+ }
201
+ }
202
+
203
+ private onInput = (event: Event): void => {
204
+ // Synthetic events are scripts, not someone using the page.
205
+ if (!event.isTrusted || !this.visible()) {
206
+ return
207
+ }
208
+
209
+ const resumed = this.now() - this.lastInputAt >= this.idleTimeoutMs
210
+ this.lastInputAt = this.now()
211
+
212
+ if (resumed) {
213
+ this.active = false
214
+ this.enqueue("visit.activity")
215
+ } else {
216
+ this.active = true
217
+ }
218
+ }
219
+
220
+ private onClick = (event: Event): void => {
221
+ // A script's click is not someone using the page.
222
+ if (!event.isTrusted) {
223
+ return
224
+ }
225
+
226
+ // The composed path reaches a marked element across shadow roots, as `closest` cannot.
227
+ const path = event.composedPath()
228
+ const markedAt = path.findIndex(
229
+ (target) => isElement(target) && target.hasAttribute(TRACK_ATTRIBUTE)
230
+ )
231
+ const marked = path[markedAt]
232
+ if (!isElement(marked)) {
233
+ return
234
+ }
235
+
236
+ const within = path.slice(0, markedAt + 1).filter(isElement)
237
+ if (within.some((element) => isDisabled(element) || forwardsClick(element, marked, path))) {
238
+ return
239
+ }
240
+
241
+ // A marked click is the person's input, and the interaction reports it.
242
+ this.lastInputAt = this.now()
243
+ this.active = false
244
+ this.record(marked.getAttribute(TRACK_ATTRIBUTE) ?? "")
245
+ }
246
+
247
+ /**
248
+ * Queues an interaction. Before the settings load, on a page that is not recorded or in a
249
+ * hidden tab, it is dropped: someone acts on a page they see.
250
+ */
251
+ private record(name: string): void {
252
+ if (!this.enabled || !this.visible() || this.route === null) {
253
+ return
254
+ }
255
+
256
+ if (!isInteractionName(name)) {
257
+ this.invalidName(name)
258
+ return
259
+ }
260
+
261
+ const now = this.now()
262
+ if (this.lastInteraction?.name === name && now - this.lastInteraction.at < COALESCE_MS) {
263
+ return
264
+ }
265
+ this.lastInteraction = { name, at: now }
266
+
267
+ this.push((route) => ({ id: crypto.randomUUID(), type: "ui.interaction", name, route }))
268
+ }
269
+
270
+ private onVisibility = (): void => {
271
+ if (this.visible()) {
272
+ this.lastInputAt = this.now()
273
+ this.active = false
274
+ // A navigation made while hidden is a page view; returning to the same page is activity.
275
+ this.enqueue(this.hiddenNavigation ? "page.view" : "visit.activity")
276
+ this.hiddenNavigation = false
277
+ return
278
+ }
279
+
280
+ if (this.active) {
281
+ this.active = false
282
+ this.enqueue("visit.activity")
283
+ }
284
+ void this.flush()
285
+ }
286
+
287
+ private visible(): boolean {
288
+ return this.options.document?.visibilityState === "visible"
289
+ }
290
+
291
+ private enqueue(type: VisitEventInput["type"]): void {
292
+ this.push((route) => ({ id: crypto.randomUUID(), type, route, ...this.nextAttribution() }))
293
+ }
294
+
295
+ /** Queues the event `build` makes for the route shown, unless it would not be recorded. */
296
+ private push(build: (route: string) => EventInput): void {
297
+ if (!this.enabled || this.route === null || this.abort.signal.aborted) {
298
+ return
299
+ }
300
+
301
+ if (this.queue.length >= MAX_QUEUE) {
302
+ this.dropped(1)
303
+ return
304
+ }
305
+
306
+ this.queue.push({ event: build(this.route), queuedAt: this.now() })
307
+ this.schedule(FLUSH_DELAY_MS)
308
+ }
309
+
310
+ /**
311
+ * The arrival travels with the first event only; later events say `{}`, so a visit started by
312
+ * inactivity reads as direct rather than inheriting an old campaign.
313
+ */
314
+ private nextAttribution(): { attribution?: ActivityAttribution } {
315
+ const first = !this.arrivalSent
316
+ this.arrivalSent = true
317
+
318
+ if (!first) {
319
+ return { attribution: {} }
320
+ }
321
+ return this.options.attribution === undefined ? {} : { attribution: this.options.attribution }
322
+ }
323
+
324
+ private schedule(delay: number): void {
325
+ if (this.flushTimer !== undefined) {
326
+ return
327
+ }
328
+
329
+ this.flushTimer = setTimeout(() => {
330
+ this.flushTimer = undefined
331
+ void this.flush()
332
+ }, delay)
333
+ }
334
+
335
+ private async sendBatch(): Promise<void> {
336
+ if (!this.enabled || this.abort.signal.aborted) {
337
+ return
338
+ }
339
+
340
+ const fresh = this.queue.filter((item) => this.now() - item.queuedAt <= MAX_AGE_MS)
341
+ if (fresh.length < this.queue.length) {
342
+ this.dropped(this.queue.length - fresh.length)
343
+ this.queue = fresh
344
+ }
345
+
346
+ const batch = this.queue.slice(0, MAX_BATCH)
347
+ if (batch.length === 0 || this.now() < this.throttledUntil) {
348
+ return
349
+ }
350
+
351
+ try {
352
+ await this.request((signal) =>
353
+ this.options.send(
354
+ batch.map((item) => item.event),
355
+ signal
356
+ )
357
+ )
358
+ if (this.abort.signal.aborted) {
359
+ return
360
+ }
361
+
362
+ this.queue.splice(0, batch.length)
363
+ this.failedAttempts = 0
364
+ } catch (error) {
365
+ if (this.abort.signal.aborted) {
366
+ return
367
+ }
368
+
369
+ if (error instanceof ActivityDeliveryError && error.status === 429) {
370
+ // Wait as asked, at most as long as the events are kept.
371
+ this.throttledUntil = this.now() + Math.min(error.retryAfterMs ?? MAX_AGE_MS, MAX_AGE_MS)
372
+ return
373
+ }
374
+
375
+ // Another refusal would answer the same again: the batch is dropped, not retried.
376
+ if (error instanceof ActivityDeliveryError && error.status >= 400 && error.status < 500) {
377
+ this.queue.splice(0, batch.length)
378
+ this.dropped(batch.length)
379
+ this.failedAttempts = 0
380
+ return
381
+ }
382
+
383
+ // A retry resends the same ids, so the server recognizes page views it already has.
384
+ this.failedAttempts++
385
+ if (this.failedAttempts >= MAX_ATTEMPTS) {
386
+ this.queue.splice(0, batch.length)
387
+ this.dropped(batch.length)
388
+ this.failedAttempts = 0
389
+ }
390
+ }
391
+ }
392
+
393
+ private async request<T>(run: (signal: AbortSignal) => Promise<T>): Promise<T> {
394
+ const controller = new AbortController()
395
+ const abort = () => controller.abort()
396
+ this.abort.signal.addEventListener("abort", abort, { once: true })
397
+ const timeout = setTimeout(abort, REQUEST_TIMEOUT_MS)
398
+
399
+ try {
400
+ return await run(controller.signal)
401
+ } finally {
402
+ clearTimeout(timeout)
403
+ this.abort.signal.removeEventListener("abort", abort)
404
+ }
405
+ }
406
+
407
+ private invalidName(name: string): void {
408
+ if (this.invalidNames.has(name)) {
409
+ return
410
+ }
411
+
412
+ if (this.invalidNames.size >= MAX_REPORTED_NAMES) {
413
+ if (!this.moreInvalidNames) {
414
+ this.moreInvalidNames = true
415
+ this.warn("[SixbClient] More interaction names are invalid; they are not reported.")
416
+ }
417
+ return
418
+ }
419
+
420
+ // A prefix only: a misused name may hold a value.
421
+ const text = String(name)
422
+ const shown =
423
+ text.length > REPORTED_NAME_LENGTH ? `${text.slice(0, REPORTED_NAME_LENGTH)}…` : text
424
+
425
+ this.invalidNames.add(name)
426
+ this.warn(
427
+ `[SixbClient] ${JSON.stringify(shown)} is not an interaction name, so it is not recorded. Use lowercase dotted identifiers such as "invoices.export".`
428
+ )
429
+ }
430
+
431
+ private dropped(count: number): void {
432
+ // Never the route or ids: the warning is for the console, not a record of the visit.
433
+ this.warn(
434
+ `[SixbClient] Activity capture dropped ${count} event(s); visit history may be incomplete.`
435
+ )
436
+ }
437
+ }
438
+
439
+ function isInteractionName(value: unknown): value is string {
440
+ return (
441
+ typeof value === "string" &&
442
+ value.length <= INTERACTION_NAME_MAX_LENGTH &&
443
+ INTERACTION_NAME_PATTERN.test(value)
444
+ )
445
+ }
446
+
447
+ function isElement(value: unknown): value is Element {
448
+ return (
449
+ typeof value === "object" &&
450
+ value !== null &&
451
+ typeof Reflect.get(value, "hasAttribute") === "function"
452
+ )
453
+ }
454
+
455
+ function isDisabled(element: Element): boolean {
456
+ return element.getAttribute("aria-disabled") === "true" || element.matches(":disabled")
457
+ }
458
+
459
+ /**
460
+ * A click on a label whose control is inside the same marked element, but not on the control:
461
+ * the browser forwards it to the control, and that click records the interaction.
462
+ */
463
+ function forwardsClick(element: Element, marked: Element, path: readonly EventTarget[]): boolean {
464
+ const control: unknown = Reflect.get(element, "control")
465
+ return (
466
+ element.tagName === "LABEL" &&
467
+ isElement(control) &&
468
+ marked.contains(control) &&
469
+ !path.includes(control)
470
+ )
471
+ }
472
+
473
+ function retryDelay(failedAttempts: number): number {
474
+ return Math.min(10_000, 1_000 * 2 ** failedAttempts)
475
+ }
476
+
477
+ /** Reads a `Retry-After` in seconds; a date or anything else leaves the default wait. */
478
+ function retryAfterMs(value: string | null): number | undefined {
479
+ const seconds = value === null ? Number.NaN : Number(value)
480
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1_000 : undefined
481
+ }
482
+
483
+ let active: ActivityTracker | undefined
484
+ // The page shown, kept across a start so the order of start and first render does not matter.
485
+ let shownRoute: string | null = null
486
+
487
+ /** Starts recording for the authority the bootstrap just established. */
488
+ export function startSixbActivityCapture(): void {
489
+ const attribution = takeActivityArrival()
490
+ active?.dispose()
491
+ active = new ActivityTracker({
492
+ attribution,
493
+ document: typeof document === "undefined" ? null : document,
494
+ load: async (signal) => (await getActivityCaptureConfig({ signal, throwOnError: true })).data,
495
+ send: async (events, signal) => {
496
+ const { response } = await captureActivity({ body: { events }, signal, keepalive: true })
497
+ if (!response.ok) {
498
+ throw new ActivityDeliveryError(
499
+ response.status,
500
+ retryAfterMs(response.headers.get("retry-after"))
501
+ )
502
+ }
503
+ },
504
+ })
505
+ active.page(shownRoute)
506
+ }
507
+
508
+ /** Reports the route pattern now shown, or `null` on a page that is not recorded. */
509
+ export function recordSixbPageView(route: string | null): void {
510
+ shownRoute = route
511
+ active?.page(route)
512
+ }
513
+
514
+ /**
515
+ * Records an interaction that is not a click, such as `invoices.filter.applied`, on the page now
516
+ * shown. Names are lowercase dotted identifiers and never carry a value. Does nothing while
517
+ * activity is off, on a page that is not recorded, or before its settings load.
518
+ */
519
+ export function trackSixbEvent(name: string): void {
520
+ active?.interaction(name)
521
+ }
522
+
523
+ export function stopSixbActivityCapture(): void {
524
+ clearActivityArrival()
525
+ active?.dispose()
526
+ active = undefined
527
+ }
@@ -1,6 +1,6 @@
1
1
  import type { AgentRunActivityEvent, AgentRunStreamEvent } from "@sixb/core/agents/streams"
2
2
  // Import the wire validator from the browser-safe streams subpath: the `@sixb/core` root pulls in
3
- // node-only runtime (e.g. `node:crypto`), which breaks the Atlas browser bundle.
3
+ // node-only runtime (e.g. `node:crypto`), which breaks browser bundles.
4
4
  import { isAgentRunActivityEvent, isAgentRunStreamEvent } from "@sixb/core/agents/streams"
5
5
  import type { BrokerRecord } from "@sixb/core/broker"
6
6
  import type { Client } from "./generated/client"
package/src/browser.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { AuthSessionAudience } from "@sixb/core"
1
+ import { prepareActivityArrival, preserveSixbActivityArrival } from "./activity-attribution"
2
+ import { stopSixbActivityCapture } from "./activity-tracker"
2
3
  import {
3
4
  configureSixbClient as configureGeneratedSixbClient,
4
5
  normalizeSixbApiBaseUrl,
@@ -11,6 +12,8 @@ import {
11
12
  } from "./client-authority"
12
13
  import { client } from "./generated/client.gen"
13
14
 
15
+ export { preserveSixbActivityArrival } from "./activity-attribution"
16
+ export { recordSixbPageView, startSixbActivityCapture, trackSixbEvent } from "./activity-tracker"
14
17
  export type { SixbApiErrorCode, SixbApiErrorInit } from "./api"
15
18
  export { isSixbApiError, SixbApiError } from "./api"
16
19
 
@@ -37,14 +40,12 @@ export interface SixbBrowserRuntimeConfig {
37
40
  readonly baseUrl: string
38
41
  }
39
42
  readonly auth: {
40
- readonly audience: AuthSessionAudience
41
43
  readonly enabled: boolean
42
44
  }
43
45
  }
44
46
 
45
47
  export interface SixbBrowserRuntimeDefaults {
46
48
  readonly apiBaseUrl?: string
47
- readonly audience: AuthSessionAudience
48
49
  readonly authEnabled?: boolean
49
50
  }
50
51
 
@@ -90,7 +91,7 @@ export function renderSixbBrowserRuntimeScript(config: SixbBrowserRuntimeConfig)
90
91
  }
91
92
 
92
93
  export function readSixbBrowserRuntimeConfig(
93
- defaults: SixbBrowserRuntimeDefaults
94
+ defaults: SixbBrowserRuntimeDefaults = {}
94
95
  ): SixbBrowserRuntimeConfig {
95
96
  const runtime = window.__SIXB_RUNTIME__
96
97
  const runtimeAuthEnabled = runtime?.auth?.enabled
@@ -101,7 +102,6 @@ export function readSixbBrowserRuntimeConfig(
101
102
  ),
102
103
  },
103
104
  auth: {
104
- audience: runtime?.auth?.audience ?? defaults.audience,
105
105
  enabled:
106
106
  typeof runtimeAuthEnabled === "boolean"
107
107
  ? runtimeAuthEnabled
@@ -115,6 +115,7 @@ export function configureSixbBrowserClient(
115
115
  options: SixbBrowserClientOptions = {}
116
116
  ): SixbBrowserClientController {
117
117
  activeBrowserController?.dispose()
118
+ prepareActivityArrival(config.api.baseUrl, "app")
118
119
 
119
120
  let csrfToken: string | null = null
120
121
  let disposed = false
@@ -165,6 +166,7 @@ export function configureSixbBrowserClient(
165
166
  ((url: string) => {
166
167
  if (typeof window !== "undefined") window.location.assign(url)
167
168
  })
169
+ preserveSixbActivityArrival()
168
170
  redirect(createSixbSignInUrl(config, currentUrl))
169
171
  } catch {
170
172
  // Allow a later response to retry navigation without replacing the original API error.
@@ -183,6 +185,7 @@ export function configureSixbBrowserClient(
183
185
  dispose() {
184
186
  if (disposed) return
185
187
  disposed = true
188
+ stopSixbActivityCapture()
186
189
  csrfToken = null
187
190
  disposeActivity()
188
191
  client.interceptors.response.eject(authResponseInterceptorId)
@@ -207,6 +210,7 @@ export function configureSixbSharedBrowserClient(
207
210
  ): SixbSharedBrowserClientController {
208
211
  activeBrowserController?.dispose()
209
212
  assertSharedAccessGrantId(options.grantId)
213
+ prepareActivityArrival(config.api.baseUrl, `share:${options.grantId}`)
210
214
 
211
215
  const previousConfig = client.getConfig()
212
216
  const previousSharedAuthority = getClientSharedGrantId(client)
@@ -269,6 +273,7 @@ export function configureSixbSharedBrowserClient(
269
273
  dispose() {
270
274
  if (disposed) return
271
275
  disposed = true
276
+ stopSixbActivityCapture()
272
277
  csrfToken = null
273
278
  disposeActivity()
274
279
  client.interceptors.response.eject(responseInterceptorId)
@@ -429,10 +434,13 @@ function isAuthRedirectExcludedRequest(
429
434
  const apiUrl = new URL(normalizeSixbApiBaseUrl(config.api.baseUrl), requestUrl)
430
435
  const apiPath = apiUrl.pathname.replace(/\/+$/, "")
431
436
  const method = request.method.toUpperCase()
437
+ // Activity is background traffic: an expired session shows on the user's next real request.
432
438
  return (
433
439
  requestUrl.origin === apiUrl.origin &&
434
440
  ((method === "GET" && requestUrl.pathname === `${apiPath}/api/auth/session`) ||
435
- (method === "POST" && requestUrl.pathname === `${apiPath}/api/auth/sign-out`))
441
+ (method === "POST" && requestUrl.pathname === `${apiPath}/api/auth/sign-out`) ||
442
+ (method === "GET" && requestUrl.pathname === `${apiPath}/api/activity/capture-config`) ||
443
+ (method === "POST" && requestUrl.pathname === `${apiPath}/api/activity/events`))
436
444
  )
437
445
  }
438
446
 
@@ -473,13 +481,13 @@ export async function requireSixbBrowserAuthSession(
473
481
  }
474
482
  const returnTo = options.returnTo ?? window.location.href
475
483
  const redirect = options.redirect ?? ((url: string) => window.location.assign(url))
484
+ preserveSixbActivityArrival()
476
485
  redirect(createSixbSignInUrl(config, returnTo))
477
486
  return data
478
487
  }
479
488
 
480
489
  export function createSixbSignInUrl(config: SixbBrowserRuntimeConfig, returnTo: string): string {
481
490
  const url = new URL("/auth/sign-in", normalizeSixbApiBaseUrl(config.api.baseUrl))
482
- url.searchParams.set("audience", config.auth.audience)
483
491
  url.searchParams.set("returnTo", returnTo)
484
492
  return url.toString()
485
493
  }
package/src/file.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AuthSessionAudience, FileRef } from "@sixb/core"
1
+ import type { FileRef } from "@sixb/core"
2
2
  import { DEFAULT_SIMPLE_FILE_UPLOAD_BYTES } from "@sixb/core/blob-storage"
3
3
  import { isSixbApiError, type SixbClient } from "./api"
4
4
  import { getClientSharedGrantId } from "./client-authority"
@@ -19,8 +19,6 @@ export interface ObjectFileContentUrlInput {
19
19
  /** Property path segments, without the leading `properties` segment. */
20
20
  readonly pathSegments: readonly string[]
21
21
  readonly fileRef: FileRef
22
- /** Session audience for browser file navigation, e.g. "app" in split-domain deployments. */
23
- readonly audience?: AuthSessionAudience
24
22
  readonly disposition?: "inline" | "attachment"
25
23
  readonly client?: SixbClient
26
24
  }
@@ -47,7 +45,6 @@ export function objectFileContentUrl(input: ObjectFileContentUrlInput): string {
47
45
  .map((segment) => segment.replaceAll("~", "~0").replaceAll("/", "~1"))
48
46
  .join("/")}`,
49
47
  disposition: input.disposition,
50
- audience: input.audience,
51
48
  shareGrant: getClientSharedGrantId(client) ?? undefined,
52
49
  // Opaque cache key, not a historical-file selector. Include per-reference metadata.
53
50
  // Encode each field so Elysia won't interpret commas in filenames as an array.