omnara 0.6.1 → 1.0.0-beta.0

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.
package/src/flags.ts ADDED
@@ -0,0 +1,174 @@
1
+ import * as z from 'zod'
2
+
3
+ export type FlagValueKind = 'string' | 'number' | 'boolean' | 'json' | 'stringArray'
4
+
5
+ export interface FlagSpec {
6
+ path: string[]
7
+ flag: string
8
+ optionKey: string
9
+ kind: FlagValueKind
10
+ required: boolean
11
+ description: string
12
+ }
13
+
14
+ type JsonSchema = z.core.JSONSchema.BaseSchema
15
+
16
+ export function kebabCase(name: string): string {
17
+ return name
18
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
19
+ .replaceAll('_', '-')
20
+ .toLowerCase()
21
+ }
22
+
23
+ function camelCase(flag: string): string {
24
+ return flag.replace(/-(\w)/g, (_, letter: string) => letter.toUpperCase())
25
+ }
26
+
27
+ interface ObjectMember {
28
+ schema: JsonSchema
29
+ conditional: boolean
30
+ }
31
+
32
+ function objectMembers(schema: JsonSchema, conditional: boolean): ObjectMember[] {
33
+ const members: ObjectMember[] = []
34
+ if (schema.properties !== undefined) members.push({ schema, conditional })
35
+ for (const member of schema.allOf ?? []) {
36
+ members.push(...objectMembers(member, conditional))
37
+ }
38
+ for (const variants of [schema.anyOf, schema.oneOf]) {
39
+ for (const variant of variants ?? []) {
40
+ members.push(...objectMembers(variant, true))
41
+ }
42
+ }
43
+ return members
44
+ }
45
+
46
+ function nonNullVariants(property: JsonSchema): JsonSchema[] | undefined {
47
+ const variants = property.anyOf ?? property.oneOf
48
+ if (variants === undefined) return undefined
49
+ return variants.filter((variant) => variant.type !== 'null')
50
+ }
51
+
52
+ function flagKind(property: JsonSchema): FlagValueKind {
53
+ if (property.const !== undefined) {
54
+ const kind = typeof property.const
55
+ return kind === 'string' || kind === 'number' || kind === 'boolean' ? kind : 'json'
56
+ }
57
+ if (property.enum !== undefined) return 'string'
58
+ const variants = nonNullVariants(property)
59
+ if (variants !== undefined) {
60
+ const kinds = new Set(variants.map(flagKind))
61
+ const [first] = kinds
62
+ return kinds.size === 1 && first !== undefined ? first : 'json'
63
+ }
64
+ switch (property.type) {
65
+ case 'string':
66
+ return 'string'
67
+ case 'integer':
68
+ case 'number':
69
+ return 'number'
70
+ case 'boolean':
71
+ return 'boolean'
72
+ case 'array': {
73
+ const items = property.items
74
+ return typeof items === 'object' &&
75
+ !Array.isArray(items) &&
76
+ items.type === 'string' &&
77
+ items.enum === undefined
78
+ ? 'stringArray'
79
+ : 'json'
80
+ }
81
+ default:
82
+ return 'json'
83
+ }
84
+ }
85
+
86
+ function enumChoices(property: JsonSchema): (string | number)[] | undefined {
87
+ if (typeof property.const === 'string' || typeof property.const === 'number') {
88
+ return [property.const]
89
+ }
90
+ if (property.enum !== undefined) {
91
+ const choices = property.enum.filter(
92
+ (value) => typeof value === 'string' || typeof value === 'number',
93
+ )
94
+ return choices.length > 0 ? choices : undefined
95
+ }
96
+ const variants = nonNullVariants(property)
97
+ const only = variants?.length === 1 ? variants[0] : undefined
98
+ return only === undefined ? undefined : enumChoices(only)
99
+ }
100
+
101
+ interface FlagDraft {
102
+ path: string[]
103
+ kind: FlagValueKind
104
+ required: boolean
105
+ description: string | undefined
106
+ choices: (string | number)[] | undefined
107
+ }
108
+
109
+ function expandsToFlags(property: JsonSchema): boolean {
110
+ return objectMembers(property, false).length > 0
111
+ }
112
+
113
+ function collectDrafts(
114
+ drafts: Map<string, FlagDraft>,
115
+ schema: JsonSchema,
116
+ prefix: string[],
117
+ conditional: boolean,
118
+ ): void {
119
+ for (const member of objectMembers(schema, conditional)) {
120
+ const required = new Set(member.schema.required ?? [])
121
+ for (const [key, property] of Object.entries(member.schema.properties ?? {})) {
122
+ if (typeof property === 'boolean') continue
123
+ const path = [...prefix, key]
124
+ const propertyRequired = !member.conditional && required.has(key)
125
+ if (expandsToFlags(property)) {
126
+ collectDrafts(drafts, property, path, !propertyRequired)
127
+ continue
128
+ }
129
+ const choices = enumChoices(property)
130
+ const description = property.description?.split('\n')[0]
131
+ const existing = drafts.get(path.join('.'))
132
+ if (existing !== undefined) {
133
+ existing.required = existing.required || propertyRequired
134
+ existing.description ??= description
135
+ existing.choices =
136
+ existing.choices !== undefined && choices !== undefined
137
+ ? [...new Set([...existing.choices, ...choices])]
138
+ : undefined
139
+ continue
140
+ }
141
+ drafts.set(path.join('.'), {
142
+ path,
143
+ kind: flagKind(property),
144
+ required: propertyRequired,
145
+ description,
146
+ choices,
147
+ })
148
+ }
149
+ }
150
+ }
151
+
152
+ function finalizeFlag(draft: FlagDraft): FlagSpec {
153
+ const flag = draft.path.map(kebabCase).join('-')
154
+ const parts: string[] = []
155
+ if (draft.description !== undefined) parts.push(draft.description)
156
+ if (draft.choices !== undefined) parts.push(`choices: ${draft.choices.join(', ')}`)
157
+ if (draft.kind === 'json') parts.push('JSON value')
158
+ if (draft.kind === 'stringArray') parts.push('repeatable')
159
+ return {
160
+ path: draft.path,
161
+ flag,
162
+ optionKey: camelCase(flag),
163
+ kind: draft.kind,
164
+ required: draft.required,
165
+ description: parts.join(' — '),
166
+ }
167
+ }
168
+
169
+ export function deriveFlags(schema: z.ZodType): FlagSpec[] {
170
+ const jsonSchema: JsonSchema = z.toJSONSchema(schema, { io: 'input' })
171
+ const drafts = new Map<string, FlagDraft>()
172
+ collectDrafts(drafts, jsonSchema, [], false)
173
+ return [...drafts.values()].map(finalizeFlag)
174
+ }
package/src/format.ts ADDED
@@ -0,0 +1,45 @@
1
+ export interface FormattedOutput {
2
+ value: unknown
3
+ columns?: readonly string[]
4
+ }
5
+
6
+ export type OutputFormat<Response> = (data: Response) => FormattedOutput
7
+
8
+ interface ListEnvelope<Item> {
9
+ data: Item[]
10
+ next_cursor: string | null
11
+ }
12
+
13
+ type FieldName<Value> = Extract<keyof Value, string>
14
+
15
+ function pickFields<Value extends object>(
16
+ source: Value,
17
+ fields: readonly FieldName<Value>[],
18
+ ): Record<string, unknown> {
19
+ const picked: Record<string, unknown> = {}
20
+ for (const field of fields) {
21
+ const value = source[field]
22
+ if (value !== undefined) picked[field] = value
23
+ }
24
+ return picked
25
+ }
26
+
27
+ export function formatTable<Item extends object>(
28
+ columns: readonly FieldName<Item>[],
29
+ ): OutputFormat<ListEnvelope<Item>> {
30
+ return (response) => ({
31
+ value: {
32
+ data: response.data.map((item) => pickFields(item, columns)),
33
+ next_cursor: response.next_cursor,
34
+ },
35
+ columns,
36
+ })
37
+ }
38
+
39
+ export function formatRecord<Value extends object>(): OutputFormat<Value> {
40
+ return (data) => ({ value: data })
41
+ }
42
+
43
+ export function formatVoid(message = 'ok'): OutputFormat<void> {
44
+ return () => ({ value: message })
45
+ }
@@ -0,0 +1,56 @@
1
+ import { isCancel, select } from '@clack/prompts'
2
+ import { type OmnaraClient, sdk } from '@omnara/sdk'
3
+
4
+ import { CliInputError } from './output.ts'
5
+
6
+ export function canPromptInteractively(): boolean {
7
+ return process.stdin.isTTY && process.stdout.isTTY
8
+ }
9
+
10
+ interface Choice {
11
+ id: string
12
+ label: string
13
+ }
14
+
15
+ async function selectFrom(message: string, choices: Choice[]): Promise<string> {
16
+ const [only] = choices
17
+ if (choices.length === 1 && only !== undefined) {
18
+ console.log(`${message}: ${only.label} (only option)`)
19
+ return only.id
20
+ }
21
+ const picked = await select({
22
+ message,
23
+ options: choices.map((choice) => ({ value: choice.id, label: choice.label, hint: choice.id })),
24
+ })
25
+ if (isCancel(picked)) throw new CliInputError('selection cancelled')
26
+ return picked
27
+ }
28
+
29
+ export async function promptOrgSelection(client: OmnaraClient): Promise<string> {
30
+ const { data } = await sdk.getCurrentUser({ client })
31
+ if (data.orgs.length === 0) {
32
+ throw new CliInputError('this account has no organizations')
33
+ }
34
+ return selectFrom(
35
+ 'Select an organization',
36
+ data.orgs.map((org) => ({ id: org.id, label: org.name })),
37
+ )
38
+ }
39
+
40
+ export async function promptProjectSelection(client: OmnaraClient, orgId: string): Promise<string> {
41
+ const projects: Choice[] = []
42
+ let cursor: string | undefined
43
+ do {
44
+ const { data } = await sdk.listVisibleProjects({
45
+ client,
46
+ path: { orgID: orgId },
47
+ query: cursor === undefined ? {} : { cursor },
48
+ })
49
+ projects.push(...data.data.map((project) => ({ id: project.id, label: project.name })))
50
+ cursor = data.next_cursor ?? undefined
51
+ } while (cursor !== undefined)
52
+ if (projects.length === 0) {
53
+ throw new CliInputError(`no projects visible in organization ${orgId}`)
54
+ }
55
+ return selectFrom('Select a project', projects)
56
+ }
@@ -0,0 +1,131 @@
1
+ import { Command } from 'commander'
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3
+
4
+ import type { CliConfig } from './config.ts'
5
+ import { registerLoginCommand } from './login.ts'
6
+
7
+ const mocks = vi.hoisted(() => ({
8
+ bearerToken: vi.fn(() => ({ authenticate: vi.fn() })),
9
+ createOmnaraClient: vi.fn(() => ({ authenticated: true })),
10
+ getCurrentUser: vi.fn(() =>
11
+ Promise.resolve({
12
+ data: {
13
+ user: { email: 'person@example.com', display_name: 'Person' },
14
+ orgs: [],
15
+ },
16
+ }),
17
+ ),
18
+ pollDeviceAuthToken: vi.fn(() => Promise.resolve('omnara_pat_v1_test')),
19
+ readConfigFile: vi.fn(() => ({})),
20
+ startDeviceAuth: vi.fn(() =>
21
+ Promise.resolve({
22
+ deviceCode: 'device-code',
23
+ userCode: 'ABCDE-FGHIJ',
24
+ verificationUri: 'https://self-hosted.example/device',
25
+ verificationUriComplete: 'https://self-hosted.example/device?user_code=ABCDE-FGHIJ',
26
+ expiresInSeconds: 900,
27
+ intervalSeconds: 5,
28
+ }),
29
+ ),
30
+ readConfigFileForUpdate: vi.fn(() => ({})),
31
+ updateConfigFile: vi.fn((patch: Record<string, unknown>) => patch),
32
+ }))
33
+
34
+ vi.mock('@omnara/sdk', () => ({
35
+ bearerToken: mocks.bearerToken,
36
+ createOmnaraClient: mocks.createOmnaraClient,
37
+ pollDeviceAuthToken: mocks.pollDeviceAuthToken,
38
+ sdk: {
39
+ getCurrentUser: mocks.getCurrentUser,
40
+ listVisibleProjects: vi.fn(),
41
+ },
42
+ startDeviceAuth: mocks.startDeviceAuth,
43
+ }))
44
+
45
+ vi.mock('./config.ts', () => ({
46
+ configFilePath: () => '/tmp/omnara-config.json',
47
+ readConfigFile: mocks.readConfigFile,
48
+ readConfigFileForUpdate: mocks.readConfigFileForUpdate,
49
+ updateConfigFile: mocks.updateConfigFile,
50
+ }))
51
+
52
+ vi.mock('./interactive.ts', () => ({
53
+ canPromptInteractively: () => false,
54
+ }))
55
+
56
+ vi.mock('./output.ts', () => ({
57
+ runCliAction: (action: () => void | Promise<void>) => Promise.resolve(action()),
58
+ }))
59
+
60
+ describe('login', () => {
61
+ beforeEach(() => {
62
+ vi.clearAllMocks()
63
+ vi.spyOn(console, 'log').mockImplementation(() => undefined)
64
+ vi.spyOn(console, 'error').mockImplementation(() => undefined)
65
+ })
66
+
67
+ afterEach(() => {
68
+ vi.restoreAllMocks()
69
+ })
70
+
71
+ it('uses and persists the configured base URL', async () => {
72
+ const baseUrl = 'https://self-hosted.example'
73
+ const program = new Command()
74
+ const cli: CliConfig = {
75
+ client: {} as CliConfig['client'],
76
+ baseUrl,
77
+ }
78
+ registerLoginCommand(program, cli)
79
+
80
+ await program.parseAsync(['node', 'omnara', 'login', '--no-browser'])
81
+
82
+ expect(mocks.startDeviceAuth).toHaveBeenCalledWith(expect.objectContaining({ baseUrl }))
83
+ expect(mocks.pollDeviceAuthToken).toHaveBeenCalledWith(expect.objectContaining({ baseUrl }))
84
+ expect(mocks.createOmnaraClient).toHaveBeenCalledWith(expect.objectContaining({ baseUrl }))
85
+ expect(mocks.updateConfigFile).toHaveBeenCalledWith({
86
+ token: 'omnara_pat_v1_test',
87
+ base_url: baseUrl,
88
+ })
89
+ })
90
+
91
+ it('validates the config before starting the device flow', async () => {
92
+ const program = new Command()
93
+ const cli: CliConfig = {
94
+ client: {} as CliConfig['client'],
95
+ baseUrl: 'https://self-hosted.example',
96
+ }
97
+ mocks.readConfigFileForUpdate.mockImplementationOnce(() => {
98
+ throw new Error('invalid config')
99
+ })
100
+ registerLoginCommand(program, cli)
101
+
102
+ await expect(program.parseAsync(['node', 'omnara', 'login', '--no-browser'])).rejects.toThrow(
103
+ 'invalid config',
104
+ )
105
+
106
+ expect(mocks.startDeviceAuth).not.toHaveBeenCalled()
107
+ expect(mocks.pollDeviceAuthToken).not.toHaveBeenCalled()
108
+ })
109
+
110
+ it('keeps the login successful when account validation fails', async () => {
111
+ const baseUrl = 'https://self-hosted.example'
112
+ const program = new Command()
113
+ const cli: CliConfig = {
114
+ client: {} as CliConfig['client'],
115
+ baseUrl,
116
+ }
117
+ mocks.getCurrentUser.mockRejectedValueOnce(new Error('temporary network failure'))
118
+ registerLoginCommand(program, cli)
119
+
120
+ await program.parseAsync(['node', 'omnara', 'login', '--no-browser'])
121
+
122
+ expect(mocks.updateConfigFile).toHaveBeenCalledWith({
123
+ token: 'omnara_pat_v1_test',
124
+ base_url: baseUrl,
125
+ })
126
+ expect(console.log).toHaveBeenCalledWith('Logged in')
127
+ expect(console.error).toHaveBeenCalledWith(
128
+ 'warning: could not verify the account or saved organization and project defaults: temporary network failure',
129
+ )
130
+ })
131
+ })
package/src/login.ts ADDED
@@ -0,0 +1,204 @@
1
+ import { hostname } from 'node:os'
2
+
3
+ import { intro, log, note, outro, spinner } from '@clack/prompts'
4
+ import {
5
+ bearerToken,
6
+ createOmnaraClient,
7
+ type OmnaraClient,
8
+ pollDeviceAuthToken,
9
+ sdk,
10
+ startDeviceAuth,
11
+ } from '@omnara/sdk'
12
+ import type { Command } from 'commander'
13
+
14
+ import { openInBrowser } from './browser.ts'
15
+ import {
16
+ type CliConfig,
17
+ configFilePath,
18
+ readConfigFile,
19
+ readConfigFileForUpdate,
20
+ updateConfigFile,
21
+ } from './config.ts'
22
+ import { canPromptInteractively } from './interactive.ts'
23
+ import { runCliAction } from './output.ts'
24
+
25
+ async function isProjectVisible(
26
+ client: OmnaraClient,
27
+ orgId: string,
28
+ projectId: string,
29
+ ): Promise<boolean> {
30
+ let cursor: string | undefined
31
+ do {
32
+ const { data } = await sdk.listVisibleProjects({
33
+ client,
34
+ path: { orgID: orgId },
35
+ query: cursor === undefined ? {} : { cursor },
36
+ })
37
+ if (data.data.some((project) => project.id === projectId)) return true
38
+ cursor = data.next_cursor ?? undefined
39
+ } while (cursor !== undefined)
40
+ return false
41
+ }
42
+
43
+ interface LoginReporter {
44
+ showCode(userCode: string, approvalUrl: string): void
45
+ startWaiting(): void
46
+ stopWaiting(approved: boolean): void
47
+ success(message: string): void
48
+ info(message: string): void
49
+ warn(message: string): void
50
+ finish(message?: string): void
51
+ }
52
+
53
+ function interactiveReporter(baseUrl: string): LoginReporter {
54
+ intro(`Log in to ${baseUrl}`)
55
+ const spin = spinner()
56
+ return {
57
+ showCode(userCode, approvalUrl) {
58
+ note(`Code: ${userCode}\n${approvalUrl}`, 'Confirm this code in your browser')
59
+ },
60
+ startWaiting() {
61
+ spin.start('Waiting for approval in your browser')
62
+ },
63
+ stopWaiting(approved) {
64
+ if (approved) {
65
+ spin.stop('Approved')
66
+ } else {
67
+ spin.error('Approval failed')
68
+ }
69
+ },
70
+ success(message) {
71
+ log.success(message)
72
+ },
73
+ info(message) {
74
+ log.info(message)
75
+ },
76
+ warn(message) {
77
+ log.warn(message)
78
+ },
79
+ finish(message) {
80
+ outro(message ?? 'Done')
81
+ },
82
+ }
83
+ }
84
+
85
+ function plainReporter(): LoginReporter {
86
+ return {
87
+ showCode(userCode, approvalUrl) {
88
+ console.log(`Confirm this code in your browser: ${userCode}`)
89
+ console.log(`Approval page: ${approvalUrl}`)
90
+ },
91
+ startWaiting() {
92
+ console.log('Waiting for approval...')
93
+ },
94
+ stopWaiting(approved) {
95
+ if (approved) console.log('Approved.')
96
+ },
97
+ success(message) {
98
+ console.log(message)
99
+ },
100
+ info(message) {
101
+ console.log(message)
102
+ },
103
+ warn(message) {
104
+ console.error(`warning: ${message}`)
105
+ },
106
+ finish(message) {
107
+ if (message !== undefined) console.log(message)
108
+ },
109
+ }
110
+ }
111
+
112
+ interface LoginOptions {
113
+ browser: boolean
114
+ tokenName?: string
115
+ }
116
+
117
+ export function registerLoginCommand(program: Command, cli: CliConfig): void {
118
+ program
119
+ .command('login')
120
+ .description('Log in via the browser and save an API token')
121
+ .option('--no-browser', 'print the approval URL instead of opening a browser')
122
+ .option('--token-name <name>', 'name for the created API token')
123
+ .action(async (options: LoginOptions) => {
124
+ await runCliAction(async () => {
125
+ readConfigFileForUpdate()
126
+ const report = canPromptInteractively() ? interactiveReporter(cli.baseUrl) : plainReporter()
127
+ const start = await startDeviceAuth({
128
+ baseUrl: cli.baseUrl,
129
+ clientName: 'Omnara CLI',
130
+ tokenName: options.tokenName ?? `Omnara CLI on ${hostname()}`,
131
+ })
132
+ report.showCode(start.userCode, start.verificationUriComplete)
133
+ if (options.browser) {
134
+ openInBrowser(start.verificationUriComplete, (message) => {
135
+ report.warn(message)
136
+ })
137
+ }
138
+ report.startWaiting()
139
+ let token: string
140
+ try {
141
+ token = await pollDeviceAuthToken({
142
+ baseUrl: cli.baseUrl,
143
+ deviceCode: start.deviceCode,
144
+ intervalSeconds: start.intervalSeconds,
145
+ })
146
+ } catch (error) {
147
+ report.stopWaiting(false)
148
+ throw error
149
+ }
150
+ report.stopWaiting(true)
151
+ const saved = updateConfigFile({ token, base_url: cli.baseUrl })
152
+ const client = createOmnaraClient({ baseUrl: cli.baseUrl, auth: bearerToken(token) })
153
+ let orgId = saved.org_id
154
+ let loginMessage = 'Logged in'
155
+ let validationWarning: string | undefined
156
+ try {
157
+ const { data: me } = await sdk.getCurrentUser({ client })
158
+ loginMessage = `Logged in as ${me.user.email || me.user.display_name}`
159
+ if (orgId !== undefined && !me.orgs.some((org) => org.id === orgId)) {
160
+ updateConfigFile({ org_id: undefined, project_id: undefined })
161
+ orgId = undefined
162
+ report.warn(
163
+ 'Cleared the saved default organization and project: this account cannot access them.',
164
+ )
165
+ } else if (
166
+ orgId !== undefined &&
167
+ saved.project_id !== undefined &&
168
+ !(await isProjectVisible(client, orgId, saved.project_id))
169
+ ) {
170
+ updateConfigFile({ project_id: undefined })
171
+ report.warn('Cleared the saved default project: this account cannot access it.')
172
+ }
173
+ } catch (error) {
174
+ validationWarning = `could not verify the account or saved organization and project defaults: ${error instanceof Error ? error.message : String(error)}`
175
+ }
176
+ report.success(loginMessage)
177
+ report.info(`Token saved to ${configFilePath()}`)
178
+ if (validationWarning !== undefined) report.warn(validationWarning)
179
+ if (process.env.OMNARA_API_KEY !== undefined) {
180
+ report.warn('OMNARA_API_KEY is set and takes precedence over the saved token')
181
+ }
182
+ if ((process.env.OMNARA_ORG_ID ?? orgId) === undefined) {
183
+ report.finish("Run 'omnara config select' to choose a default organization and project.")
184
+ } else {
185
+ report.finish()
186
+ }
187
+ })
188
+ })
189
+ program
190
+ .command('logout')
191
+ .description('Remove the saved API token')
192
+ .action(async () => {
193
+ await runCliAction(() => {
194
+ if (readConfigFile().token === undefined) {
195
+ console.log('No saved token.')
196
+ return
197
+ }
198
+ updateConfigFile({ token: undefined })
199
+ console.log(
200
+ `Removed the saved token from ${configFilePath()}. It stays valid until revoked on the API Tokens page.`,
201
+ )
202
+ })
203
+ })
204
+ }