@sortlist/cli 0.26.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/.published +1 -0
- package/README.md +145 -0
- package/bin/sl.mjs +73 -0
- package/codegen.ts +36 -0
- package/package.json +62 -0
- package/src/commands/chat/chat.ts +302 -0
- package/src/commands/chat/interactive/App.tsx +119 -0
- package/src/commands/chat/interactive/components/ChatInput.tsx +115 -0
- package/src/commands/chat/interactive/components/ChoicePrompt.tsx +35 -0
- package/src/commands/chat/interactive/components/MessageView.tsx +63 -0
- package/src/commands/chat/interactive/components/ThinkingBox.tsx +54 -0
- package/src/commands/chat/interactive/connection.ts +111 -0
- package/src/commands/chat/interactive/debug-log.ts +19 -0
- package/src/commands/chat/interactive/hooks/useChat.ts +440 -0
- package/src/commands/chat/interactive/hooks/useTerminalSize.ts +23 -0
- package/src/commands/chat/interactive/index.tsx +26 -0
- package/src/commands/chat/interactive/markdown.ts +29 -0
- package/src/commands/chat/interactive/types.ts +34 -0
- package/src/commands/config.ts +94 -0
- package/src/commands/dynamic.ts +396 -0
- package/src/commands/login.ts +191 -0
- package/src/commands/logout.ts +43 -0
- package/src/commands/offer.ts +96 -0
- package/src/commands/switch.ts +72 -0
- package/src/commands/token.ts +23 -0
- package/src/commands/whoami.ts +50 -0
- package/src/graphql/client.ts +257 -0
- package/src/graphql/generated/gql.ts +106 -0
- package/src/graphql/generated/graphql.ts +7732 -0
- package/src/graphql/generated/index.ts +1 -0
- package/src/graphql/introspection.ts +240 -0
- package/src/graphql/operations/common.ts +115 -0
- package/src/graphql/operations/hermes.ts +54 -0
- package/src/graphql/query-builder.ts +236 -0
- package/src/index.ts +176 -0
- package/src/lib/auth.ts +58 -0
- package/src/lib/browser.ts +6 -0
- package/src/lib/company.ts +35 -0
- package/src/lib/config.ts +73 -0
- package/src/lib/env.ts +10 -0
- package/src/lib/output.ts +84 -0
- package/src/lib/parse.ts +8 -0
- package/src/lib/sentry.ts +77 -0
- package/src/lib/sequence-buffer.ts +95 -0
- package/src/lib/version-check.ts +88 -0
- package/src/types/marked-terminal.d.ts +20 -0
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dynamic command registration.
|
|
3
|
+
*
|
|
4
|
+
* Derives service grouping from the `@join__field(graph: ...)` directives
|
|
5
|
+
* that the router injects into introspection responses, then builds
|
|
6
|
+
* Commander.js commands at runtime.
|
|
7
|
+
*/
|
|
8
|
+
import { Command } from 'commander';
|
|
9
|
+
import {
|
|
10
|
+
isInputObjectType,
|
|
11
|
+
isInterfaceType,
|
|
12
|
+
isListType,
|
|
13
|
+
isNonNullType,
|
|
14
|
+
isUnionType,
|
|
15
|
+
type GraphQLArgument,
|
|
16
|
+
type GraphQLField,
|
|
17
|
+
type GraphQLInputType,
|
|
18
|
+
type GraphQLNamedType,
|
|
19
|
+
type GraphQLObjectType,
|
|
20
|
+
type GraphQLOutputType,
|
|
21
|
+
type GraphQLSchema,
|
|
22
|
+
} from 'graphql';
|
|
23
|
+
|
|
24
|
+
import { graphqlRaw } from '../graphql/client.ts';
|
|
25
|
+
import { type FieldServiceMap } from '../graphql/introspection.ts';
|
|
26
|
+
import { buildQuery } from '../graphql/query-builder.ts';
|
|
27
|
+
import { resolveCompanyId } from '../lib/company.ts';
|
|
28
|
+
import { getUserContext } from '../lib/config.ts';
|
|
29
|
+
import { error, hint, printJson, warn } from '../lib/output.ts';
|
|
30
|
+
|
|
31
|
+
// Context fields that are auto-injected from ~/.sortlist/config.json.
|
|
32
|
+
// Schema field names (key) → UserContext property (value). The CLI is
|
|
33
|
+
// company-scoped; marketplace fields like `agencyId` are NOT auto-filled
|
|
34
|
+
// (Agency and Company are independent entities) and must be passed
|
|
35
|
+
// explicitly via `--agency-id`.
|
|
36
|
+
const CONTEXT_FIELDS: Record<string, string> = {
|
|
37
|
+
companyId: 'companyId',
|
|
38
|
+
companySlug: 'companySlug',
|
|
39
|
+
oauthId: 'oauthId',
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// Fields to skip — internal relay/federation helpers
|
|
43
|
+
const SKIP_FIELDS = new Set(['node', 'nodes', 'id', '_entities', '_service']);
|
|
44
|
+
|
|
45
|
+
function unwrap(type: GraphQLOutputType | GraphQLInputType): GraphQLNamedType {
|
|
46
|
+
if (isNonNullType(type)) return unwrap(type.ofType as GraphQLOutputType | GraphQLInputType);
|
|
47
|
+
if (isListType(type)) return unwrap(type.ofType as GraphQLOutputType | GraphQLInputType);
|
|
48
|
+
return type as GraphQLNamedType;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function kebab(s: string): string {
|
|
52
|
+
return s.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function ucfirst(s: string): string {
|
|
56
|
+
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* For mutations with a single `input` argument of an Input type,
|
|
61
|
+
* return the fields of that input type for flattening into CLI options.
|
|
62
|
+
*/
|
|
63
|
+
function getInputFields(
|
|
64
|
+
field: GraphQLField<unknown, unknown>,
|
|
65
|
+
): { name: string; type: GraphQLArgument['type']; required: boolean }[] | null {
|
|
66
|
+
if (field.args.length !== 1) return null;
|
|
67
|
+
const arg = field.args[0];
|
|
68
|
+
if (arg.name !== 'input') return null;
|
|
69
|
+
const argType = unwrap(arg.type);
|
|
70
|
+
if (!argType || !isInputObjectType(argType)) return null;
|
|
71
|
+
const fields = argType.getFields();
|
|
72
|
+
return Object.entries(fields).map(([name, f]) => ({
|
|
73
|
+
name,
|
|
74
|
+
type: f.type,
|
|
75
|
+
required: isNonNullType(f.type),
|
|
76
|
+
}));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function coerceValue(raw: string, typeName: string): unknown {
|
|
80
|
+
if (typeName === 'Int') return parseInt(raw, 10);
|
|
81
|
+
if (typeName === 'Float') return parseFloat(raw);
|
|
82
|
+
if (typeName === 'Boolean') return raw === 'true';
|
|
83
|
+
return raw;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function buildCommand(
|
|
87
|
+
schema: GraphQLSchema,
|
|
88
|
+
fieldName: string,
|
|
89
|
+
kind: 'query' | 'mutation',
|
|
90
|
+
description: string,
|
|
91
|
+
): Command {
|
|
92
|
+
const rootType = kind === 'query' ? schema.getQueryType() : schema.getMutationType();
|
|
93
|
+
if (!rootType) throw new Error(`No ${kind} type in schema`);
|
|
94
|
+
|
|
95
|
+
const field = rootType.getFields()[fieldName];
|
|
96
|
+
if (!field) throw new Error(`Unknown ${kind} field: ${fieldName}`);
|
|
97
|
+
|
|
98
|
+
const inputFields = getInputFields(field);
|
|
99
|
+
const useInputWrapper = inputFields != null;
|
|
100
|
+
const cliArgs = useInputWrapper
|
|
101
|
+
? inputFields
|
|
102
|
+
: field.args.map((a) => ({
|
|
103
|
+
name: a.name,
|
|
104
|
+
type: a.type,
|
|
105
|
+
required: isNonNullType(a.type),
|
|
106
|
+
}));
|
|
107
|
+
|
|
108
|
+
const cmd = new Command(kebab(fieldName)).description(description);
|
|
109
|
+
|
|
110
|
+
const acceptsCompanyId = cliArgs.some((a) => a.name === 'companyId');
|
|
111
|
+
const acceptsCompanySlug = cliArgs.some((a) => a.name === 'companySlug');
|
|
112
|
+
|
|
113
|
+
for (const a of cliArgs) {
|
|
114
|
+
const flag = `--${kebab(a.name)} <${a.name}>`;
|
|
115
|
+
const isContext = a.name in CONTEXT_FIELDS;
|
|
116
|
+
if (isContext) {
|
|
117
|
+
cmd.option(flag, `${a.name} (from context)`);
|
|
118
|
+
} else if (a.required) {
|
|
119
|
+
cmd.requiredOption(flag, a.name);
|
|
120
|
+
} else {
|
|
121
|
+
cmd.option(flag, a.name);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// For company-scoped operations the schema typically only accepts `companyId`.
|
|
126
|
+
// Mirror the chat command's UX: also expose `--company-slug` for convenience,
|
|
127
|
+
// resolved client-side via `me.companies`.
|
|
128
|
+
if (acceptsCompanyId && !acceptsCompanySlug) {
|
|
129
|
+
cmd.option('--company-slug <companySlug>', 'companySlug (resolved to companyId via me.companies)');
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
cmd
|
|
133
|
+
.option('--depth <depth>', 'Selection depth (default: 0)', parseInt)
|
|
134
|
+
.option('--fields <fields>', 'Comma-separated fields to include')
|
|
135
|
+
.option('--exclude <fields>', 'Comma-separated fields to exclude');
|
|
136
|
+
|
|
137
|
+
cmd.action(async function (this: Command) {
|
|
138
|
+
const opts = this.optsWithGlobals();
|
|
139
|
+
const needsContext = cliArgs.some((a) => a.name in CONTEXT_FIELDS);
|
|
140
|
+
const ctx = needsContext ? getUserContext() : undefined;
|
|
141
|
+
|
|
142
|
+
if (acceptsCompanyId) {
|
|
143
|
+
const resolved = await resolveCompanyId({
|
|
144
|
+
companyId: typeof opts.companyId === 'string' ? opts.companyId : undefined,
|
|
145
|
+
companySlug: typeof opts.companySlug === 'string' ? opts.companySlug : undefined,
|
|
146
|
+
ctx,
|
|
147
|
+
endpoint: opts.endpoint,
|
|
148
|
+
});
|
|
149
|
+
if (!resolved) {
|
|
150
|
+
error('No company selected.');
|
|
151
|
+
hint('Pass --company-id <id>, --company-slug <slug>, or run `sl switch` to set one.');
|
|
152
|
+
process.exit(2);
|
|
153
|
+
}
|
|
154
|
+
opts.companyId = resolved;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
let variables: Record<string, unknown>;
|
|
158
|
+
if (useInputWrapper) {
|
|
159
|
+
const input: Record<string, unknown> = {};
|
|
160
|
+
for (const a of cliArgs) {
|
|
161
|
+
const raw = opts[a.name];
|
|
162
|
+
const ctxProp = CONTEXT_FIELDS[a.name];
|
|
163
|
+
const namedType = unwrap(a.type);
|
|
164
|
+
if (raw != null) {
|
|
165
|
+
input[a.name] = coerceValue(raw, namedType.name);
|
|
166
|
+
} else if (ctxProp && ctx) {
|
|
167
|
+
input[a.name] = (ctx as Record<string, unknown>)[ctxProp];
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
variables = { input };
|
|
171
|
+
} else if (cliArgs.length === 0) {
|
|
172
|
+
variables = {};
|
|
173
|
+
} else {
|
|
174
|
+
variables = {};
|
|
175
|
+
for (const a of cliArgs) {
|
|
176
|
+
const raw = opts[a.name];
|
|
177
|
+
const ctxProp = CONTEXT_FIELDS[a.name];
|
|
178
|
+
const namedType = unwrap(a.type);
|
|
179
|
+
if (raw != null) {
|
|
180
|
+
variables[a.name] = coerceValue(raw, namedType.name);
|
|
181
|
+
} else if (ctxProp && ctx) {
|
|
182
|
+
variables[a.name] = (ctx as Record<string, unknown>)[ctxProp];
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const { query, fieldName: fName } = buildQuery(schema, kind, fieldName, variables, {
|
|
188
|
+
depth: opts.depth,
|
|
189
|
+
fields: opts.fields?.split(','),
|
|
190
|
+
exclude: opts.exclude?.split(','),
|
|
191
|
+
});
|
|
192
|
+
const data = await graphqlRaw(query, variables, { endpoint: opts.endpoint });
|
|
193
|
+
const result = data[fName];
|
|
194
|
+
if (result == null) {
|
|
195
|
+
warn('No results returned.');
|
|
196
|
+
hint('The query succeeded but the server returned null.');
|
|
197
|
+
hint('Try different arguments or check that the resource exists.');
|
|
198
|
+
} else {
|
|
199
|
+
printJson(result);
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
return cmd;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// ── Help formatting ──
|
|
207
|
+
|
|
208
|
+
const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
209
|
+
const ansi = {
|
|
210
|
+
reset: '\x1b[0m',
|
|
211
|
+
bold: '\x1b[1m',
|
|
212
|
+
dim: '\x1b[2m',
|
|
213
|
+
cyan: '\x1b[36m',
|
|
214
|
+
yellow: '\x1b[33m',
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
function formatCommandList(commands: Command[]): string {
|
|
218
|
+
if (commands.length === 0) return '';
|
|
219
|
+
|
|
220
|
+
const maxLen = Math.max(...commands.map((c) => c.name().length + (c.options.length > 0 ? 10 : 0)));
|
|
221
|
+
const padWidth = Math.max(maxLen, 20);
|
|
222
|
+
|
|
223
|
+
return commands
|
|
224
|
+
.map((c) => {
|
|
225
|
+
const name = c.options.length > 0 ? `${c.name()} [options]` : c.name();
|
|
226
|
+
const desc = c.description();
|
|
227
|
+
const padding = ' '.repeat(Math.max(2, padWidth - name.length + 2));
|
|
228
|
+
if (desc) {
|
|
229
|
+
return ` ${name}${padding}${desc}`;
|
|
230
|
+
}
|
|
231
|
+
const noDesc = useColor ? `${ansi.yellow}No description provided${ansi.reset}` : 'No description provided';
|
|
232
|
+
return ` ${name}${padding}${noDesc}`;
|
|
233
|
+
})
|
|
234
|
+
.join('\n');
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// ── Service map derivation ──
|
|
238
|
+
|
|
239
|
+
interface ServiceEntry {
|
|
240
|
+
queries: Array<{ fieldName: string; description: string }>;
|
|
241
|
+
mutations: Array<{ fieldName: string; description: string }>;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Derive the service → operations map from the `@join__field(graph: ...)`
|
|
246
|
+
* directives the router exposes on each root field. Fields without a mapped
|
|
247
|
+
* subgraph are skipped.
|
|
248
|
+
*/
|
|
249
|
+
function deriveServiceMap(schema: GraphQLSchema, fieldServices: FieldServiceMap): Map<string, ServiceEntry> {
|
|
250
|
+
const map = new Map<string, ServiceEntry>();
|
|
251
|
+
|
|
252
|
+
function ensure(service: string): ServiceEntry {
|
|
253
|
+
if (!map.has(service)) map.set(service, { queries: [], mutations: [] });
|
|
254
|
+
return map.get(service)!;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const rootTypes: Array<{ kind: 'queries' | 'mutations'; type: GraphQLObjectType | null | undefined }> = [
|
|
258
|
+
{ kind: 'queries', type: schema.getQueryType() },
|
|
259
|
+
{ kind: 'mutations', type: schema.getMutationType() },
|
|
260
|
+
];
|
|
261
|
+
|
|
262
|
+
for (const { kind, type } of rootTypes) {
|
|
263
|
+
if (!type) continue;
|
|
264
|
+
const services = fieldServices.get(type.name);
|
|
265
|
+
if (!services) continue;
|
|
266
|
+
|
|
267
|
+
for (const [fieldName, field] of Object.entries(type.getFields())) {
|
|
268
|
+
if (SKIP_FIELDS.has(fieldName) || fieldName.startsWith('__')) continue;
|
|
269
|
+
|
|
270
|
+
// Skip operations returning interfaces or unions
|
|
271
|
+
const returnType = unwrap(field.type);
|
|
272
|
+
if (isInterfaceType(returnType) || isUnionType(returnType)) continue;
|
|
273
|
+
|
|
274
|
+
const service = services.get(fieldName);
|
|
275
|
+
if (!service) continue;
|
|
276
|
+
|
|
277
|
+
ensure(service)[kind].push({ fieldName, description: field.description ?? '' });
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Sort fields alphabetically within each service
|
|
282
|
+
for (const entry of map.values()) {
|
|
283
|
+
entry.queries.sort((a, b) => a.fieldName.localeCompare(b.fieldName));
|
|
284
|
+
entry.mutations.sort((a, b) => a.fieldName.localeCompare(b.fieldName));
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
return map;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Short blurb shown after `sl <service>` in the root help. Services not listed
|
|
292
|
+
* here fall back to `<Service> service operations`.
|
|
293
|
+
*/
|
|
294
|
+
const SERVICE_DESCRIPTIONS: Record<string, string> = {
|
|
295
|
+
atlas: 'Atlas service (contacts, orgs)',
|
|
296
|
+
marketplace: 'Marketplace service',
|
|
297
|
+
hermes: 'Hermes service',
|
|
298
|
+
chat: 'Chat AI service (conversations)',
|
|
299
|
+
};
|
|
300
|
+
|
|
301
|
+
function serviceDescription(service: string): string {
|
|
302
|
+
return SERVICE_DESCRIPTIONS[service] ?? `${ucfirst(service)} service operations`;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export interface ServiceCommand {
|
|
306
|
+
command: Command;
|
|
307
|
+
/** First query name suitable for an example in the root help, or null. */
|
|
308
|
+
exampleQuery: string | null;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Build all service commands from the introspected schema.
|
|
313
|
+
* Returns a map of service name → Commander Command + metadata for the root help.
|
|
314
|
+
*/
|
|
315
|
+
export function buildServiceCommands(
|
|
316
|
+
schema: GraphQLSchema,
|
|
317
|
+
fieldServices: FieldServiceMap,
|
|
318
|
+
): Map<string, ServiceCommand> {
|
|
319
|
+
const serviceMap = deriveServiceMap(schema, fieldServices);
|
|
320
|
+
const commands = new Map<string, ServiceCommand>();
|
|
321
|
+
|
|
322
|
+
// Track operation names to deduplicate (same name across query + mutation)
|
|
323
|
+
const allNames = new Map<string, number>();
|
|
324
|
+
for (const entry of serviceMap.values()) {
|
|
325
|
+
for (const op of [...entry.queries, ...entry.mutations]) {
|
|
326
|
+
allNames.set(op.fieldName, (allNames.get(op.fieldName) ?? 0) + 1);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
for (const [service, entry] of serviceMap) {
|
|
331
|
+
const subCmd = new Command(service).description(serviceDescription(service));
|
|
332
|
+
|
|
333
|
+
const queryCommands: Command[] = [];
|
|
334
|
+
const mutationCommands: Command[] = [];
|
|
335
|
+
|
|
336
|
+
for (const op of entry.queries) {
|
|
337
|
+
try {
|
|
338
|
+
const cmd = buildCommand(schema, op.fieldName, 'query', op.description);
|
|
339
|
+
if ((allNames.get(op.fieldName) ?? 0) > 1) {
|
|
340
|
+
cmd.name(`${kebab(op.fieldName)}-query`);
|
|
341
|
+
}
|
|
342
|
+
subCmd.addCommand(cmd, { hidden: true });
|
|
343
|
+
queryCommands.push(cmd);
|
|
344
|
+
} catch {
|
|
345
|
+
// Field may not be resolvable — skip
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
for (const op of entry.mutations) {
|
|
350
|
+
try {
|
|
351
|
+
const cmd = buildCommand(schema, op.fieldName, 'mutation', op.description);
|
|
352
|
+
if ((allNames.get(op.fieldName) ?? 0) > 1) {
|
|
353
|
+
cmd.name(`${kebab(op.fieldName)}-mutation`);
|
|
354
|
+
}
|
|
355
|
+
subCmd.addCommand(cmd, { hidden: true });
|
|
356
|
+
mutationCommands.push(cmd);
|
|
357
|
+
} catch {
|
|
358
|
+
// Field may not be resolvable — skip
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// Custom help that groups queries and mutations
|
|
363
|
+
subCmd.configureHelp({
|
|
364
|
+
formatHelp: () => {
|
|
365
|
+
const lines: string[] = [];
|
|
366
|
+
lines.push(`Usage: sl ${service} [command] [options]\n`);
|
|
367
|
+
lines.push(`${serviceDescription(service)}\n`);
|
|
368
|
+
|
|
369
|
+
if (queryCommands.length > 0) {
|
|
370
|
+
lines.push(`Queries:`);
|
|
371
|
+
lines.push(formatCommandList(queryCommands));
|
|
372
|
+
lines.push('');
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
if (mutationCommands.length > 0) {
|
|
376
|
+
lines.push(`Mutations:`);
|
|
377
|
+
lines.push(formatCommandList(mutationCommands));
|
|
378
|
+
lines.push('');
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
lines.push(`Options:`);
|
|
382
|
+
lines.push(` -h, --help display help for command\n`);
|
|
383
|
+
return lines.join('\n');
|
|
384
|
+
},
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
if (queryCommands.length > 0 || mutationCommands.length > 0) {
|
|
388
|
+
commands.set(service, {
|
|
389
|
+
command: subCmd,
|
|
390
|
+
exampleQuery: queryCommands[0]?.name() ?? null,
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
return commands;
|
|
396
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { createInterface } from 'node:readline';
|
|
2
|
+
import { Command } from 'commander';
|
|
3
|
+
|
|
4
|
+
import { graphql, graphqlUnauthenticated } from '../graphql/client.ts';
|
|
5
|
+
import { Me } from '../graphql/operations/common.ts';
|
|
6
|
+
import { DeviceAuthorize, DeviceToken } from '../graphql/operations/hermes.ts';
|
|
7
|
+
import { saveCredentials } from '../lib/auth.ts';
|
|
8
|
+
import { openBrowser } from '../lib/browser.ts';
|
|
9
|
+
import { saveConfig } from '../lib/config.ts';
|
|
10
|
+
import { error, hint, info, success, warn } from '../lib/output.ts';
|
|
11
|
+
|
|
12
|
+
// TODO: fetch the set of available API scopes dynamically (e.g. from Hermes'
|
|
13
|
+
// resource server) once the backend exposes them. For now the CLI requests a
|
|
14
|
+
// fixed superset so users can exercise every subgraph.
|
|
15
|
+
const DEFAULT_SCOPE = 'openid profile email offline_access atlas:*/* core:*/* max/*:* billing/*:*';
|
|
16
|
+
|
|
17
|
+
function sleep(ms: number): Promise<void> {
|
|
18
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface CompanyChoice {
|
|
22
|
+
id: string;
|
|
23
|
+
name: string;
|
|
24
|
+
slug: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function promptCompanySelection(companies: CompanyChoice[]): Promise<CompanyChoice> {
|
|
28
|
+
if (companies.length === 1) {
|
|
29
|
+
info(`Company: ${companies[0].name} (${companies[0].slug})`);
|
|
30
|
+
return companies[0];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
info('\nSelect a company:\n');
|
|
34
|
+
for (let i = 0; i < companies.length; i++) {
|
|
35
|
+
info(` ${i + 1}) ${companies[i].name} (${companies[i].slug})`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
39
|
+
|
|
40
|
+
return new Promise((resolve) => {
|
|
41
|
+
rl.question(`\nChoice [1-${companies.length}]: `, (answer) => {
|
|
42
|
+
rl.close();
|
|
43
|
+
const idx = parseInt(answer, 10) - 1;
|
|
44
|
+
if (idx >= 0 && idx < companies.length) {
|
|
45
|
+
resolve(companies[idx]);
|
|
46
|
+
} else {
|
|
47
|
+
warn('Invalid choice — defaulting to the first company.');
|
|
48
|
+
resolve(companies[0]);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function setupUserContext(endpoint?: string): Promise<void> {
|
|
55
|
+
const userData = await graphql(Me, undefined, { endpoint });
|
|
56
|
+
const user = userData.me;
|
|
57
|
+
if (!user) return;
|
|
58
|
+
|
|
59
|
+
const companies: CompanyChoice[] = (user.companies?.nodes ?? [])
|
|
60
|
+
.filter((c): c is { id: string; name: string; slug: string } => c != null)
|
|
61
|
+
.map((c) => ({ id: c.id, name: c.name ?? c.slug, slug: c.slug }));
|
|
62
|
+
|
|
63
|
+
const context: Record<string, string | undefined> = {
|
|
64
|
+
oauthId: user.sub ?? undefined,
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
if (companies.length > 0) {
|
|
68
|
+
const selected = await promptCompanySelection(companies);
|
|
69
|
+
context.companyId = selected.id;
|
|
70
|
+
context.companySlug = selected.slug;
|
|
71
|
+
context.companyName = selected.name;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
saveConfig(context);
|
|
75
|
+
info('');
|
|
76
|
+
info(` User: ${user.firstName} ${user.lastName} <${user.email}>`);
|
|
77
|
+
if (context.companyName) {
|
|
78
|
+
info(` Company: ${context.companyName} (${context.companySlug})`);
|
|
79
|
+
}
|
|
80
|
+
hint('Run `sl whoami` to verify, or `sl switch` to change company.');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export const loginCommand = new Command('login')
|
|
84
|
+
.summary('Log in to your Sortlist account')
|
|
85
|
+
.description(
|
|
86
|
+
'Log in to your Sortlist account\n\n' +
|
|
87
|
+
'Opens a browser to complete authentication, then saves your\n' +
|
|
88
|
+
"credentials locally. If you belong to multiple companies, you'll\n" +
|
|
89
|
+
'be prompted to pick one.\n\n' +
|
|
90
|
+
'Examples:\n' +
|
|
91
|
+
' sl login Log in with default settings\n' +
|
|
92
|
+
' sl login --no-browser Print the login URL instead of opening it',
|
|
93
|
+
)
|
|
94
|
+
.option('--scope <scope>', 'OAuth scope', DEFAULT_SCOPE)
|
|
95
|
+
.option('--no-browser', 'Print the login URL instead of opening a browser')
|
|
96
|
+
.action(async function (this: Command) {
|
|
97
|
+
const opts = this.optsWithGlobals();
|
|
98
|
+
|
|
99
|
+
info('Starting device authorization...');
|
|
100
|
+
|
|
101
|
+
const authData = await graphqlUnauthenticated(DeviceAuthorize, { input: { scope: opts.scope } }, opts.endpoint);
|
|
102
|
+
|
|
103
|
+
const device = authData.deviceAuthorize;
|
|
104
|
+
if (!device) {
|
|
105
|
+
error('Device authorization failed — the server returned an empty response.');
|
|
106
|
+
hint('Check your network connection and try again.');
|
|
107
|
+
hint('If the problem persists, verify the endpoint: sl config show');
|
|
108
|
+
process.exit(2);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const url = device.verificationUriComplete ?? device.verificationUri;
|
|
112
|
+
info('');
|
|
113
|
+
info(` Open this URL in your browser:`);
|
|
114
|
+
info(` ${url}`);
|
|
115
|
+
info('');
|
|
116
|
+
info(` Enter code: ${device.userCode}`);
|
|
117
|
+
info('');
|
|
118
|
+
|
|
119
|
+
if (opts.browser) {
|
|
120
|
+
openBrowser(url);
|
|
121
|
+
info(' (Browser opened automatically)');
|
|
122
|
+
info('');
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
info('Waiting for you to complete login in the browser...');
|
|
126
|
+
|
|
127
|
+
let interval = device.interval * 1000;
|
|
128
|
+
const deadline = Date.now() + device.expiresIn * 1000;
|
|
129
|
+
|
|
130
|
+
while (Date.now() < deadline) {
|
|
131
|
+
await sleep(interval);
|
|
132
|
+
|
|
133
|
+
const tokenData = await graphqlUnauthenticated(
|
|
134
|
+
DeviceToken,
|
|
135
|
+
{ input: { deviceCode: device.deviceCode } },
|
|
136
|
+
opts.endpoint,
|
|
137
|
+
);
|
|
138
|
+
|
|
139
|
+
const token = tokenData.deviceToken;
|
|
140
|
+
if (!token) {
|
|
141
|
+
error('Token exchange failed — the server returned an empty response.');
|
|
142
|
+
hint('Try running `sl login` again.');
|
|
143
|
+
process.exit(2);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (token.error === 'authorization_pending') {
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (token.error === 'slow_down') {
|
|
151
|
+
interval += 5000;
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (token.error === 'expired_token') {
|
|
156
|
+
error('The login code expired before you completed authentication.');
|
|
157
|
+
hint('Run `sl login` to generate a new code.');
|
|
158
|
+
process.exit(2);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (token.error === 'access_denied') {
|
|
162
|
+
error('Access was denied during authentication.');
|
|
163
|
+
hint('Make sure you approved the request in the browser.');
|
|
164
|
+
hint('If you denied it by mistake, run `sl login` to try again.');
|
|
165
|
+
process.exit(2);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (token.error) {
|
|
169
|
+
error(`Authentication failed (${token.error}).`);
|
|
170
|
+
hint('Run `sl login` to try again.');
|
|
171
|
+
process.exit(2);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (token.accessToken && token.refreshToken && token.idToken && token.expiresIn) {
|
|
175
|
+
saveCredentials({
|
|
176
|
+
accessToken: token.accessToken,
|
|
177
|
+
refreshToken: token.refreshToken,
|
|
178
|
+
idToken: token.idToken,
|
|
179
|
+
expiresAt: Math.floor(Date.now() / 1000) + token.expiresIn,
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
success('Logged in successfully.');
|
|
183
|
+
await setupUserContext(opts.endpoint);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
error('Authentication timed out — no response from the browser.');
|
|
189
|
+
hint('Run `sl login` to start a new session.');
|
|
190
|
+
process.exit(2);
|
|
191
|
+
});
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Command } from 'commander';
|
|
2
|
+
|
|
3
|
+
import { graphqlUnauthenticated } from '../graphql/client.ts';
|
|
4
|
+
import { LogoutUrl } from '../graphql/operations/hermes.ts';
|
|
5
|
+
import { clearCredentials } from '../lib/auth.ts';
|
|
6
|
+
import { openBrowser } from '../lib/browser.ts';
|
|
7
|
+
import { hint, info, success, warn } from '../lib/output.ts';
|
|
8
|
+
|
|
9
|
+
export const logoutCommand = new Command('logout')
|
|
10
|
+
.summary('Log out and remove stored credentials')
|
|
11
|
+
.description(
|
|
12
|
+
'Log out and remove stored credentials\n\n' +
|
|
13
|
+
'Deletes the saved tokens from ~/.sortlist/credentials.json and\n' +
|
|
14
|
+
'opens the Auth0 logout URL in your browser so the next `sl login`\n' +
|
|
15
|
+
"doesn't silently reuse the previous account.\n\n" +
|
|
16
|
+
'Examples:\n' +
|
|
17
|
+
' sl logout Clear credentials and log out of Auth0\n' +
|
|
18
|
+
' sl logout --no-browser Only clear local credentials',
|
|
19
|
+
)
|
|
20
|
+
.option('--no-browser', 'Skip opening the Auth0 logout URL in a browser')
|
|
21
|
+
.action(async function (this: Command) {
|
|
22
|
+
const opts = this.optsWithGlobals();
|
|
23
|
+
|
|
24
|
+
clearCredentials();
|
|
25
|
+
success('Logged out — credentials removed.');
|
|
26
|
+
|
|
27
|
+
if (!opts.browser) {
|
|
28
|
+
hint('Run `sl login` to authenticate again.');
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
try {
|
|
33
|
+
const data = await graphqlUnauthenticated(LogoutUrl, {}, opts.endpoint);
|
|
34
|
+
if (data.logoutUrl) {
|
|
35
|
+
openBrowser(data.logoutUrl);
|
|
36
|
+
info('Opened Auth0 logout in your browser.');
|
|
37
|
+
}
|
|
38
|
+
} catch {
|
|
39
|
+
warn('Could not fetch the Auth0 logout URL — skipped browser logout.');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
hint('Run `sl login` to authenticate again.');
|
|
43
|
+
});
|