@sixb/client 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +193 -0
  3. package/dist/actions.d.ts +61 -0
  4. package/dist/actions.d.ts.map +1 -0
  5. package/dist/agent-streams.d.ts +72 -0
  6. package/dist/agent-streams.d.ts.map +1 -0
  7. package/dist/api.d.ts +54 -0
  8. package/dist/api.d.ts.map +1 -0
  9. package/dist/browser.d.ts +41 -0
  10. package/dist/browser.d.ts.map +1 -0
  11. package/dist/browser.js +174 -0
  12. package/dist/browser.js.map +10 -0
  13. package/dist/chunk-05yz32g0.js +240 -0
  14. package/dist/chunk-05yz32g0.js.map +10 -0
  15. package/dist/chunk-2d7239yx.js +1181 -0
  16. package/dist/chunk-2d7239yx.js.map +17 -0
  17. package/dist/chunk-3g6ad4jc.js +147 -0
  18. package/dist/chunk-3g6ad4jc.js.map +10 -0
  19. package/dist/chunk-aw8rcsq3.js +145 -0
  20. package/dist/chunk-aw8rcsq3.js.map +10 -0
  21. package/dist/chunk-ctsdm59b.js +1477 -0
  22. package/dist/chunk-ctsdm59b.js.map +19 -0
  23. package/dist/chunk-fxrh83wy.js +180 -0
  24. package/dist/chunk-fxrh83wy.js.map +12 -0
  25. package/dist/chunk-pey7nh0d.js +123 -0
  26. package/dist/chunk-pey7nh0d.js.map +10 -0
  27. package/dist/chunk-trpg18dp.js +3 -0
  28. package/dist/chunk-trpg18dp.js.map +9 -0
  29. package/dist/events-builder.d.ts +218 -0
  30. package/dist/events-builder.d.ts.map +1 -0
  31. package/dist/events-hooks.d.ts +50 -0
  32. package/dist/events-hooks.d.ts.map +1 -0
  33. package/dist/events-model.d.ts +12 -0
  34. package/dist/events-model.d.ts.map +1 -0
  35. package/dist/events-provider.d.ts +56 -0
  36. package/dist/events-provider.d.ts.map +1 -0
  37. package/dist/events-transport.d.ts +62 -0
  38. package/dist/events-transport.d.ts.map +1 -0
  39. package/dist/events.d.ts +5 -0
  40. package/dist/events.d.ts.map +1 -0
  41. package/dist/file.d.ts +27 -0
  42. package/dist/file.d.ts.map +1 -0
  43. package/dist/generated/@tanstack/react-query.gen.d.ts +17064 -0
  44. package/dist/generated/@tanstack/react-query.gen.d.ts.map +1 -0
  45. package/dist/generated/client/client.gen.d.ts +3 -0
  46. package/dist/generated/client/client.gen.d.ts.map +1 -0
  47. package/dist/generated/client/index.d.ts +9 -0
  48. package/dist/generated/client/index.d.ts.map +1 -0
  49. package/dist/generated/client/types.gen.d.ts +118 -0
  50. package/dist/generated/client/types.gen.d.ts.map +1 -0
  51. package/dist/generated/client/utils.gen.d.ts +34 -0
  52. package/dist/generated/client/utils.gen.d.ts.map +1 -0
  53. package/dist/generated/client.gen.d.ts +13 -0
  54. package/dist/generated/client.gen.d.ts.map +1 -0
  55. package/dist/generated/core/auth.gen.d.ts +19 -0
  56. package/dist/generated/core/auth.gen.d.ts.map +1 -0
  57. package/dist/generated/core/bodySerializer.gen.d.ts +26 -0
  58. package/dist/generated/core/bodySerializer.gen.d.ts.map +1 -0
  59. package/dist/generated/core/params.gen.d.ts +44 -0
  60. package/dist/generated/core/params.gen.d.ts.map +1 -0
  61. package/dist/generated/core/pathSerializer.gen.d.ts +34 -0
  62. package/dist/generated/core/pathSerializer.gen.d.ts.map +1 -0
  63. package/dist/generated/core/queryKeySerializer.gen.d.ts +19 -0
  64. package/dist/generated/core/queryKeySerializer.gen.d.ts.map +1 -0
  65. package/dist/generated/core/serverSentEvents.gen.d.ts +72 -0
  66. package/dist/generated/core/serverSentEvents.gen.d.ts.map +1 -0
  67. package/dist/generated/core/types.gen.d.ts +79 -0
  68. package/dist/generated/core/types.gen.d.ts.map +1 -0
  69. package/dist/generated/core/utils.gen.d.ts +20 -0
  70. package/dist/generated/core/utils.gen.d.ts.map +1 -0
  71. package/dist/generated/index.d.ts +3 -0
  72. package/dist/generated/index.d.ts.map +1 -0
  73. package/dist/generated/sdk.gen.d.ts +464 -0
  74. package/dist/generated/sdk.gen.d.ts.map +1 -0
  75. package/dist/generated/types.gen.d.ts +7672 -0
  76. package/dist/generated/types.gen.d.ts.map +1 -0
  77. package/dist/hooks.d.ts +123 -0
  78. package/dist/hooks.d.ts.map +1 -0
  79. package/dist/hooks.js +3179 -0
  80. package/dist/hooks.js.map +16 -0
  81. package/dist/index.d.ts +11 -0
  82. package/dist/index.d.ts.map +1 -0
  83. package/dist/index.js +329 -0
  84. package/dist/index.js.map +9 -0
  85. package/dist/logs-builder.d.ts +59 -0
  86. package/dist/logs-builder.d.ts.map +1 -0
  87. package/dist/logs-hooks.d.ts +30 -0
  88. package/dist/logs-hooks.d.ts.map +1 -0
  89. package/dist/logs-transport.d.ts +38 -0
  90. package/dist/logs-transport.d.ts.map +1 -0
  91. package/dist/logs.d.ts +7 -0
  92. package/dist/logs.d.ts.map +1 -0
  93. package/dist/logs.js +22 -0
  94. package/dist/logs.js.map +9 -0
  95. package/dist/models.d.ts +126 -0
  96. package/dist/models.d.ts.map +1 -0
  97. package/dist/models.js +252 -0
  98. package/dist/models.js.map +9 -0
  99. package/dist/query-hooks.d.ts +365 -0
  100. package/dist/query-hooks.d.ts.map +1 -0
  101. package/dist/query.d.ts +27 -0
  102. package/dist/query.d.ts.map +1 -0
  103. package/dist/query.js +15 -0
  104. package/dist/query.js.map +9 -0
  105. package/dist/sha256.d.ts +15 -0
  106. package/dist/sha256.d.ts.map +1 -0
  107. package/dist/telemetry-events.d.ts +25 -0
  108. package/dist/telemetry-events.d.ts.map +1 -0
  109. package/dist/tsconfig.json +5 -0
  110. package/dist/useAgentRunStream.d.ts +21 -0
  111. package/dist/useAgentRunStream.d.ts.map +1 -0
  112. package/dist/ws-socket.d.ts +45 -0
  113. package/dist/ws-socket.d.ts.map +1 -0
  114. package/package.json +105 -0
  115. package/src/actions.ts +310 -0
  116. package/src/agent-streams.ts +275 -0
  117. package/src/api.ts +229 -0
  118. package/src/browser.ts +267 -0
  119. package/src/events-builder.ts +735 -0
  120. package/src/events-hooks.ts +233 -0
  121. package/src/events-model.ts +40 -0
  122. package/src/events-provider.ts +161 -0
  123. package/src/events-transport.ts +193 -0
  124. package/src/events.ts +6 -0
  125. package/src/file.ts +367 -0
  126. package/src/generated/@tanstack/react-query.gen.ts +3876 -0
  127. package/src/generated/client/client.gen.ts +288 -0
  128. package/src/generated/client/index.ts +25 -0
  129. package/src/generated/client/types.gen.ts +209 -0
  130. package/src/generated/client/utils.gen.ts +316 -0
  131. package/src/generated/client.gen.ts +18 -0
  132. package/src/generated/core/auth.gen.ts +41 -0
  133. package/src/generated/core/bodySerializer.gen.ts +84 -0
  134. package/src/generated/core/params.gen.ts +169 -0
  135. package/src/generated/core/pathSerializer.gen.ts +171 -0
  136. package/src/generated/core/queryKeySerializer.gen.ts +117 -0
  137. package/src/generated/core/serverSentEvents.gen.ts +243 -0
  138. package/src/generated/core/types.gen.ts +104 -0
  139. package/src/generated/core/utils.gen.ts +140 -0
  140. package/src/generated/index.ts +672 -0
  141. package/src/generated/sdk.gen.ts +1984 -0
  142. package/src/generated/types.gen.ts +9049 -0
  143. package/src/hooks.ts +404 -0
  144. package/src/index.ts +18 -0
  145. package/src/logs-builder.ts +171 -0
  146. package/src/logs-hooks.ts +112 -0
  147. package/src/logs-transport.ts +112 -0
  148. package/src/logs.ts +15 -0
  149. package/src/models.ts +420 -0
  150. package/src/query-hooks.ts +1021 -0
  151. package/src/query.ts +175 -0
  152. package/src/sha256.ts +159 -0
  153. package/src/telemetry-events.ts +71 -0
  154. package/src/useAgentRunStream.ts +62 -0
  155. package/src/ws-socket.ts +202 -0
@@ -0,0 +1,275 @@
1
+ import type { AgentRunStreamEvent } from "@sixb/core/agents/streams"
2
+ // Import the schema-version value from the browser-safe streams subpath: the `@sixb/core` root pulls
3
+ // in node-only runtime (e.g. `node:crypto`), which breaks the Atlas browser bundle.
4
+ import { AGENT_RUN_STREAM_SCHEMA_VERSION } from "@sixb/core/agents/streams"
5
+ import type { BrokerRecord } from "@sixb/core/broker"
6
+ import type { GetAgentRunResponses } from "./generated/types.gen"
7
+ import {
8
+ createReconnectingSocket,
9
+ createSixbWebSocketUrl,
10
+ type ReconnectingSocket,
11
+ type ReconnectingSocketState,
12
+ } from "./ws-socket"
13
+
14
+ export type { AgentRunStreamEvent } from "@sixb/core/agents/streams"
15
+ export type { ReconnectingSocket, ReconnectingSocketState } from "./ws-socket"
16
+
17
+ export type AgentRunSnapshot = GetAgentRunResponses[200]
18
+
19
+ export interface AgentRunStreamRecord extends Omit<BrokerRecord, "payload"> {
20
+ readonly payload: AgentRunStreamEvent
21
+ }
22
+
23
+ export interface AgentRunStreamSubscribeMessage {
24
+ readonly type: "subscribe"
25
+ readonly runId: string
26
+ readonly afterCursor?: string
27
+ }
28
+
29
+ export interface AgentRunStreamReplayMessage {
30
+ readonly type: "replay"
31
+ readonly runId: string
32
+ readonly afterCursor?: string
33
+ readonly limit?: number
34
+ }
35
+
36
+ export interface AgentRunStreamUnsubscribeMessage {
37
+ readonly type: "unsubscribe"
38
+ readonly runId?: string
39
+ }
40
+
41
+ export type AgentRunStreamClientMessage =
42
+ | AgentRunStreamSubscribeMessage
43
+ | AgentRunStreamReplayMessage
44
+ | AgentRunStreamUnsubscribeMessage
45
+
46
+ export type AgentRunStreamServerMessage =
47
+ | { readonly type: "connected"; readonly channel?: string }
48
+ | { readonly type: "subscribed"; readonly runId: string; readonly afterCursor: string | null }
49
+ | {
50
+ readonly type: "replayed"
51
+ readonly runId: string
52
+ readonly afterCursor: string | null
53
+ readonly count: number
54
+ }
55
+ | { readonly type: "unsubscribed"; readonly runId?: string | null }
56
+ | { readonly type: "error"; readonly message: string }
57
+ | { readonly type: "run.snapshot"; readonly run: AgentRunSnapshot }
58
+ | { readonly type: "record"; readonly record: AgentRunStreamRecord }
59
+
60
+ export function createSixbAgentsWebSocketUrl(baseUrl?: string): string {
61
+ return createSixbWebSocketUrl("/ws/agents", baseUrl)
62
+ }
63
+
64
+ export interface AgentRunSocketOptions {
65
+ readonly runId: string
66
+ readonly afterCursor?: string
67
+ readonly reconnect?: boolean
68
+ readonly reconnectDelayMs?: number
69
+ /** Override the API base url. Defaults to the global client config. */
70
+ readonly baseUrl?: string
71
+ readonly onEvent: (event: AgentRunStreamEvent, cursor: string) => void
72
+ readonly onRunSnapshot?: (run: AgentRunSnapshot) => void
73
+ readonly onError?: (message: string) => void
74
+ readonly onStateChange?: (state: ReconnectingSocketState) => void
75
+ }
76
+
77
+ /**
78
+ * Open a subscribing WebSocket to `/ws/agents` for one run and stream its records to `onEvent`.
79
+ * Tracks the latest cursor across reconnects so no record is replayed. React-free: the
80
+ * `useAgentRunStream` hook is a thin wrapper that mirrors the socket state into React state.
81
+ */
82
+ export function createAgentRunSocket(options: AgentRunSocketOptions): ReconnectingSocket {
83
+ let latestCursor = options.afterCursor
84
+
85
+ return createReconnectingSocket({
86
+ url: createSixbAgentsWebSocketUrl(options.baseUrl),
87
+ reconnect: options.reconnect,
88
+ reconnectDelayMs: options.reconnectDelayMs,
89
+ connectionErrorMessage: "Agent stream websocket connection failed.",
90
+ onError: options.onError,
91
+ onStateChange: options.onStateChange,
92
+ subscribeMessage: () =>
93
+ ({
94
+ type: "subscribe",
95
+ runId: options.runId,
96
+ ...(latestCursor ? { afterCursor: latestCursor } : {}),
97
+ }) satisfies AgentRunStreamSubscribeMessage,
98
+ onMessage: (data, sink) => {
99
+ const message = parseAgentRunStreamServerMessage(data)
100
+ if (!message) return
101
+
102
+ if (message.type === "record") {
103
+ latestCursor = message.record.cursor
104
+ options.onEvent(message.record.payload, message.record.cursor)
105
+ return
106
+ }
107
+
108
+ if (message.type === "run.snapshot") {
109
+ options.onRunSnapshot?.(message.run)
110
+ return
111
+ }
112
+
113
+ if (message.type === "error") {
114
+ sink.reportError(message.message)
115
+ }
116
+ },
117
+ })
118
+ }
119
+
120
+ export function parseAgentRunStreamServerMessage(
121
+ value: unknown
122
+ ): AgentRunStreamServerMessage | null {
123
+ if (typeof value !== "string") {
124
+ return null
125
+ }
126
+
127
+ let parsed: unknown
128
+ try {
129
+ parsed = JSON.parse(value)
130
+ } catch {
131
+ return null
132
+ }
133
+
134
+ if (!isRecord(parsed) || typeof parsed.type !== "string") {
135
+ return null
136
+ }
137
+
138
+ if (parsed.type === "record" && isAgentRunStreamRecord(parsed.record)) {
139
+ return { type: "record", record: parsed.record }
140
+ }
141
+
142
+ if (parsed.type === "run.snapshot" && isAgentRunSnapshot(parsed.run)) {
143
+ return { type: "run.snapshot", run: parsed.run }
144
+ }
145
+
146
+ if (parsed.type === "error") {
147
+ return { type: "error", message: String(parsed.message ?? "Agent stream error.") }
148
+ }
149
+
150
+ if (parsed.type === "connected") {
151
+ return {
152
+ type: "connected",
153
+ ...(typeof parsed.channel === "string" ? { channel: parsed.channel } : {}),
154
+ }
155
+ }
156
+
157
+ if (parsed.type === "subscribed") {
158
+ if (typeof parsed.runId !== "string") {
159
+ return null
160
+ }
161
+
162
+ return {
163
+ type: "subscribed",
164
+ runId: parsed.runId,
165
+ afterCursor: typeof parsed.afterCursor === "string" ? parsed.afterCursor : null,
166
+ }
167
+ }
168
+
169
+ if (parsed.type === "replayed") {
170
+ if (typeof parsed.runId !== "string" || !isFiniteNumber(parsed.count)) {
171
+ return null
172
+ }
173
+
174
+ return {
175
+ type: "replayed",
176
+ runId: parsed.runId,
177
+ afterCursor: typeof parsed.afterCursor === "string" ? parsed.afterCursor : null,
178
+ count: parsed.count,
179
+ }
180
+ }
181
+
182
+ if (parsed.type === "unsubscribed") {
183
+ return {
184
+ type: "unsubscribed",
185
+ ...(typeof parsed.runId === "string" || parsed.runId === null ? { runId: parsed.runId } : {}),
186
+ }
187
+ }
188
+
189
+ return null
190
+ }
191
+
192
+ function isAgentRunSnapshot(value: unknown): value is AgentRunSnapshot {
193
+ return (
194
+ isRecord(value) &&
195
+ typeof value.id === "string" &&
196
+ typeof value.projectId === "string" &&
197
+ typeof value.threadId === "string" &&
198
+ typeof value.agentId === "string" &&
199
+ typeof value.triggerMessageId === "string" &&
200
+ isRecord(value.requestedByPrincipal) &&
201
+ typeof value.requestedByPrincipal.type === "string" &&
202
+ typeof value.requestedByPrincipal.id === "string" &&
203
+ isDurableAgentRunStatus(value.status) &&
204
+ isFiniteNumber(value.attempt) &&
205
+ typeof value.streamId === "string" &&
206
+ typeof value.createdAt === "string"
207
+ )
208
+ }
209
+
210
+ function isAgentRunStreamRecord(value: unknown): value is AgentRunStreamRecord {
211
+ return (
212
+ isRecord(value) &&
213
+ typeof value.streamId === "string" &&
214
+ typeof value.cursor === "string" &&
215
+ (value.name === undefined || typeof value.name === "string") &&
216
+ (value.key === undefined || typeof value.key === "string") &&
217
+ typeof value.publishedAt === "string" &&
218
+ isAgentRunStreamEvent(value.payload)
219
+ )
220
+ }
221
+
222
+ function isAgentRunStreamEvent(value: unknown): value is AgentRunStreamEvent {
223
+ if (
224
+ !isRecord(value) ||
225
+ value.schemaVersion !== AGENT_RUN_STREAM_SCHEMA_VERSION ||
226
+ typeof value.projectId !== "string" ||
227
+ typeof value.runId !== "string" ||
228
+ typeof value.threadId !== "string" ||
229
+ typeof value.agentId !== "string" ||
230
+ !isFiniteNumber(value.attempt) ||
231
+ typeof value.occurredAt !== "string" ||
232
+ typeof value.type !== "string"
233
+ ) {
234
+ return false
235
+ }
236
+
237
+ switch (value.type) {
238
+ case "agent.run.started":
239
+ return value.modelId === undefined || typeof value.modelId === "string"
240
+ case "agent.ui.chunk":
241
+ return Number.isInteger(value.chunkIndex) && Object.hasOwn(value, "chunk")
242
+ case "agent.message.finalized":
243
+ return typeof value.messageId === "string"
244
+ case "agent.run.finished":
245
+ return (
246
+ isAgentRunStatus(value.status) &&
247
+ (value.finishReason === undefined || typeof value.finishReason === "string") &&
248
+ (value.error === undefined || typeof value.error === "string")
249
+ )
250
+ default:
251
+ return false
252
+ }
253
+ }
254
+
255
+ function isDurableAgentRunStatus(value: unknown): value is AgentRunSnapshot["status"] {
256
+ return (
257
+ value === "queued" ||
258
+ value === "running" ||
259
+ value === "succeeded" ||
260
+ value === "failed" ||
261
+ value === "cancelled"
262
+ )
263
+ }
264
+
265
+ function isAgentRunStatus(value: unknown): value is "succeeded" | "failed" | "cancelled" {
266
+ return value === "succeeded" || value === "failed" || value === "cancelled"
267
+ }
268
+
269
+ function isFiniteNumber(value: unknown): value is number {
270
+ return typeof value === "number" && Number.isFinite(value)
271
+ }
272
+
273
+ function isRecord(value: unknown): value is Record<string, unknown> {
274
+ return typeof value === "object" && value !== null
275
+ }
package/src/api.ts ADDED
@@ -0,0 +1,229 @@
1
+ import { type Auth, type Client, type Config, createClient, createConfig } from "./generated/client"
2
+
3
+ export const SIXB_CSRF_HEADER_NAME = "x-sixb-csrf"
4
+ export const SIXB_CSRF_TOKEN_RESPONSE_HEADER_NAME = "x-sixb-csrf-token"
5
+
6
+ export type SixbClient = Client
7
+
8
+ export type SixbClientAuth =
9
+ | {
10
+ readonly kind: "bearer"
11
+ readonly token: string
12
+ }
13
+ | {
14
+ readonly kind: "cookie"
15
+ readonly csrfToken?: () => string | null | undefined
16
+ }
17
+ | {
18
+ readonly kind: "none"
19
+ }
20
+
21
+ export interface SixbClientOptions {
22
+ readonly baseUrl?: string
23
+ readonly auth?: SixbClientAuth
24
+ readonly fetch?: typeof fetch
25
+ readonly headers?: Config["headers"]
26
+ readonly credentials?: RequestCredentials
27
+ }
28
+
29
+ export interface SixbApiErrorInit {
30
+ readonly status: number
31
+ readonly statusText?: string
32
+ readonly url?: string
33
+ readonly method?: string
34
+ readonly body?: unknown
35
+ }
36
+
37
+ /**
38
+ * A structured HTTP error thrown by the Sixb client. The raw generated client
39
+ * throws the bare response body (a string, or parsed JSON) with no status code
40
+ * or identity, which makes failures impossible to branch on and prints as
41
+ * cryptic quoted text in dev tooling. `SixbApiError` carries the status, the
42
+ * parsed `body`, and a readable `message`, so callers and error boundaries can
43
+ * tell a `404` apart from a `500` instead of catching a stringy blob.
44
+ */
45
+ export class SixbApiError extends Error {
46
+ readonly status: number
47
+ readonly statusText: string
48
+ readonly url: string
49
+ readonly method: string
50
+ readonly body: unknown
51
+
52
+ constructor(message: string, init: SixbApiErrorInit) {
53
+ super(message)
54
+ this.name = "SixbApiError"
55
+ this.status = init.status
56
+ this.statusText = init.statusText ?? ""
57
+ this.url = init.url ?? ""
58
+ this.method = init.method ?? ""
59
+ this.body = init.body
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Identifies a `SixbApiError` across bundle boundaries. The custom app and the
65
+ * client are bundled separately, so a plain `instanceof` would miss errors that
66
+ * crossed packages; the structural fallback recognizes them by shape.
67
+ */
68
+ export function isSixbApiError(value: unknown): value is SixbApiError {
69
+ if (value instanceof SixbApiError) {
70
+ return true
71
+ }
72
+ return (
73
+ typeof value === "object" &&
74
+ value !== null &&
75
+ (value as { name?: unknown }).name === "SixbApiError" &&
76
+ typeof (value as { status?: unknown }).status === "number"
77
+ )
78
+ }
79
+
80
+ export function createSixbClient(options: SixbClientOptions = {}): SixbClient {
81
+ const client = createClient(createSixbClientConfig(options))
82
+ installSixbErrorInterceptor(client)
83
+ return client
84
+ }
85
+
86
+ export function configureSixbClient(
87
+ client: SixbClient,
88
+ options: SixbClientOptions = {}
89
+ ): SixbClient {
90
+ client.setConfig(createSixbClientConfig(options))
91
+ installSixbErrorInterceptor(client)
92
+ return client
93
+ }
94
+
95
+ export function createSixbClientConfig(options: SixbClientOptions = {}): Config {
96
+ const auth = options.auth ?? { kind: "none" as const }
97
+ if (auth.kind === "bearer" && !auth.token.trim()) {
98
+ throw new Error("[SixbClient] Bearer token cannot be empty.")
99
+ }
100
+
101
+ return createConfig({
102
+ ...(options.baseUrl === undefined ? {} : { baseUrl: normalizeSixbApiBaseUrl(options.baseUrl) }),
103
+ ...(options.fetch === undefined ? {} : { fetch: options.fetch }),
104
+ ...(options.headers === undefined ? {} : { headers: options.headers }),
105
+ credentials: auth.kind === "cookie" ? "include" : options.credentials,
106
+ auth: auth.kind === "none" ? undefined : createSixbAuthResolver(auth),
107
+ })
108
+ }
109
+
110
+ export function normalizeSixbApiBaseUrl(value: string): string {
111
+ const absolute = /^[a-z][a-z\d+.-]*:\/\//i.test(value)
112
+ let url: URL
113
+
114
+ try {
115
+ url = new URL(value, absolute ? undefined : "http://sixb.local")
116
+ } catch {
117
+ throw new Error(`[SixbClient] Invalid API base URL '${value}'.`)
118
+ }
119
+
120
+ const pathname = stripTrailingApiPath(url.pathname)
121
+ if (!absolute) {
122
+ return pathname
123
+ }
124
+
125
+ return `${url.origin}${pathname === "/" ? "" : pathname}`
126
+ }
127
+
128
+ function createSixbAuthResolver(auth: SixbClientAuth): Config["auth"] {
129
+ return (scheme: Auth) => {
130
+ if (auth.kind === "bearer") {
131
+ return isBearerAuth(scheme) ? auth.token : undefined
132
+ }
133
+
134
+ if (auth.kind === "cookie") {
135
+ return isCsrfAuth(scheme) ? (auth.csrfToken?.() ?? undefined) : undefined
136
+ }
137
+
138
+ return undefined
139
+ }
140
+ }
141
+
142
+ function isBearerAuth(auth: Auth): boolean {
143
+ return auth.type === "http" && auth.scheme === "bearer"
144
+ }
145
+
146
+ function isCsrfAuth(auth: Auth): boolean {
147
+ return auth.type === "apiKey" && auth.in !== "query" && auth.name === SIXB_CSRF_HEADER_NAME
148
+ }
149
+
150
+ function stripTrailingApiPath(pathname: string): string {
151
+ const trimmed = pathname.replace(/\/+$/, "")
152
+ if (!trimmed || trimmed === "/api") {
153
+ return ""
154
+ }
155
+
156
+ if (trimmed.endsWith("/api")) {
157
+ return trimmed.slice(0, -4) || ""
158
+ }
159
+
160
+ return trimmed
161
+ }
162
+
163
+ /**
164
+ * Maps the generated client's raw error (bare body) into a `SixbApiError`.
165
+ * Runs for every failed response regardless of `throwOnError`, so both thrown
166
+ * errors and the `{ error }` result field carry the structured type. Network
167
+ * failures (no `response`) are already native `Error`s and pass through.
168
+ */
169
+ function sixbErrorInterceptor(
170
+ error: unknown,
171
+ response: Response | undefined,
172
+ request: Request | undefined
173
+ ): unknown {
174
+ if (isSixbApiError(error) || !response) {
175
+ return error
176
+ }
177
+
178
+ const method = request?.method ?? ""
179
+ const url = response.url || request?.url || ""
180
+ return new SixbApiError(buildSixbApiErrorMessage(method, url, response, error), {
181
+ status: response.status,
182
+ statusText: response.statusText,
183
+ url,
184
+ method,
185
+ body: error,
186
+ })
187
+ }
188
+
189
+ function buildSixbApiErrorMessage(
190
+ method: string,
191
+ url: string,
192
+ response: Response,
193
+ body: unknown
194
+ ): string {
195
+ const status = response.statusText
196
+ ? `${response.status} ${response.statusText}`
197
+ : String(response.status)
198
+ const target = [method, safeRequestPath(url)].filter(Boolean).join(" ")
199
+ const head = target ? `[SixbClient] ${target} → ${status}` : `[SixbClient] request → ${status}`
200
+ const detail = extractErrorDetail(body)
201
+ return detail ? `${head}: ${detail}` : head
202
+ }
203
+
204
+ function extractErrorDetail(body: unknown): string | undefined {
205
+ if (typeof body === "string") {
206
+ return body.trim() || undefined
207
+ }
208
+ if (body && typeof body === "object" && "error" in body) {
209
+ const message = (body as { error: unknown }).error
210
+ if (typeof message === "string" && message.trim()) {
211
+ return message
212
+ }
213
+ }
214
+ return undefined
215
+ }
216
+
217
+ function safeRequestPath(url: string): string {
218
+ try {
219
+ return new URL(url).pathname
220
+ } catch {
221
+ return url
222
+ }
223
+ }
224
+
225
+ function installSixbErrorInterceptor(client: SixbClient): void {
226
+ if (!client.interceptors.error.exists(sixbErrorInterceptor)) {
227
+ client.interceptors.error.use(sixbErrorInterceptor)
228
+ }
229
+ }