@sendhoney/cli 0.1.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/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # SendHoney CLI
2
+
3
+ Authenticated API and operations CLI for SendHoney tech teams. It follows the
4
+ small launcher pattern used by the GameDay and Decoded CLIs, while keeping API
5
+ behavior server-side.
6
+
7
+ Run `sendhoney` with no arguments for the interactive resource menu. It groups
8
+ the generated endpoint contract by domain and resource, hides service-only
9
+ routes by default, prompts for route parameters and JSON, and confirms deletes.
10
+ Use `sendhoney menu --operator` for service routes.
11
+
12
+ ```bash
13
+ pnpm --filter @sendhoney/cli generate-catalog
14
+ node apps/sendhoney-cli/bin/sendhoney login --username you@example.com --password '…'
15
+ # CI/service account alternative:
16
+ sendhoney login --token "$SENDHONEY_TOKEN"
17
+ sendhoney api catalog --search crm
18
+ sendhoney api get /health
19
+ sendhoney crud /api/v1/crm/contacts list
20
+ sendhoney crud /api/v1/crm/contacts create --json '{"name":"Ada"}'
21
+ sendhoney thundercompute health
22
+ sendhoney thundercompute catalog
23
+ sendhoney thundercompute models
24
+ sendhoney thundercompute status --model qwen2.5:7b
25
+ sendhoney thundercompute chat --json '{"message":"Summarize this incident"}'
26
+ sendhoney release check --platform all
27
+ ```
28
+
29
+ Installation:
30
+
31
+ ```bash
32
+ npm install -g @sendhoney/cli
33
+ brew tap sendhoney/tap && brew install sendhoney
34
+ curl -fsSL https://sendhoney.app/cli/install.sh | sh
35
+ ```
36
+
37
+ Use `SENDHONEY_TOKEN` for CI/service accounts. Credentials are stored in
38
+ `$XDG_CONFIG_HOME/sendhoney/config.json` (or `~/.config/sendhoney/config.json`)
39
+ with mode `0600`; tokens are never printed by the CLI.
package/bin/sendhoney ADDED
@@ -0,0 +1,259 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('node:fs')
4
+ const os = require('node:os')
5
+ const path = require('node:path')
6
+ const { spawnSync } = require('node:child_process')
7
+ const readline = require('node:readline/promises')
8
+ const { stdin, stdout } = require('node:process')
9
+
10
+ const root = path.resolve(__dirname, '..', '..', '..')
11
+ const configDir = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'sendhoney')
12
+ const configFile = path.join(configDir, 'config.json')
13
+ const catalogFiles = [
14
+ path.join(__dirname, '..', 'endpoints.json'),
15
+ path.join(root, 'contracts', 'api-endpoint-matrix.js'),
16
+ ]
17
+
18
+ function loadConfig() {
19
+ try { return JSON.parse(fs.readFileSync(configFile, 'utf8')) } catch { return {} }
20
+ }
21
+
22
+ function saveConfig(value) {
23
+ fs.mkdirSync(configDir, { recursive: true, mode: 0o700 })
24
+ fs.writeFileSync(configFile, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
25
+ }
26
+
27
+ function catalog() {
28
+ for (const file of catalogFiles) {
29
+ try {
30
+ const value = file.endsWith('.js') ? require(file) : JSON.parse(fs.readFileSync(file, 'utf8'))
31
+ return Array.isArray(value) ? value : []
32
+ } catch {}
33
+ }
34
+ return []
35
+ }
36
+
37
+ function json(value) { process.stdout.write(`${JSON.stringify(value, null, 2)}\n`) }
38
+ function die(message, code = 1) { process.stderr.write(`sendhoney: ${message}\n`); process.exit(code) }
39
+ function parseArgs(args) {
40
+ const out = { _: [] }
41
+ for (let i = 0; i < args.length; i += 1) {
42
+ const arg = args[i]
43
+ if (!arg.startsWith('--')) { out._.push(arg); continue }
44
+ const [key, inline] = arg.slice(2).split('=', 2)
45
+ if (inline !== undefined) out[key] = inline
46
+ else if (args[i + 1] && !args[i + 1].startsWith('--')) out[key] = args[++i]
47
+ else out[key] = true
48
+ }
49
+ return out
50
+ }
51
+
52
+ function readJson(value) {
53
+ if (!value) return undefined
54
+ const source = value.startsWith('@') ? fs.readFileSync(value.slice(1), 'utf8') : value
55
+ try { return JSON.parse(source) } catch { die(`invalid JSON: ${value.startsWith('@') ? value : 'inline value'}`) }
56
+ }
57
+
58
+ function visibleCatalog(operator = false) {
59
+ return catalog().filter(entry => operator || entry.auth !== 'service')
60
+ }
61
+
62
+ function resourceKey(route) {
63
+ const parts = route.split('/').filter(Boolean)
64
+ const apiIndex = parts.findIndex(part => part === 'api')
65
+ const start = apiIndex >= 0 ? apiIndex : 0
66
+ const kept = []
67
+ for (const part of parts.slice(start)) {
68
+ if (part.startsWith('{')) break
69
+ kept.push(part)
70
+ }
71
+ return `/${kept.join('/')}` || '/'
72
+ }
73
+
74
+ function domainKey(entry, resource) {
75
+ const service = String(entry.service || '')
76
+ if (service && !service.startsWith('sendhoney-')) {
77
+ return service
78
+ .replace(/-(drogon|oatpp|service|worker|adapter)$/i, '')
79
+ .replace(/^ai-agent$/, 'ai')
80
+ .replace(/^ai-proxy$/, 'ai')
81
+ }
82
+ const parts = resource.split('/').filter(Boolean)
83
+ if (parts[0] === 'api' && parts[1] === 'v1') return parts[2] || 'platform'
84
+ if (parts[0] === 'api') return parts[1] || 'platform'
85
+ return parts[0] || 'platform'
86
+ }
87
+
88
+ function menuResources(operator) {
89
+ const groups = new Map()
90
+ for (const entry of visibleCatalog(operator)) {
91
+ if (entry.method === 'OPTIONS') continue
92
+ const resource = resourceKey(entry.path)
93
+ const domain = domainKey(entry, resource)
94
+ if (!groups.has(domain)) groups.set(domain, new Map())
95
+ const resources = groups.get(domain)
96
+ if (!resources.has(resource)) resources.set(resource, [])
97
+ resources.get(resource).push(entry)
98
+ }
99
+ return groups
100
+ }
101
+
102
+ async function choose(io, label, values) {
103
+ stdout.write(`\n${label}\n`)
104
+ values.forEach((value, index) => stdout.write(` ${index + 1}) ${value}\n`))
105
+ const answer = await io.question('Choose a number (q to exit): ')
106
+ if (answer.toLowerCase() === 'q') return null
107
+ const selected = Number(answer) - 1
108
+ return Number.isInteger(selected) && values[selected] !== undefined ? values[selected] : choose(io, label, values)
109
+ }
110
+
111
+ async function confirm(io, message, assumeYes = false) {
112
+ if (assumeYes) return true
113
+ return (await io.question(`${message} [y/N] `)).toLowerCase() === 'y'
114
+ }
115
+
116
+ async function interactiveMenu(args) {
117
+ const io = readline.createInterface({ input: stdin, output: stdout })
118
+ try {
119
+ const groups = menuResources(Boolean(args.operator))
120
+ let domains = [...groups.keys()].sort()
121
+ if (domains.length > 40) {
122
+ const filter = await io.question('Filter domains (blank to show all, q to exit): ')
123
+ if (filter.toLowerCase() === 'q') return
124
+ if (filter.trim()) domains = domains.filter(domain => domain.toLowerCase().includes(filter.toLowerCase()))
125
+ }
126
+ if (!domains.length) { stdout.write('No matching domains.\n'); return }
127
+ const domain = await choose(io, 'Domains', domains)
128
+ if (!domain) return
129
+ const resources = groups.get(domain)
130
+ const resource = await choose(io, 'Resources', [...resources.keys()].sort())
131
+ if (!resource) return interactiveMenu(args)
132
+ const entries = resources.get(resource)
133
+ const operation = await choose(io, 'Operations', entries.map(entry => `${entry.method} ${entry.path} — ${entry.description || entry.id}`))
134
+ if (!operation) return interactiveMenu(args)
135
+ const entry = entries.find(candidate => `${candidate.method} ${candidate.path} — ${candidate.description || candidate.id}` === operation)
136
+ if (!entry) return interactiveMenu(args)
137
+
138
+ let endpoint = entry.path
139
+ for (const parameter of endpoint.matchAll(/\{([^}]+)\}/g)) {
140
+ const value = await io.question(`${parameter[1]}: `)
141
+ endpoint = endpoint.replace(parameter[0], encodeURIComponent(value))
142
+ }
143
+ let body
144
+ if (['POST', 'PUT', 'PATCH'].includes(entry.method)) {
145
+ const value = await io.question('JSON body (blank for none, or @file): ')
146
+ body = readJson(value || undefined)
147
+ }
148
+ if (entry.method === 'DELETE' && !(await confirm(io, `Delete via ${endpoint}?`))) return
149
+ await request(entry.method, endpoint, { ...args, json: body })
150
+ } finally {
151
+ io.close()
152
+ }
153
+ }
154
+
155
+ async function request(method, endpoint, options = {}) {
156
+ const config = loadConfig()
157
+ const base = options.base || process.env.SENDHONEY_API_URL || config.apiUrl || 'https://api.sendhoney.app'
158
+ const url = /^https?:\/\//.test(endpoint) ? endpoint : `${base.replace(/\/$/, '')}/${endpoint.replace(/^\//, '')}`
159
+ const token = options.token || process.env.SENDHONEY_TOKEN || config.accessToken
160
+ const headers = { Accept: 'application/json', ...(options.json ? { 'Content-Type': 'application/json' } : {}) }
161
+ if (token) headers.Authorization = `Bearer ${token}`
162
+ const response = await fetch(url, { method, headers, body: options.json ? JSON.stringify(options.json) : undefined })
163
+ const text = await response.text()
164
+ let body
165
+ try { body = text ? JSON.parse(text) : null } catch { body = text }
166
+ if (!response.ok) { json({ status: response.status, url, error: body }); process.exitCode = 1; return }
167
+ json(body)
168
+ }
169
+
170
+ async function login(args) {
171
+ const config = loadConfig()
172
+ const directToken = args.token || process.env.SENDHONEY_TOKEN
173
+ if (directToken) {
174
+ saveConfig({ ...config, apiUrl: args['api-url'] || config.apiUrl || 'https://api.sendhoney.app', accessToken: directToken })
175
+ return json({ ok: true, apiUrl: args['api-url'] || config.apiUrl || 'https://api.sendhoney.app' })
176
+ }
177
+ const authUrl = (args['auth-url'] || process.env.SENDHONEY_AUTH_URL || config.authUrl || 'https://auth.sendhoney.app').replace(/\/$/, '')
178
+ const realm = args.realm || process.env.SENDHONEY_KEYCLOAK_REALM || config.realm || 'users'
179
+ const clientId = args['client-id'] || process.env.SENDHONEY_CLIENT_ID || config.clientId || 'sendhoney-mobile'
180
+ const username = args.username || process.env.SENDHONEY_USERNAME
181
+ const password = args.password || process.env.SENDHONEY_PASSWORD
182
+ if (!username || !password) die('login requires --username and --password (or SENDHONEY_USERNAME/SENDHONEY_PASSWORD)')
183
+ const response = await fetch(`${authUrl}/realms/${realm}/protocol/openid-connect/token`, {
184
+ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
185
+ body: new URLSearchParams({ grant_type: 'password', client_id: clientId, username, password }).toString(),
186
+ })
187
+ const body = await response.json().catch(() => ({}))
188
+ if (!response.ok || !body.access_token) die(`login failed (${response.status}): ${body.error_description || body.error || 'no access token'}`)
189
+ saveConfig({ ...config, apiUrl: args['api-url'] || config.apiUrl || 'https://api.sendhoney.app', authUrl, realm, clientId, accessToken: body.access_token, refreshToken: body.refresh_token, expiresAt: Date.now() + (body.expires_in || 300) * 1000 })
190
+ json({ ok: true, username, apiUrl: args['api-url'] || config.apiUrl || 'https://api.sendhoney.app' })
191
+ }
192
+
193
+ async function main() {
194
+ const args = parseArgs(process.argv.slice(2)); const [command, subcommand, ...rest] = args._
195
+ if (args.version) {
196
+ process.stdout.write(`${require('../package.json').version}\n`)
197
+ return
198
+ }
199
+ if (!command && stdin.isTTY && stdout.isTTY) return interactiveMenu(args)
200
+ if (!command || command === 'help' || args.help) {
201
+ process.stdout.write('SendHoney CLI\n\nCommands: login, logout, whoami, menu, api, crud, thundercompute, release\n\nRunning `sendhoney` interactively opens the resource menu.\nmenu [--operator]\napi request METHOD PATH [--json JSON] | api get|post|put|patch|delete PATH\napi catalog [--search TEXT] [--method GET]\ncrud PATH list|create|update|delete [--id ID] [--json JSON] [--yes]\nthundercompute catalog|health|models|status|pull|ensure|chat\nrelease check [--platform android|ios|all]\n')
202
+ return
203
+ }
204
+ if (command === 'login') return login(args)
205
+ if (command === 'logout') { const c = loadConfig(); delete c.accessToken; delete c.refreshToken; delete c.expiresAt; saveConfig(c); return json({ ok: true }) }
206
+ if (command === 'menu') return interactiveMenu(args)
207
+ if (command === 'whoami') return request('GET', '/api/v1/users/me', args)
208
+ if (command === 'api' || command === 'crud') {
209
+ if (command === 'api' && subcommand === 'catalog') {
210
+ const search = String(args.search || '').toLowerCase(); const method = args.method && String(args.method).toUpperCase()
211
+ return json(catalog().filter(e => (!search || JSON.stringify(e).toLowerCase().includes(search)) && (!method || e.method === method)))
212
+ }
213
+ let method; let endpoint
214
+ if (command === 'crud') {
215
+ endpoint = subcommand; const op = rest[0] || 'list'; method = ({ list: 'GET', create: 'POST', update: 'PUT', delete: 'DELETE' })[op];
216
+ if (!method) die('crud operation must be list, create, update, or delete')
217
+ if (args.id) endpoint = `${endpoint.replace(/\/$/, '')}/${encodeURIComponent(args.id)}`
218
+ if (method === 'DELETE' && !args.yes) {
219
+ const deleteIo = readline.createInterface({ input: stdin, output: stdout })
220
+ const allowed = await confirm(deleteIo, `Delete via ${endpoint}?`)
221
+ deleteIo.close()
222
+ if (!allowed) return
223
+ }
224
+ } else { method = String(subcommand || '').toUpperCase(); endpoint = rest[0] }
225
+ if (!['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(method) || !endpoint) die('use api request METHOD PATH or api get|post|put|patch|delete PATH')
226
+ return request(method, endpoint, { ...args, json: readJson(args.json) })
227
+ }
228
+ if (command === 'thundercompute') {
229
+ const model = args.model ? `/${encodeURIComponent(args.model)}` : ''
230
+ const routes = {
231
+ catalog: ['GET', '/internal/ai/models/catalog'],
232
+ health: ['GET', '/internal/ai/models/health'],
233
+ models: ['GET', '/internal/ai/models/ollama/list'],
234
+ status: ['GET', `/internal/ai/models/ollama/status${model}`],
235
+ pull: ['POST', `/internal/ai/models/ollama/pull${model}`],
236
+ ensure: ['POST', '/internal/ai/models/ensure-ready'],
237
+ chat: ['POST', '/ai/chat'],
238
+ }
239
+ const route = routes[subcommand]
240
+ if (!route) die(`unknown ThunderCompute command: ${subcommand || '(missing)'}`)
241
+ return request(route[0], route[1], { ...args, json: readJson(args.json) })
242
+ }
243
+ if (command === 'release') {
244
+ if (!['check', 'status'].includes(subcommand)) die('use release check [--platform android|ios|all]')
245
+ const script = path.join(root, 'scripts', 'check-mobile-release-readiness.sh')
246
+ const result = spawnSync('bash', [script], {
247
+ cwd: root,
248
+ env: { ...process.env, PLATFORM: args.platform || 'all', STRICT_SECRETS: args.strict ? '1' : '0' },
249
+ encoding: 'utf8',
250
+ })
251
+ process.stdout.write(result.stdout || '')
252
+ process.stderr.write(result.stderr || '')
253
+ process.exitCode = result.status || 0
254
+ return
255
+ }
256
+ die(`unknown command: ${command}`)
257
+ }
258
+
259
+ main().catch(error => die(error.message))