@sixb/cli 0.1.5 → 0.1.7

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 (54) hide show
  1. package/README.md +125 -18
  2. package/dist/commands/init.d.ts +0 -1
  3. package/dist/commands/init.d.ts.map +1 -1
  4. package/dist/commands/login.d.ts +8 -0
  5. package/dist/commands/login.d.ts.map +1 -0
  6. package/dist/commands/logout.d.ts +6 -0
  7. package/dist/commands/logout.d.ts.map +1 -0
  8. package/dist/commands/profile.d.ts +7 -0
  9. package/dist/commands/profile.d.ts.map +1 -0
  10. package/dist/commands/service-account.d.ts +1 -0
  11. package/dist/commands/service-account.d.ts.map +1 -1
  12. package/dist/commands/status.d.ts +8 -0
  13. package/dist/commands/status.d.ts.map +1 -0
  14. package/dist/commands/token.d.ts +1 -0
  15. package/dist/commands/token.d.ts.map +1 -1
  16. package/dist/lib/api-client.d.ts +0 -11
  17. package/dist/lib/api-client.d.ts.map +1 -1
  18. package/dist/lib/command-line.d.ts +176 -0
  19. package/dist/lib/command-line.d.ts.map +1 -0
  20. package/dist/lib/errors.d.ts +6 -0
  21. package/dist/lib/errors.d.ts.map +1 -1
  22. package/dist/lib/instance-command.d.ts +3 -0
  23. package/dist/lib/instance-command.d.ts.map +1 -0
  24. package/dist/lib/loadSixb.d.ts.map +1 -1
  25. package/dist/lib/profile-api-client.d.ts +6 -0
  26. package/dist/lib/profile-api-client.d.ts.map +1 -0
  27. package/dist/lib/profiles.d.ts +34 -0
  28. package/dist/lib/profiles.d.ts.map +1 -0
  29. package/dist/lib/runtime.d.ts.map +1 -1
  30. package/dist/lib/worker-registry.d.ts.map +1 -1
  31. package/dist/ui/index.d.ts +5 -5
  32. package/dist/ui/index.d.ts.map +1 -1
  33. package/package.json +15 -14
  34. package/src/commands/init.tsx +1 -13
  35. package/src/commands/login.tsx +196 -0
  36. package/src/commands/logout.tsx +36 -0
  37. package/src/commands/profile.tsx +101 -0
  38. package/src/commands/service-account.tsx +18 -15
  39. package/src/commands/status.tsx +93 -0
  40. package/src/commands/token.tsx +11 -8
  41. package/src/index.tsx +134 -156
  42. package/src/lib/api-client.ts +4 -65
  43. package/src/lib/command-line.ts +743 -0
  44. package/src/lib/errors.ts +13 -0
  45. package/src/lib/instance-command.ts +80 -0
  46. package/src/lib/loadSixb.ts +0 -2
  47. package/src/lib/profile-api-client.ts +38 -0
  48. package/src/lib/profiles.ts +262 -0
  49. package/src/lib/runtime.ts +7 -1
  50. package/src/lib/worker-registry.ts +7 -1
  51. package/src/ui/index.tsx +39 -140
  52. package/dist/commands/auth.d.ts +0 -8
  53. package/dist/commands/auth.d.ts.map +0 -1
  54. package/src/commands/auth.tsx +0 -96
@@ -0,0 +1,93 @@
1
+ import { CliError, createInstanceApiClient, writeJson } from "@sixb/cli-core"
2
+ import { resolveProfile } from "../lib/profiles"
3
+ import { KeyValueResultView, renderStatic } from "../ui"
4
+
5
+ export interface StatusCommandOptions {
6
+ readonly apiUrl?: string
7
+ readonly token?: string
8
+ readonly profile?: string
9
+ readonly json?: boolean
10
+ }
11
+
12
+ export async function runStatus(options: StatusCommandOptions = {}): Promise<void> {
13
+ const resolved = await resolveProfile(options)
14
+ try {
15
+ const project = await createInstanceApiClient({
16
+ kind: "local",
17
+ baseUrl: resolved.apiUrl,
18
+ ...(resolved.token ? { token: resolved.token } : {}),
19
+ ...(resolved.profile ? { profile: resolved.profile } : {}),
20
+ }).get("/api/project")
21
+ const projectId = projectIdFrom(project)
22
+ await renderStatus({
23
+ connected: true,
24
+ authenticated: Boolean(resolved.token),
25
+ apiUrl: resolved.apiUrl,
26
+ source: resolved.source,
27
+ ...(resolved.profile ? { profile: resolved.profile } : {}),
28
+ projectId,
29
+ json: options.json,
30
+ })
31
+ } catch (error) {
32
+ if (!(error instanceof CliError) || (error.body.status !== 401 && error.body.status !== 403)) {
33
+ throw error
34
+ }
35
+ await renderStatus({
36
+ connected: true,
37
+ authenticated: false,
38
+ apiUrl: resolved.apiUrl,
39
+ source: resolved.source,
40
+ ...(resolved.profile ? { profile: resolved.profile } : {}),
41
+ message: error.message,
42
+ json: options.json,
43
+ })
44
+ process.exitCode = 1
45
+ }
46
+ }
47
+
48
+ async function renderStatus(input: {
49
+ readonly connected: boolean
50
+ readonly authenticated: boolean
51
+ readonly apiUrl: string
52
+ readonly source: string
53
+ readonly profile?: string
54
+ readonly projectId?: string
55
+ readonly message?: string
56
+ readonly json?: boolean
57
+ }): Promise<void> {
58
+ if (input.json) {
59
+ const { json: _json, ...result } = input
60
+ writeJson(result)
61
+ return
62
+ }
63
+
64
+ await renderStatic(
65
+ <KeyValueResultView
66
+ title={input.message ? "Authentication failed" : "Connected"}
67
+ titleColor={input.message ? "red" : "green"}
68
+ items={[
69
+ ...(input.profile ? [{ label: "Profile", value: input.profile }] : []),
70
+ ...(input.projectId ? [{ label: "Project", value: input.projectId }] : []),
71
+ { label: "API", value: input.apiUrl },
72
+ {
73
+ label: "Authentication",
74
+ value: input.authenticated ? "token" : input.message ? "failed" : "not required",
75
+ },
76
+ ]}
77
+ message={input.message}
78
+ />
79
+ )
80
+ }
81
+
82
+ function projectIdFrom(value: unknown): string {
83
+ if (
84
+ typeof value !== "object" ||
85
+ value === null ||
86
+ !("id" in value) ||
87
+ typeof value.id !== "string" ||
88
+ !value.id.trim()
89
+ ) {
90
+ throw new Error("[SixbCLI] The Sixb API returned project metadata without a project id.")
91
+ }
92
+ return value.id.trim()
93
+ }
@@ -1,9 +1,11 @@
1
+ import { writeJson } from "@sixb/cli-core"
1
2
  import {
2
3
  createAuthPersonalAccessToken,
3
4
  listAuthAccessTokens,
4
5
  revokeAuthAccessToken,
5
6
  } from "@sixb/client"
6
- import { createCliSixbClient, resolveApiClientConfig, unwrapSixbApiResult } from "../lib/api-client"
7
+ import { createCliSixbClient, unwrapSixbApiResult } from "../lib/api-client"
8
+ import { resolveProfileApiClientConfig } from "../lib/profile-api-client"
7
9
  import { KeyValueResultView, renderStatic, SecretResultView, TableResultView } from "../ui"
8
10
  import {
9
11
  formatDate,
@@ -17,6 +19,7 @@ export interface TokenCommandOptions {
17
19
  readonly positionals?: readonly string[]
18
20
  readonly apiUrl?: string
19
21
  readonly token?: string
22
+ readonly profile?: string
20
23
  readonly id?: string
21
24
  readonly name?: string
22
25
  readonly expiresAt?: string
@@ -26,7 +29,7 @@ export interface TokenCommandOptions {
26
29
  }
27
30
 
28
31
  export async function runToken(options: TokenCommandOptions = {}) {
29
- const action = options.action ?? "list"
32
+ const action = options.action
30
33
  if (action === "list") {
31
34
  await listTokens(options)
32
35
  return
@@ -46,11 +49,11 @@ export async function runToken(options: TokenCommandOptions = {}) {
46
49
  }
47
50
 
48
51
  async function listTokens(options: TokenCommandOptions) {
49
- const client = createCliSixbClient(resolveApiClientConfig(options))
52
+ const client = createCliSixbClient(await resolveProfileApiClientConfig(options))
50
53
  const result = unwrapSixbApiResult(await listAuthAccessTokens({ client }))
51
54
 
52
55
  if (options.json) {
53
- console.log(JSON.stringify(result, null, 2))
56
+ writeJson(result)
54
57
  return
55
58
  }
56
59
 
@@ -80,7 +83,7 @@ async function createToken(options: TokenCommandOptions) {
80
83
 
81
84
  const expiresAt = resolveExpiration(options)
82
85
  const groupIds = normalizeGroupIds(options.groupIds)
83
- const client = createCliSixbClient(resolveApiClientConfig(options))
86
+ const client = createCliSixbClient(await resolveProfileApiClientConfig(options))
84
87
  const result = unwrapSixbApiResult(
85
88
  await createAuthPersonalAccessToken({
86
89
  client,
@@ -93,7 +96,7 @@ async function createToken(options: TokenCommandOptions) {
93
96
  )
94
97
 
95
98
  if (options.json) {
96
- console.log(JSON.stringify(result, null, 2))
99
+ writeJson(result)
97
100
  return
98
101
  }
99
102
 
@@ -117,7 +120,7 @@ async function revokeToken(options: TokenCommandOptions) {
117
120
  throw new Error("Usage: sixb token revoke <token-id>")
118
121
  }
119
122
 
120
- const client = createCliSixbClient(resolveApiClientConfig(options))
123
+ const client = createCliSixbClient(await resolveProfileApiClientConfig(options))
121
124
  const result = unwrapSixbApiResult(
122
125
  await revokeAuthAccessToken({
123
126
  client,
@@ -126,7 +129,7 @@ async function revokeToken(options: TokenCommandOptions) {
126
129
  )
127
130
 
128
131
  if (options.json) {
129
- console.log(JSON.stringify(result, null, 2))
132
+ writeJson(result)
130
133
  return
131
134
  }
132
135
 
package/src/index.tsx CHANGED
@@ -1,7 +1,18 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
3
  import { join } from "node:path"
4
- import { HelpView, renderCliError, renderStatic, VersionView } from "./ui"
4
+ import { CliError } from "@sixb/cli-core"
5
+ import {
6
+ booleanOption,
7
+ type CliOptionName,
8
+ CliUsageError,
9
+ parseCliArgs,
10
+ repeatedOption,
11
+ stringOption,
12
+ wantsManagementJson,
13
+ } from "./lib/command-line"
14
+ import { errorMessage, SixbApiError } from "./lib/errors"
15
+ import { CommandHelpView, HelpView, renderCliError, renderStatic, VersionView } from "./ui"
5
16
 
6
17
  const args = process.argv.slice(2)
7
18
 
@@ -59,121 +70,29 @@ async function readPackageVersion(): Promise<string> {
59
70
  }
60
71
  }
61
72
 
62
- function getFlag(name: string): string | undefined {
63
- const direct = args.find((arg) => arg.startsWith(`--${name}=`))
64
- if (direct) return direct.slice(name.length + 3)
65
-
66
- const idx = args.indexOf(`--${name}`)
67
- if (idx >= 0) return args[idx + 1]
68
-
69
- return undefined
70
- }
71
-
72
- function getFlags(name: string, options: { readonly includeMissing?: boolean } = {}): string[] {
73
- const values: string[] = []
74
-
75
- for (let index = 0; index < args.length; index++) {
76
- const arg = args[index]
77
- if (arg === `--${name}`) {
78
- const value = args[index + 1]
79
- if (value && !value.startsWith("--")) {
80
- values.push(value)
81
- index++
82
- } else if (options.includeMissing) {
83
- values.push("")
84
- }
85
- } else if (arg?.startsWith(`--${name}=`)) {
86
- values.push(arg.slice(name.length + 3))
87
- }
88
- }
89
-
90
- return values
91
- }
92
-
93
- function getFlagRequiringValue(name: string): string | undefined {
94
- const value = getFlag(name)
95
- return value ?? (hasFlagValue(name) ? "" : undefined)
96
- }
97
-
98
- function hasFlag(name: string): boolean {
99
- return args.includes(`--${name}`)
100
- }
101
-
102
- function hasFlagValue(name: string): boolean {
103
- return hasFlag(name) || args.some((arg) => arg.startsWith(`--${name}=`))
104
- }
105
-
106
- const flagsWithValues = new Set([
107
- "entry",
108
- "port",
109
- "host",
110
- "api-port",
111
- "api-host",
112
- "api-public-origin",
113
- "agent-turn-timeout",
114
- "concurrency",
115
- "atlas-public-origin",
116
- "app-public-origin",
117
- "outdir",
118
- "dir",
119
- "expire-older-than",
120
- "delete-older-than",
121
- "api-url",
122
- "token",
123
- "id",
124
- "name",
125
- "description",
126
- "expires-at",
127
- "expires-in",
128
- "group",
129
- ])
130
-
131
- function getCommandPositionals(): string[] {
132
- const values: string[] = []
133
-
134
- for (let index = 1; index < args.length; index++) {
135
- const arg = args[index]
136
- if (!arg) continue
137
-
138
- if (arg.startsWith("--")) {
139
- const flagName = arg.slice(2).split("=")[0] ?? ""
140
- const next = args[index + 1]
141
- if (!arg.includes("=") && flagsWithValues.has(flagName) && next && !next.startsWith("--")) {
142
- index++
143
- }
144
- continue
145
- }
146
-
147
- values.push(arg)
148
- }
149
-
150
- return values
151
- }
152
-
153
- function getCommand(): string {
154
- if (args[0] === "db") {
155
- return args[1] ? `db:${args[1]}` : "db"
156
- }
157
- if (args[0] === "lake") {
158
- return args[1] ? `lake:${args[1]}` : "lake"
159
- }
160
- return args[0] ?? "help"
161
- }
162
-
163
73
  async function main(): Promise<void> {
164
- const command = getCommand()
165
-
166
- if (hasFlag("help") || command === "help") {
167
- await renderStatic(<HelpView />)
74
+ const parsed = parseCliArgs(args)
75
+ if (parsed.kind === "version") {
76
+ await renderStatic(<VersionView version={VERSION} />)
168
77
  return
169
78
  }
170
-
171
- if (hasFlag("version") || command === "--version" || command === "-v") {
172
- await renderStatic(<VersionView version={VERSION} />)
79
+ if (parsed.kind === "help") {
80
+ if (parsed.help.path.length === 0) await renderStatic(<HelpView />)
81
+ else await renderStatic(<CommandHelpView help={parsed.help} />)
82
+ return
83
+ }
84
+ if (parsed.kind === "instance") {
85
+ const { runLocalInstanceCommand } = await import("./lib/instance-command")
86
+ await runLocalInstanceCommand(parsed.args)
173
87
  return
174
88
  }
175
89
 
176
- switch (command) {
90
+ const { options, positionals } = parsed
91
+ const getFlag = (name: CliOptionName) => stringOption(options, name)
92
+ const getFlags = (name: CliOptionName) => repeatedOption(options, name)
93
+ const hasFlag = (name: CliOptionName) => booleanOption(options, name)
94
+
95
+ switch (parsed.id) {
177
96
  case "dev": {
178
97
  const { runDev } = await import("./commands/dev")
179
98
  await runDev({
@@ -186,24 +105,20 @@ async function main(): Promise<void> {
186
105
  atlasPublicOrigin: getFlag("atlas-public-origin"),
187
106
  appPublicOrigin: getFlag("app-public-origin"),
188
107
  agentTurnTimeout: getFlag("agent-turn-timeout"),
189
- concurrency: getFlags("concurrency", { includeMissing: true }),
108
+ concurrency: getFlags("concurrency"),
190
109
  })
191
110
  break
192
111
  }
193
112
 
194
113
  case "worker": {
195
- if (hasFlagValue("type") || hasFlagValue("worker")) {
196
- throw new Error("[SixbWorker] Use `sixb worker <type>`.")
197
- }
198
-
199
114
  const { runWorker } = await import("./commands/worker")
200
115
  await runWorker({
201
116
  entry: getFlag("entry"),
202
117
  noMigrate: hasFlag("no-migrate"),
203
- workerType: getCommandPositionals()[0],
118
+ workerType: positionals[0],
204
119
  apiPublicOrigin: getFlag("api-public-origin"),
205
120
  agentTurnTimeout: getFlag("agent-turn-timeout"),
206
- concurrency: getFlagRequiringValue("concurrency"),
121
+ concurrency: getFlag("concurrency"),
207
122
  })
208
123
  break
209
124
  }
@@ -213,10 +128,10 @@ async function main(): Promise<void> {
213
128
  await runWorkerGroup({
214
129
  entry: getFlag("entry"),
215
130
  noMigrate: hasFlag("no-migrate"),
216
- workerTypes: getCommandPositionals(),
131
+ workerTypes: positionals,
217
132
  apiPublicOrigin: getFlag("api-public-origin"),
218
133
  agentTurnTimeout: getFlag("agent-turn-timeout"),
219
- concurrency: getFlags("concurrency", { includeMissing: true }),
134
+ concurrency: getFlags("concurrency"),
220
135
  })
221
136
  break
222
137
  }
@@ -261,26 +176,57 @@ async function main(): Promise<void> {
261
176
  break
262
177
  }
263
178
 
264
- case "auth": {
265
- const { runAuth } = await import("./commands/auth")
266
- const positionals = getCommandPositionals()
267
- await runAuth({
268
- action: positionals[0],
179
+ case "login": {
180
+ const { runLogin } = await import("./commands/login")
181
+ await runLogin({
182
+ apiUrl: positionals[0],
183
+ profile: getFlag("profile"),
184
+ tokenStdin: hasFlag("token-stdin"),
185
+ json: hasFlag("json"),
186
+ })
187
+ break
188
+ }
189
+
190
+ case "logout": {
191
+ const { runLogout } = await import("./commands/logout")
192
+ await runLogout({ profile: getFlag("profile"), json: hasFlag("json") })
193
+ break
194
+ }
195
+
196
+ case "status": {
197
+ const { runStatus } = await import("./commands/status")
198
+ await runStatus({
269
199
  apiUrl: getFlag("api-url"),
270
200
  token: getFlag("token"),
201
+ profile: getFlag("profile"),
271
202
  json: hasFlag("json"),
272
203
  })
273
204
  break
274
205
  }
275
206
 
276
- case "token": {
207
+ case "profile:list":
208
+ case "profile:show":
209
+ case "profile:use": {
210
+ const { runProfile } = await import("./commands/profile")
211
+ await runProfile({
212
+ action: parsed.id.slice("profile:".length),
213
+ name: positionals[0],
214
+ json: hasFlag("json"),
215
+ })
216
+ break
217
+ }
218
+
219
+ case "token:list":
220
+ case "token:create":
221
+ case "token:revoke": {
277
222
  const { runToken } = await import("./commands/token")
278
- const positionals = getCommandPositionals()
223
+ const action = parsed.id.slice("token:".length)
279
224
  await runToken({
280
- action: positionals[0],
281
- positionals,
225
+ action,
226
+ positionals: [action, ...positionals],
282
227
  apiUrl: getFlag("api-url"),
283
228
  token: getFlag("token"),
229
+ profile: getFlag("profile"),
284
230
  id: getFlag("id"),
285
231
  name: getFlag("name"),
286
232
  expiresAt: getFlag("expires-at"),
@@ -291,12 +237,19 @@ async function main(): Promise<void> {
291
237
  break
292
238
  }
293
239
 
294
- case "service-account": {
240
+ case "service-account:list":
241
+ case "service-account:create":
242
+ case "service-account:disable":
243
+ case "service-account:token:list":
244
+ case "service-account:token:create":
245
+ case "service-account:token:revoke": {
295
246
  const { runServiceAccount } = await import("./commands/service-account")
247
+ const commandPath = parsed.id.split(":").slice(1)
296
248
  await runServiceAccount({
297
- positionals: getCommandPositionals(),
249
+ positionals: [...commandPath, ...positionals],
298
250
  apiUrl: getFlag("api-url"),
299
251
  token: getFlag("token"),
252
+ profile: getFlag("profile"),
300
253
  id: getFlag("id"),
301
254
  name: getFlag("name"),
302
255
  description: getFlag("description"),
@@ -368,39 +321,64 @@ async function main(): Promise<void> {
368
321
  }
369
322
 
370
323
  case "init": {
371
- const dir = args[1] && !args[1].startsWith("-") ? args[1] : undefined
372
324
  const { runInit } = await import("./commands/init")
373
- await runInit(dir)
325
+ await runInit(positionals[0])
374
326
  break
375
327
  }
376
328
 
377
- case "create": {
378
- const positionals = getCommandPositionals()
379
- if (positionals.length !== 1) {
380
- throw new Error("Usage: sixb create <project-name>")
381
- }
382
- const { runCreate } = await import("./commands/init")
383
- await runCreate(positionals[0]!)
384
- break
385
- }
386
-
387
- case "db":
388
- await renderStatic(<HelpView errorMessage="Usage: sixb db <migrate>" />)
389
- process.exit(1)
390
- break
391
-
392
- case "lake":
393
- await renderStatic(<HelpView errorMessage="Usage: sixb lake <check|cleanup>" />)
394
- process.exit(1)
395
- break
396
-
397
329
  default:
398
- await renderStatic(<HelpView errorMessage={`Unknown command: ${command}`} />)
399
- process.exit(1)
330
+ assertNever(parsed.id)
400
331
  }
401
332
  }
402
333
 
403
334
  main().catch(async (error) => {
404
- await renderCliError(error)
405
- process.exit(1)
335
+ const exitCode = cliExitCode(error)
336
+ if (wantsManagementJson(args)) {
337
+ process.stderr.write(`${JSON.stringify({ error: cliErrorBody(error) })}\n`)
338
+ } else if (error instanceof CliUsageError) {
339
+ if (error.help.path.length === 0) {
340
+ await renderStatic(<HelpView errorMessage={error.message} />)
341
+ } else {
342
+ await renderStatic(<CommandHelpView help={error.help} errorMessage={error.message} />)
343
+ }
344
+ } else {
345
+ await renderCliError(error)
346
+ }
347
+ process.exit(exitCode)
406
348
  })
349
+
350
+ function cliExitCode(error: unknown): number {
351
+ if (error instanceof CliUsageError) return error.exitCode
352
+ if (error instanceof CliError) return error.exitCode
353
+ if (error instanceof SixbApiError) return 3
354
+ if (errorMessage(error).startsWith("Usage:")) return 2
355
+ return 1
356
+ }
357
+
358
+ function cliErrorBody(error: unknown): {
359
+ readonly code: string
360
+ readonly status?: number
361
+ readonly message: string
362
+ readonly hint?: string
363
+ readonly issues?: readonly unknown[]
364
+ } {
365
+ if (error instanceof CliError) return error.body
366
+ if (error instanceof CliUsageError) {
367
+ return { code: "invalid_arguments", message: error.message, hint: error.help.usage }
368
+ }
369
+ if (error instanceof SixbApiError) {
370
+ return {
371
+ code: "api_error",
372
+ ...(error.status === undefined ? {} : { status: error.status }),
373
+ message: error.message,
374
+ }
375
+ }
376
+ return {
377
+ code: errorMessage(error).startsWith("Usage:") ? "invalid_arguments" : "command_failed",
378
+ message: errorMessage(error),
379
+ }
380
+ }
381
+
382
+ function assertNever(value: never): never {
383
+ throw new Error(`[SixbCLI] Command '${String(value)}' has no handler.`)
384
+ }
@@ -1,4 +1,5 @@
1
1
  import { createSixbClient, normalizeSixbApiBaseUrl, type SixbClient } from "@sixb/client"
2
+ import { SixbApiError } from "./errors"
2
3
 
3
4
  export interface SixbApiClientConfig {
4
5
  readonly apiUrl: string
@@ -7,55 +8,11 @@ export interface SixbApiClientConfig {
7
8
  readonly tokenSource?: string
8
9
  }
9
10
 
10
- export interface ResolveApiClientConfigOptions {
11
- readonly apiUrl?: string
12
- readonly token?: string
13
- readonly env?: Record<string, string | undefined>
14
- }
15
-
16
- export class SixbApiError extends Error {
17
- readonly status: number | undefined
18
- readonly responseBody: unknown
19
-
20
- constructor(message: string, status: number | undefined, responseBody: unknown) {
21
- super(message)
22
- this.name = "SixbApiError"
23
- this.status = status
24
- this.responseBody = responseBody
25
- }
26
- }
27
-
28
- export function resolveApiClientConfig(
29
- options: ResolveApiClientConfigOptions = {}
30
- ): SixbApiClientConfig {
31
- const env = options.env ?? process.env
32
- const apiUrlCandidate = firstConfigValue([
33
- ["--api-url", options.apiUrl],
34
- ["SIXB_API_URL", env.SIXB_API_URL],
35
- ["SIXB_API_PUBLIC_ORIGIN", env.SIXB_API_PUBLIC_ORIGIN],
36
- ]) ?? { source: "default", value: "http://localhost:3002" }
37
- const tokenCandidate = firstConfigValue([
38
- ["--token", options.token],
39
- ["SIXB_API_TOKEN", env.SIXB_API_TOKEN],
40
- ["SIXB_TOKEN", env.SIXB_TOKEN],
41
- ])
42
- const apiUrl = normalizeApiUrl(apiUrlCandidate.value)
43
-
44
- return {
45
- apiUrl,
46
- apiUrlSource: apiUrlCandidate.source,
47
- ...(tokenCandidate
48
- ? {
49
- token: tokenCandidate.value,
50
- tokenSource: tokenCandidate.source,
51
- }
52
- : {}),
53
- }
54
- }
55
-
56
11
  export function createCliSixbClient(config: SixbApiClientConfig): SixbClient {
57
12
  if (!config.token) {
58
- throw new Error("[SixbCLI] Missing API token. Set SIXB_API_TOKEN or pass --token.")
13
+ throw new Error(
14
+ "[SixbCLI] Missing API token. Run `sixb login <api-url>`, select a profile, or set SIXB_API_TOKEN."
15
+ )
59
16
  }
60
17
 
61
18
  return createSixbClient({
@@ -96,24 +53,6 @@ export function normalizeApiUrl(value: string): string {
96
53
  }
97
54
  }
98
55
 
99
- function firstConfigValue(
100
- entries: readonly (readonly [source: string, value: string | undefined])[]
101
- ): { readonly source: string; readonly value: string } | undefined {
102
- for (const [source, raw] of entries) {
103
- const value = nonEmpty(raw)
104
- if (value !== undefined) {
105
- return { source, value }
106
- }
107
- }
108
-
109
- return undefined
110
- }
111
-
112
- function nonEmpty(value: string | undefined): string | undefined {
113
- const trimmed = value?.trim()
114
- return trimmed ? trimmed : undefined
115
- }
116
-
117
56
  function formatApiError(status: number | undefined, body: unknown): string {
118
57
  const statusLabel = status === undefined ? "network" : String(status)
119
58
  if (typeof body === "object" && body && "error" in body && typeof body.error === "string") {