@sortlist/cli 0.41.0 → 0.47.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/dist/index.js +643 -113
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -88,6 +88,8 @@ function hint(msg) {
|
|
|
88
88
|
|
|
89
89
|
// src/lib/auth.ts
|
|
90
90
|
var CREDENTIALS_PATH = path2.join(os2.homedir(), ".sortlist", "credentials.json");
|
|
91
|
+
var ELEVATED_CREDENTIALS_PATH = path2.join(os2.homedir(), ".sortlist", "elevated-credentials.json");
|
|
92
|
+
var ELEVATION_MAX_SECONDS = 30 * 60;
|
|
91
93
|
function ensureDir() {
|
|
92
94
|
const dir = path2.dirname(CREDENTIALS_PATH);
|
|
93
95
|
if (!fs2.existsSync(dir)) {
|
|
@@ -115,6 +117,40 @@ function clearCredentials() {
|
|
|
115
117
|
function isExpired(creds) {
|
|
116
118
|
return Date.now() >= (creds.expiresAt - 60) * 1e3;
|
|
117
119
|
}
|
|
120
|
+
function saveElevatedCredentials(accessToken, expiresIn, level) {
|
|
121
|
+
const creds = {
|
|
122
|
+
accessToken,
|
|
123
|
+
expiresAt: Math.floor(Date.now() / 1e3) + Math.min(expiresIn, ELEVATION_MAX_SECONDS),
|
|
124
|
+
level
|
|
125
|
+
};
|
|
126
|
+
ensureDir();
|
|
127
|
+
fs2.writeFileSync(ELEVATED_CREDENTIALS_PATH, JSON.stringify(creds, null, 2) + "\n", { mode: 384 });
|
|
128
|
+
return creds;
|
|
129
|
+
}
|
|
130
|
+
function loadElevatedCredentials() {
|
|
131
|
+
let creds;
|
|
132
|
+
try {
|
|
133
|
+
creds = JSON.parse(fs2.readFileSync(ELEVATED_CREDENTIALS_PATH, "utf-8"));
|
|
134
|
+
} catch {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
if (isExpired(creds)) {
|
|
138
|
+
clearElevatedCredentials();
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
return creds;
|
|
142
|
+
}
|
|
143
|
+
function clearElevatedCredentials() {
|
|
144
|
+
try {
|
|
145
|
+
fs2.unlinkSync(ELEVATED_CREDENTIALS_PATH);
|
|
146
|
+
return true;
|
|
147
|
+
} catch {
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function storedUserAccessToken() {
|
|
152
|
+
return loadElevatedCredentials()?.accessToken ?? loadCredentials()?.accessToken ?? null;
|
|
153
|
+
}
|
|
118
154
|
function ensureAuthenticated() {
|
|
119
155
|
const creds = loadCredentials();
|
|
120
156
|
if (!creds) {
|
|
@@ -212,13 +248,13 @@ var ENVIRONMENTS = [
|
|
|
212
248
|
name: "production",
|
|
213
249
|
label: "federation.sortlist.com",
|
|
214
250
|
endpoint: "https://federation.sortlist.com/graphql",
|
|
215
|
-
tokenEndpoint: "https://hermes.
|
|
251
|
+
tokenEndpoint: "https://hermes.sortlist.com/oauth/token"
|
|
216
252
|
},
|
|
217
253
|
{
|
|
218
254
|
name: "staging",
|
|
219
255
|
label: "federation.sortlist-test.com",
|
|
220
256
|
endpoint: "https://federation.sortlist-test.com/graphql",
|
|
221
|
-
tokenEndpoint: "https://hermes.
|
|
257
|
+
tokenEndpoint: "https://hermes.sortlist-test.com/oauth/token"
|
|
222
258
|
},
|
|
223
259
|
{
|
|
224
260
|
name: "local",
|
|
@@ -269,22 +305,24 @@ if (isLocalDev) {
|
|
|
269
305
|
configCommand.command("reset").description("Reset all config and credentials").action(() => {
|
|
270
306
|
resetConfig();
|
|
271
307
|
clearCredentials();
|
|
308
|
+
clearElevatedCredentials();
|
|
272
309
|
clearApplicationSession();
|
|
273
310
|
success("Config, credentials and any application session cleared.");
|
|
274
311
|
hint("Run `sl login` to re-authenticate.");
|
|
275
312
|
});
|
|
276
313
|
|
|
277
314
|
// src/commands/dynamic.ts
|
|
278
|
-
import {
|
|
315
|
+
import { randomUUID } from "crypto";
|
|
316
|
+
import { Command as Command2, Option } from "commander";
|
|
279
317
|
import {
|
|
280
318
|
isEnumType as isEnumType2,
|
|
281
319
|
isInputObjectType,
|
|
282
|
-
isInterfaceType
|
|
320
|
+
isInterfaceType,
|
|
283
321
|
isListType as isListType2,
|
|
284
322
|
isNonNullType as isNonNullType2,
|
|
285
323
|
isObjectType as isObjectType2,
|
|
286
324
|
isScalarType as isScalarType2,
|
|
287
|
-
isUnionType
|
|
325
|
+
isUnionType
|
|
288
326
|
} from "graphql";
|
|
289
327
|
|
|
290
328
|
// src/graphql/client.ts
|
|
@@ -348,12 +386,16 @@ function applicationIdentity(accessToken) {
|
|
|
348
386
|
return null;
|
|
349
387
|
}
|
|
350
388
|
}
|
|
389
|
+
var RETIRED_TOKEN_ENDPOINTS = {
|
|
390
|
+
"https://hermes.production.sortlist.cloud/oauth/token": "https://hermes.sortlist.com/oauth/token",
|
|
391
|
+
"https://hermes.staging.sortlist.cloud/oauth/token": "https://hermes.sortlist-test.com/oauth/token"
|
|
392
|
+
};
|
|
351
393
|
function tokenEndpoint() {
|
|
352
394
|
const configured = process.env.SORTLIST_TOKEN_URL ?? loadConfig().tokenEndpoint;
|
|
353
395
|
if (!configured) {
|
|
354
396
|
throw new Error("No token endpoint configured. Set SORTLIST_TOKEN_URL or run: sl config set tokenEndpoint <url>");
|
|
355
397
|
}
|
|
356
|
-
return configured;
|
|
398
|
+
return RETIRED_TOKEN_ENDPOINTS[configured] ?? configured;
|
|
357
399
|
}
|
|
358
400
|
async function fetchClientCredentialsToken(credentials) {
|
|
359
401
|
if (cached && Date.now() < cached.expiresAt) return cached.accessToken;
|
|
@@ -389,7 +431,17 @@ function isCompanyId(value) {
|
|
|
389
431
|
}
|
|
390
432
|
}
|
|
391
433
|
var COMPANY_BY_SLUG = `query CompanyBySlug($slug: String!) { company(slug: $slug) { id } }`;
|
|
434
|
+
var PERSONAL_COMPANY = `query PersonalCompany { me { companies(first: 50) { nodes { id personal } } } }`;
|
|
392
435
|
var resolved = /* @__PURE__ */ new Map();
|
|
436
|
+
var personal;
|
|
437
|
+
function pickPersonalCompanyId(data) {
|
|
438
|
+
const me = data.me;
|
|
439
|
+
return me?.companies?.nodes?.find((company) => company.personal === true)?.id;
|
|
440
|
+
}
|
|
441
|
+
function personalCompanyId() {
|
|
442
|
+
personal ??= graphqlRaw(PERSONAL_COMPANY, void 0, { withoutCompany: true, throwOnError: true }).then(pickPersonalCompanyId).catch(() => void 0);
|
|
443
|
+
return personal;
|
|
444
|
+
}
|
|
393
445
|
async function lookupCompanyId(slug) {
|
|
394
446
|
const data = await graphqlRaw(COMPANY_BY_SLUG, { slug }, { withoutCompany: true });
|
|
395
447
|
const id = data.company?.id;
|
|
@@ -600,6 +652,8 @@ async function resolveAccessToken(options, attempt) {
|
|
|
600
652
|
hint("Run `sl use application <id>` again, or `sl use me` to act as yourself.");
|
|
601
653
|
process.exit(2);
|
|
602
654
|
}
|
|
655
|
+
const elevated = options.asPerson ? null : loadElevatedCredentials();
|
|
656
|
+
if (elevated) return { token: elevated.accessToken, kind: "user" };
|
|
603
657
|
let creds = ensureAuthenticated();
|
|
604
658
|
if (isExpired(creds)) {
|
|
605
659
|
const refreshed = await refreshAccessToken(creds, attempt.endpoint);
|
|
@@ -646,12 +700,15 @@ function codeOf(errors) {
|
|
|
646
700
|
return null;
|
|
647
701
|
}
|
|
648
702
|
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
703
|
+
var CALLBACK_STATUS_NOT_OK = "SUBGRAPH_HTTP_CALLBACK_STATUS_CODE_NOT_OK";
|
|
649
704
|
function subrequestStatus(errors) {
|
|
650
|
-
for (const { extensions } of errors) {
|
|
705
|
+
for (const { message, extensions } of errors) {
|
|
651
706
|
const http = extensions?.http;
|
|
652
707
|
if (typeof http === "object" && http !== null && typeof http.status === "number") {
|
|
653
708
|
return http.status;
|
|
654
709
|
}
|
|
710
|
+
const callbackStatus = extensions?.code === CALLBACK_STATUS_NOT_OK ? message.match(/'(\d{3})\b/)?.[1] : void 0;
|
|
711
|
+
if (callbackStatus) return Number(callbackStatus);
|
|
655
712
|
}
|
|
656
713
|
return null;
|
|
657
714
|
}
|
|
@@ -665,11 +722,39 @@ function detailLines(errors) {
|
|
|
665
722
|
const details = extensions?.details;
|
|
666
723
|
if (typeof details !== "object" || details === null) continue;
|
|
667
724
|
for (const [attribute, codes] of Object.entries(details)) {
|
|
668
|
-
|
|
725
|
+
const described = Array.isArray(codes) ? codes.map(describeDetail) : [describeDetail(codes)];
|
|
726
|
+
lines.push(`${attribute}: ${described.join(", ")}`);
|
|
669
727
|
}
|
|
670
728
|
}
|
|
671
729
|
return lines;
|
|
672
730
|
}
|
|
731
|
+
function describeDetail(detail) {
|
|
732
|
+
if (typeof detail !== "object" || detail === null) return String(detail);
|
|
733
|
+
const { error: error2, message, ...rest } = detail;
|
|
734
|
+
if (error2 === void 0) return JSON.stringify(detail);
|
|
735
|
+
const context = Object.entries(rest).map(([key, value]) => `${key}: ${String(value)}`);
|
|
736
|
+
const code = context.length > 0 ? `${String(error2)} (${context.join(", ")})` : String(error2);
|
|
737
|
+
return message === void 0 ? code : `${code} \u2014 ${String(message)}`;
|
|
738
|
+
}
|
|
739
|
+
var HEADLINE_EXTENSIONS = /* @__PURE__ */ new Set(["code", "details"]);
|
|
740
|
+
function explainLines(errors) {
|
|
741
|
+
const lines = detailLines(errors);
|
|
742
|
+
const seen = new Set(lines);
|
|
743
|
+
const add = (line) => {
|
|
744
|
+
if (seen.has(line)) return;
|
|
745
|
+
seen.add(line);
|
|
746
|
+
lines.push(line);
|
|
747
|
+
};
|
|
748
|
+
for (const gqlError of errors) {
|
|
749
|
+
if (gqlError.message !== ROUTER_PLACEHOLDER && gqlError.message !== "") add(`message: ${gqlError.message}`);
|
|
750
|
+
for (const [key, value] of Object.entries(gqlError.extensions ?? {})) {
|
|
751
|
+
if (HEADLINE_EXTENSIONS.has(key) || value === null || value === void 0) continue;
|
|
752
|
+
add(`${key}: ${typeof value === "object" ? JSON.stringify(value) : String(value)}`);
|
|
753
|
+
}
|
|
754
|
+
if (gqlError.path !== void 0 && gqlError.path.length > 0) add(`path: ${gqlError.path.join(".")}`);
|
|
755
|
+
}
|
|
756
|
+
return lines;
|
|
757
|
+
}
|
|
673
758
|
var ROUTER_PLACEHOLDER = "Unexpected error";
|
|
674
759
|
function describe(errors) {
|
|
675
760
|
const code = codeOf(errors);
|
|
@@ -691,6 +776,12 @@ function serviceOf(errors) {
|
|
|
691
776
|
}
|
|
692
777
|
return null;
|
|
693
778
|
}
|
|
779
|
+
function refusedForNamingNoCompany(errors, namedNoCompany) {
|
|
780
|
+
if (!namedNoCompany) return false;
|
|
781
|
+
const status = subrequestStatus(errors);
|
|
782
|
+
const maskedCallbackRefusal = status === null && codeOf(errors) === CALLBACK_STATUS_NOT_OK;
|
|
783
|
+
return status === 403 || maskedCallbackRefusal;
|
|
784
|
+
}
|
|
694
785
|
function hasResolvedField(data) {
|
|
695
786
|
if (data === null || data === void 0) return false;
|
|
696
787
|
return Object.values(data).some((value) => value !== null);
|
|
@@ -737,7 +828,12 @@ function reportGraphqlErrors(errors, options, attempt) {
|
|
|
737
828
|
const service = serviceOf(errors);
|
|
738
829
|
const where = service ?? "The subgraph";
|
|
739
830
|
const company = options.company ?? getUserContext().company ?? options.companyId;
|
|
740
|
-
if (
|
|
831
|
+
if (options.actingForPersonalCompany) {
|
|
832
|
+
error(`${where} refused to act for your personal company.`);
|
|
833
|
+
hint("It was tried because the request named no company, and your token does not list it as yours.");
|
|
834
|
+
hint("On a local stack the token comes from a shared tenant and lists that environment's companies.");
|
|
835
|
+
hint("Pass --company <slug|id>, or `sl config set company <slug|id>`; `sl companies` lists them.");
|
|
836
|
+
} else if (company && UUID.test(company)) {
|
|
741
837
|
error(`${where} refused ${company}: that is a raw uuid, not a company id.`);
|
|
742
838
|
hint("Pass its slug, or the id `sl companies` lists.");
|
|
743
839
|
} else if (company) {
|
|
@@ -756,9 +852,7 @@ function reportGraphqlErrors(errors, options, attempt) {
|
|
|
756
852
|
const code = codeOf(errors);
|
|
757
853
|
if (code !== null && code !== "DOWNSTREAM_SERVICE_ERROR") {
|
|
758
854
|
error(humanise(code));
|
|
759
|
-
const
|
|
760
|
-
const lines = details.length > 0 ? details : messageLines(errors);
|
|
761
|
-
for (const line of lines) info(` ${line}`);
|
|
855
|
+
for (const line of explainLines(errors)) info(` ${line}`);
|
|
762
856
|
if (verbose) for (const gqlError of errors) info(`[debug] ${JSON.stringify(gqlError)}`);
|
|
763
857
|
process.exit(1);
|
|
764
858
|
}
|
|
@@ -779,8 +873,7 @@ function logRequest(query, variables, attempt) {
|
|
|
779
873
|
${query}`);
|
|
780
874
|
if (variables) info(`[debug] Variables: ${JSON.stringify(variables, null, 2)}`);
|
|
781
875
|
}
|
|
782
|
-
|
|
783
|
-
const authenticated = options.authenticated ?? true;
|
|
876
|
+
function startAttempt(query, variables, options) {
|
|
784
877
|
const attempt = {
|
|
785
878
|
endpoint: getEndpoint(options.endpoint),
|
|
786
879
|
operationName: extractOperationName(query),
|
|
@@ -790,18 +883,25 @@ async function executeQuery(query, variables, options = {}) {
|
|
|
790
883
|
addBreadcrumb2({
|
|
791
884
|
category: "graphql",
|
|
792
885
|
message: attempt.operationName,
|
|
793
|
-
data: { endpoint: attempt.endpoint, authenticated },
|
|
886
|
+
data: { endpoint: attempt.endpoint, authenticated: options.authenticated ?? true },
|
|
794
887
|
level: "info"
|
|
795
888
|
});
|
|
796
889
|
if (attempt.verbose) logRequest(query, variables, attempt);
|
|
890
|
+
return attempt;
|
|
891
|
+
}
|
|
892
|
+
async function requestHeaders(options, attempt) {
|
|
797
893
|
const headers = baseRequestHeaders();
|
|
798
|
-
if (authenticated) {
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
}
|
|
894
|
+
if (!(options.authenticated ?? true)) return { headers, namedNoCompany: false };
|
|
895
|
+
const { token, kind } = await resolveAccessToken(options, attempt);
|
|
896
|
+
headers["Authorization"] = `Bearer ${token}`;
|
|
897
|
+
const companyId = options.withoutCompany ? void 0 : options.companyId ?? await resolveCompanyId({ ctx: getUserContext() });
|
|
898
|
+
if (companyId) headers["X-Company-Id"] = companyId;
|
|
899
|
+
if (attempt.verbose) info(`[debug] ${kind} token: ...${token.slice(-8)}`);
|
|
900
|
+
return { headers, namedNoCompany: !companyId && kind === "user" && !options.withoutCompany };
|
|
901
|
+
}
|
|
902
|
+
async function executeQuery(query, variables, options = {}) {
|
|
903
|
+
const attempt = startAttempt(query, variables, options);
|
|
904
|
+
const { headers, namedNoCompany } = await requestHeaders(options, attempt);
|
|
805
905
|
let res;
|
|
806
906
|
try {
|
|
807
907
|
res = await fetch(attempt.endpoint, {
|
|
@@ -820,6 +920,12 @@ async function executeQuery(query, variables, options = {}) {
|
|
|
820
920
|
const json = await res.json();
|
|
821
921
|
if (json.errors?.length) {
|
|
822
922
|
const refused = !hasResolvedField(json.data);
|
|
923
|
+
if (refused && refusedForNamingNoCompany(json.errors, namedNoCompany)) {
|
|
924
|
+
const personal2 = await personalCompanyId();
|
|
925
|
+
if (personal2) {
|
|
926
|
+
return executeQuery(query, variables, { ...options, companyId: personal2, actingForPersonalCompany: true });
|
|
927
|
+
}
|
|
928
|
+
}
|
|
823
929
|
if (refused) reportGraphqlErrors(json.errors, options, attempt);
|
|
824
930
|
for (const gqlError of json.errors) warn(gqlError.message);
|
|
825
931
|
if (hasFieldError(json.errors)) {
|
|
@@ -840,6 +946,101 @@ async function executeQuery(query, variables, options = {}) {
|
|
|
840
946
|
}
|
|
841
947
|
return json.data;
|
|
842
948
|
}
|
|
949
|
+
async function* parseEventStream(chunks) {
|
|
950
|
+
const decoder = new TextDecoder();
|
|
951
|
+
let buffer = "";
|
|
952
|
+
for await (const chunk of chunks) {
|
|
953
|
+
buffer += typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true });
|
|
954
|
+
buffer = buffer.replaceAll("\r\n", "\n");
|
|
955
|
+
let boundary = buffer.indexOf("\n\n");
|
|
956
|
+
while (boundary !== -1) {
|
|
957
|
+
const block = buffer.slice(0, boundary);
|
|
958
|
+
buffer = buffer.slice(boundary + 2);
|
|
959
|
+
const parsed = parseEventBlock(block);
|
|
960
|
+
if (parsed) yield parsed;
|
|
961
|
+
boundary = buffer.indexOf("\n\n");
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
const rest = parseEventBlock(buffer);
|
|
965
|
+
if (rest) yield rest;
|
|
966
|
+
}
|
|
967
|
+
function parseEventBlock(block) {
|
|
968
|
+
let event = "message";
|
|
969
|
+
const data = [];
|
|
970
|
+
for (const line of block.split("\n")) {
|
|
971
|
+
if (line === "" || line.startsWith(":")) continue;
|
|
972
|
+
const colon = line.indexOf(":");
|
|
973
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
974
|
+
const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
975
|
+
if (field === "event") event = value;
|
|
976
|
+
if (field === "data") data.push(value);
|
|
977
|
+
}
|
|
978
|
+
return data.length > 0 || event !== "message" ? { event, data: data.join("\n") } : null;
|
|
979
|
+
}
|
|
980
|
+
async function openEventStream(query, variables, options, attempt) {
|
|
981
|
+
const { headers, namedNoCompany } = await requestHeaders(options, attempt);
|
|
982
|
+
headers["Accept"] = "text/event-stream";
|
|
983
|
+
let res;
|
|
984
|
+
try {
|
|
985
|
+
res = await fetch(attempt.endpoint, {
|
|
986
|
+
method: "POST",
|
|
987
|
+
headers,
|
|
988
|
+
body: JSON.stringify({ query, variables }),
|
|
989
|
+
signal: options.signal
|
|
990
|
+
});
|
|
991
|
+
} catch (err) {
|
|
992
|
+
reportUnreachable(err, {
|
|
993
|
+
endpoint: attempt.endpoint,
|
|
994
|
+
operationName: attempt.operationName,
|
|
995
|
+
throwOnError: attempt.throwOnError
|
|
996
|
+
});
|
|
997
|
+
}
|
|
998
|
+
if (!res.ok) {
|
|
999
|
+
const body = await res.text();
|
|
1000
|
+
const errors = parseErrors(body);
|
|
1001
|
+
if (errors) reportGraphqlErrors(errors, options, attempt);
|
|
1002
|
+
reportHttpFailure(res, body, attempt);
|
|
1003
|
+
}
|
|
1004
|
+
return { res, namedNoCompany };
|
|
1005
|
+
}
|
|
1006
|
+
function parseErrors(body) {
|
|
1007
|
+
try {
|
|
1008
|
+
const errors = JSON.parse(body).errors;
|
|
1009
|
+
return errors?.length ? errors : null;
|
|
1010
|
+
} catch {
|
|
1011
|
+
return null;
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
async function* subscriptionEvents(res, query, variables, options, attempt, namedNoCompany) {
|
|
1015
|
+
if (!res.body) return;
|
|
1016
|
+
for await (const { event, data } of parseEventStream(res.body)) {
|
|
1017
|
+
if (event === "complete") return;
|
|
1018
|
+
if (event !== "next" && event !== "message") continue;
|
|
1019
|
+
const payload = JSON.parse(data);
|
|
1020
|
+
if (payload.errors?.length && !hasResolvedField(payload.data)) {
|
|
1021
|
+
if (refusedForNamingNoCompany(payload.errors, namedNoCompany)) {
|
|
1022
|
+
const personal2 = await personalCompanyId();
|
|
1023
|
+
if (personal2) {
|
|
1024
|
+
const retry = await graphqlSubscribe(query, variables, {
|
|
1025
|
+
...options,
|
|
1026
|
+
companyId: personal2,
|
|
1027
|
+
actingForPersonalCompany: true
|
|
1028
|
+
});
|
|
1029
|
+
yield* retry.events;
|
|
1030
|
+
return;
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
reportGraphqlErrors(payload.errors, options, attempt);
|
|
1034
|
+
}
|
|
1035
|
+
for (const gqlError of payload.errors ?? []) warn(gqlError.message);
|
|
1036
|
+
if (payload.data) yield payload.data;
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
async function graphqlSubscribe(query, variables, options = {}) {
|
|
1040
|
+
const attempt = startAttempt(query, variables, options);
|
|
1041
|
+
const { res, namedNoCompany } = await openEventStream(query, variables, options, attempt);
|
|
1042
|
+
return { events: subscriptionEvents(res, query, variables, options, attempt, namedNoCompany) };
|
|
1043
|
+
}
|
|
843
1044
|
async function graphql(document, variables, options = {}) {
|
|
844
1045
|
return executeQuery(print(document), variables, options);
|
|
845
1046
|
}
|
|
@@ -852,13 +1053,12 @@ async function graphqlUnauthenticated(document, variables, endpoint) {
|
|
|
852
1053
|
|
|
853
1054
|
// src/graphql/query-builder.ts
|
|
854
1055
|
import {
|
|
1056
|
+
isAbstractType,
|
|
855
1057
|
isEnumType,
|
|
856
|
-
isInterfaceType,
|
|
857
1058
|
isListType,
|
|
858
1059
|
isNonNullType,
|
|
859
1060
|
isObjectType,
|
|
860
|
-
isScalarType
|
|
861
|
-
isUnionType
|
|
1061
|
+
isScalarType
|
|
862
1062
|
} from "graphql";
|
|
863
1063
|
var CLI_OPERATION_PREFIX = "SlCli_";
|
|
864
1064
|
function unwrap(type) {
|
|
@@ -873,6 +1073,10 @@ function ucfirst(s) {
|
|
|
873
1073
|
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
874
1074
|
}
|
|
875
1075
|
var PAYLOAD_TYPE_PATTERN = /(?:Response|Payload|MutationPayload)$/;
|
|
1076
|
+
var PAYLOAD_PLUMBING = /* @__PURE__ */ new Set(["id", "clientMutationId"]);
|
|
1077
|
+
function effectiveDepth(returnType, depth) {
|
|
1078
|
+
return isObjectType(returnType) && PAYLOAD_TYPE_PATTERN.test(returnType.name) ? depth + 1 : depth;
|
|
1079
|
+
}
|
|
876
1080
|
function buildSelections(type, schema, depth, exclude, prefix, totalCount, visited) {
|
|
877
1081
|
if (!isObjectType(type)) return [];
|
|
878
1082
|
if (visited.has(type.name)) return [];
|
|
@@ -895,7 +1099,7 @@ function buildSelections(type, schema, depth, exclude, prefix, totalCount, visit
|
|
|
895
1099
|
}
|
|
896
1100
|
for (const [name, field] of Object.entries(fields)) {
|
|
897
1101
|
if (name.startsWith("__")) continue;
|
|
898
|
-
if (
|
|
1102
|
+
if (isPayload && PAYLOAD_PLUMBING.has(name)) continue;
|
|
899
1103
|
const fullPath = `${prefix}${name}`;
|
|
900
1104
|
if (exclude.has(fullPath) || exclude.has(name)) continue;
|
|
901
1105
|
const hasRequiredArgs = field.args.some((a) => isNonNullType(a.type) && a.defaultValue === void 0);
|
|
@@ -918,10 +1122,35 @@ function buildSelections(type, schema, depth, exclude, prefix, totalCount, visit
|
|
|
918
1122
|
for (const sel of subSelections) lines.push(` ${sel}`);
|
|
919
1123
|
lines.push(`}`);
|
|
920
1124
|
}
|
|
1125
|
+
} else if (isAbstractType(namedType) && depth > 0) {
|
|
1126
|
+
lines.push(`${name} {`);
|
|
1127
|
+
for (const sel of abstractSelections(
|
|
1128
|
+
namedType,
|
|
1129
|
+
schema,
|
|
1130
|
+
depth - 1,
|
|
1131
|
+
exclude,
|
|
1132
|
+
`${fullPath}.`,
|
|
1133
|
+
totalCount,
|
|
1134
|
+
visited
|
|
1135
|
+
)) {
|
|
1136
|
+
lines.push(` ${sel}`);
|
|
1137
|
+
}
|
|
1138
|
+
lines.push(`}`);
|
|
921
1139
|
}
|
|
922
1140
|
}
|
|
923
1141
|
return lines;
|
|
924
1142
|
}
|
|
1143
|
+
function abstractSelections(type, schema, depth, exclude, prefix, totalCount, visited) {
|
|
1144
|
+
const lines = ["__typename"];
|
|
1145
|
+
for (const member of schema.getPossibleTypes(type)) {
|
|
1146
|
+
const memberSelections = buildSelections(member, schema, depth, exclude, prefix, totalCount, new Set(visited));
|
|
1147
|
+
if (memberSelections.length === 0) continue;
|
|
1148
|
+
lines.push(`... on ${member.name} {`);
|
|
1149
|
+
for (const sel of memberSelections) lines.push(` ${sel}`);
|
|
1150
|
+
lines.push(`}`);
|
|
1151
|
+
}
|
|
1152
|
+
return lines;
|
|
1153
|
+
}
|
|
925
1154
|
var NESTED_PAGE_SIZE = 10;
|
|
926
1155
|
function fieldCall(name, field) {
|
|
927
1156
|
const named = unwrap(field.type);
|
|
@@ -995,11 +1224,14 @@ function connectionExtras(connection) {
|
|
|
995
1224
|
return inner.length === 0 ? [] : [`${field.name} { ${inner.join(" ")} }`];
|
|
996
1225
|
});
|
|
997
1226
|
}
|
|
1227
|
+
function fieldNamesOf(type) {
|
|
1228
|
+
return isObjectType(type) ? Object.keys(type.getFields()) : [];
|
|
1229
|
+
}
|
|
998
1230
|
var UnknownFieldError = class extends Error {
|
|
999
1231
|
field;
|
|
1000
1232
|
suggestions;
|
|
1001
|
-
constructor(field, type) {
|
|
1002
|
-
const names =
|
|
1233
|
+
constructor(field, type, candidates = fieldNamesOf(type)) {
|
|
1234
|
+
const names = candidates.filter((name) => !name.startsWith("__"));
|
|
1003
1235
|
const needle = field.toLowerCase();
|
|
1004
1236
|
const suggestions = names.filter((name) => {
|
|
1005
1237
|
const candidate = name.toLowerCase();
|
|
@@ -1011,23 +1243,34 @@ var UnknownFieldError = class extends Error {
|
|
|
1011
1243
|
this.suggestions = suggestions.length > 0 ? suggestions : names;
|
|
1012
1244
|
}
|
|
1013
1245
|
};
|
|
1246
|
+
function rootTypeOf(schema, kind) {
|
|
1247
|
+
if (kind === "query") return schema.getQueryType();
|
|
1248
|
+
if (kind === "mutation") return schema.getMutationType();
|
|
1249
|
+
return schema.getSubscriptionType();
|
|
1250
|
+
}
|
|
1014
1251
|
function buildQuery(schema, kind, fieldName, variables, options = {}) {
|
|
1015
|
-
const rootType =
|
|
1252
|
+
const rootType = rootTypeOf(schema, kind);
|
|
1016
1253
|
if (!rootType) throw new Error(`No ${kind} type in schema`);
|
|
1017
1254
|
const field = rootType.getFields()[fieldName];
|
|
1018
1255
|
if (!field) throw new Error(`Unknown ${kind} field: ${fieldName}`);
|
|
1019
|
-
const
|
|
1256
|
+
const returnType = unwrap(field.type);
|
|
1257
|
+
const depth = effectiveDepth(returnType, options.depth ?? 0);
|
|
1020
1258
|
const exclude = new Set(options.exclude ?? []);
|
|
1021
1259
|
const wantsTotalCount = options.totalCount === true;
|
|
1022
|
-
const returnType = unwrap(field.type);
|
|
1023
1260
|
const allArgs = field.args;
|
|
1024
1261
|
const varDefsInner = allArgs.map((a) => `$${a.name}: ${a.type.toString()}`).join(", ");
|
|
1025
1262
|
const fieldArgsInner = allArgs.map((a) => `${a.name}: $${a.name}`).join(", ");
|
|
1026
1263
|
const varDefs = allArgs.length > 0 ? `(${varDefsInner})` : "";
|
|
1027
1264
|
const fieldArgs = allArgs.length > 0 ? `(${fieldArgsInner})` : "";
|
|
1028
1265
|
let selectionBody;
|
|
1029
|
-
if (isLeaf(returnType)
|
|
1266
|
+
if (isLeaf(returnType)) {
|
|
1030
1267
|
selectionBody = ` ${fieldName}${fieldArgs}`;
|
|
1268
|
+
} else if (isAbstractType(returnType)) {
|
|
1269
|
+
const indent = " ";
|
|
1270
|
+
const body = abstractSelections(returnType, schema, depth, exclude, "", wantsTotalCount, /* @__PURE__ */ new Set()).map((s) => `${indent}${s}`).join("\n");
|
|
1271
|
+
selectionBody = ` ${fieldName}${fieldArgs} {
|
|
1272
|
+
${body}
|
|
1273
|
+
}`;
|
|
1031
1274
|
} else {
|
|
1032
1275
|
let selections;
|
|
1033
1276
|
if (options.fields && options.fields.length > 0) {
|
|
@@ -1087,10 +1330,35 @@ function buildFieldsFromList(type, schema, fieldPaths, totalCount) {
|
|
|
1087
1330
|
for (const sel of subSelections) lines.push(` ${sel}`);
|
|
1088
1331
|
lines.push(`}`);
|
|
1089
1332
|
}
|
|
1333
|
+
} else if (isAbstractType(namedType)) {
|
|
1334
|
+
lines.push(`${name} {`);
|
|
1335
|
+
for (const sel of abstractFieldsFromList(namedType, schema, subPaths, totalCount)) lines.push(` ${sel}`);
|
|
1336
|
+
lines.push(`}`);
|
|
1090
1337
|
}
|
|
1091
1338
|
}
|
|
1092
1339
|
return lines;
|
|
1093
1340
|
}
|
|
1341
|
+
function abstractFieldsFromList(type, schema, subPaths, totalCount) {
|
|
1342
|
+
const members = schema.getPossibleTypes(type);
|
|
1343
|
+
if (subPaths.length === 0) {
|
|
1344
|
+
return abstractSelections(type, schema, 0, /* @__PURE__ */ new Set(), "", totalCount, /* @__PURE__ */ new Set());
|
|
1345
|
+
}
|
|
1346
|
+
const lines = ["__typename"];
|
|
1347
|
+
const claimed = /* @__PURE__ */ new Set();
|
|
1348
|
+
for (const member of members) {
|
|
1349
|
+
const known = subPaths.filter((fp) => Boolean(member.getFields()[fp.split(".")[0]]));
|
|
1350
|
+
if (known.length === 0) continue;
|
|
1351
|
+
for (const fp of known) claimed.add(fp);
|
|
1352
|
+
lines.push(`... on ${member.name} {`);
|
|
1353
|
+
for (const sel of buildFieldsFromList(member, schema, known, totalCount)) lines.push(` ${sel}`);
|
|
1354
|
+
lines.push(`}`);
|
|
1355
|
+
}
|
|
1356
|
+
const unknown = subPaths.find((fp) => !claimed.has(fp));
|
|
1357
|
+
if (unknown !== void 0) {
|
|
1358
|
+
throw new UnknownFieldError(unknown.split(".")[0], type, members.flatMap(fieldNamesOf));
|
|
1359
|
+
}
|
|
1360
|
+
return lines;
|
|
1361
|
+
}
|
|
1094
1362
|
|
|
1095
1363
|
// src/lib/render.ts
|
|
1096
1364
|
var INDENT = " ";
|
|
@@ -1155,10 +1423,13 @@ function summarise(key, value) {
|
|
|
1155
1423
|
if (Array.isArray(value)) return value.length === 0 ? "none" : `${value.length} items`;
|
|
1156
1424
|
if (isRecord(value)) {
|
|
1157
1425
|
const label = value.name ?? value.sub ?? value.id;
|
|
1158
|
-
return label === void 0 ?
|
|
1426
|
+
return label === void 0 ? null : formatScalar(label);
|
|
1159
1427
|
}
|
|
1160
1428
|
return null;
|
|
1161
1429
|
}
|
|
1430
|
+
function isUnlabelledRecord(value) {
|
|
1431
|
+
return isRecord(value) && value.name === void 0 && value.sub === void 0 && value.id === void 0;
|
|
1432
|
+
}
|
|
1162
1433
|
function titleOf(record) {
|
|
1163
1434
|
return typeof record.id === "string" && record.id !== "" ? record.id : null;
|
|
1164
1435
|
}
|
|
@@ -1169,6 +1440,11 @@ function formatRecord(record, indent, titled = false) {
|
|
|
1169
1440
|
const width = Math.max(0, ...entries.map(([key]) => key.length));
|
|
1170
1441
|
const valueIndent = `${indent}${"".padEnd(width)} `;
|
|
1171
1442
|
const body = entries.map(([key, value]) => {
|
|
1443
|
+
if (isUnlabelledRecord(value) && !asConnection(value)) {
|
|
1444
|
+
const nestedIndent = indent + INDENT;
|
|
1445
|
+
return `${indent}${key}
|
|
1446
|
+
${formatRecord(value, nestedIndent)}`;
|
|
1447
|
+
}
|
|
1172
1448
|
const rendered = isFlatRows(value) ? formatFlatRows(value, valueIndent) : summarise(key, value) ?? formatScalar(value);
|
|
1173
1449
|
return `${indent}${key.padEnd(width)} ${rendered}`;
|
|
1174
1450
|
}).join("\n");
|
|
@@ -1220,6 +1496,14 @@ function unwrap2(type) {
|
|
|
1220
1496
|
if (isListType2(type)) return unwrap2(type.ofType);
|
|
1221
1497
|
return type;
|
|
1222
1498
|
}
|
|
1499
|
+
var RESERVED_FLAGS = /* @__PURE__ */ new Set(["version", "help", "endpoint", "company", "json", "color", "no-color"]);
|
|
1500
|
+
function flagNameFor(fieldName, argName) {
|
|
1501
|
+
const name = kebab(argName);
|
|
1502
|
+
return RESERVED_FLAGS.has(name) ? `${kebab(fieldName)}-${name}` : name;
|
|
1503
|
+
}
|
|
1504
|
+
function optionKey(flagName) {
|
|
1505
|
+
return flagName.replace(/-([a-z0-9])/g, (_, letter) => letter.toUpperCase());
|
|
1506
|
+
}
|
|
1223
1507
|
function kebab(s) {
|
|
1224
1508
|
return s.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
|
|
1225
1509
|
}
|
|
@@ -1253,6 +1537,11 @@ function enumListOf(type) {
|
|
|
1253
1537
|
const inner = unwrap2(listless.ofType);
|
|
1254
1538
|
return isEnumType2(inner) ? inner : null;
|
|
1255
1539
|
}
|
|
1540
|
+
function enumOf(type) {
|
|
1541
|
+
const listless = isNonNullType2(type) ? type.ofType : type;
|
|
1542
|
+
if (isListType2(listless)) return null;
|
|
1543
|
+
return isEnumType2(listless) ? listless : null;
|
|
1544
|
+
}
|
|
1256
1545
|
function commonPrefix(values) {
|
|
1257
1546
|
if (values.length < 2) return "";
|
|
1258
1547
|
let prefix = values[0];
|
|
@@ -1260,28 +1549,46 @@ function commonPrefix(values) {
|
|
|
1260
1549
|
const cut = prefix.lastIndexOf("_");
|
|
1261
1550
|
return cut === -1 ? "" : prefix.slice(0, cut + 1);
|
|
1262
1551
|
}
|
|
1552
|
+
function matchEnumValue(part, names, prefix) {
|
|
1553
|
+
const wanted = part.trim().replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
|
|
1554
|
+
return names.find((name) => name === wanted || name === `${prefix}${wanted}`);
|
|
1555
|
+
}
|
|
1556
|
+
function spellableValues(names, prefix) {
|
|
1557
|
+
return names.map(
|
|
1558
|
+
(name) => name.slice(prefix.length).toLowerCase().replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())
|
|
1559
|
+
);
|
|
1560
|
+
}
|
|
1263
1561
|
function coerceEnumList(raw, enumType, flagName) {
|
|
1264
1562
|
const names = enumType.getValues().map((value) => value.name);
|
|
1265
1563
|
if (raw.trim() === "all") return names;
|
|
1266
1564
|
if (raw.trim() === "none") return [];
|
|
1267
1565
|
const prefix = commonPrefix(names);
|
|
1268
1566
|
return raw.split(",").filter((part) => part.trim() !== "").map((part) => {
|
|
1269
|
-
const
|
|
1270
|
-
const match = names.find((name) => name === wanted || name === `${prefix}${wanted}`);
|
|
1567
|
+
const match = matchEnumValue(part, names, prefix);
|
|
1271
1568
|
if (match === void 0) {
|
|
1272
|
-
const short = names.map(
|
|
1273
|
-
(name) => name.slice(prefix.length).toLowerCase().replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())
|
|
1274
|
-
);
|
|
1275
1569
|
throw new Error(
|
|
1276
|
-
`--${flagName} does not know "${part.trim()}". One or more of: ${
|
|
1570
|
+
`--${flagName} does not know "${part.trim()}". One or more of: ${spellableValues(names, prefix).join(", ")}, all, or none.`
|
|
1277
1571
|
);
|
|
1278
1572
|
}
|
|
1279
1573
|
return match;
|
|
1280
1574
|
});
|
|
1281
1575
|
}
|
|
1576
|
+
function coerceEnum(raw, enumType, flagName) {
|
|
1577
|
+
const names = enumType.getValues().map((value) => value.name);
|
|
1578
|
+
const prefix = commonPrefix(names);
|
|
1579
|
+
const match = matchEnumValue(raw, names, prefix);
|
|
1580
|
+
if (match === void 0) {
|
|
1581
|
+
throw new Error(
|
|
1582
|
+
`--${flagName} does not know "${raw.trim()}". One of: ${spellableValues(names, prefix).join(", ")}.`
|
|
1583
|
+
);
|
|
1584
|
+
}
|
|
1585
|
+
return match;
|
|
1586
|
+
}
|
|
1282
1587
|
function coerceValue(raw, type, flagName) {
|
|
1283
1588
|
const enumList = enumListOf(type);
|
|
1284
1589
|
if (enumList && !raw.trim().startsWith("[")) return coerceEnumList(raw, enumList, flagName);
|
|
1590
|
+
const enumValue = enumOf(type);
|
|
1591
|
+
if (enumValue) return coerceEnum(raw, enumValue, flagName);
|
|
1285
1592
|
if (isStructuredInput(type)) {
|
|
1286
1593
|
try {
|
|
1287
1594
|
return JSON.parse(raw);
|
|
@@ -1397,8 +1704,96 @@ function describeArg(arg) {
|
|
|
1397
1704
|
}
|
|
1398
1705
|
return parts.join(" \u2014 ");
|
|
1399
1706
|
}
|
|
1400
|
-
|
|
1401
|
-
|
|
1707
|
+
var DEFAULT_SUBSCRIPTION_TIMEOUT_SECONDS = 300;
|
|
1708
|
+
var DEFAULT_WAIT_SECONDS = 120;
|
|
1709
|
+
var TIMED_OUT_EXIT_CODE = 5;
|
|
1710
|
+
function supersededBy(field, siblings) {
|
|
1711
|
+
const replacement = field.deprecationReason?.match(/`(\w+)`/)?.[1];
|
|
1712
|
+
if (!replacement || SKIP_FIELDS.has(replacement)) return null;
|
|
1713
|
+
const sibling = siblings[replacement];
|
|
1714
|
+
return sibling && !sibling.deprecationReason ? replacement : null;
|
|
1715
|
+
}
|
|
1716
|
+
function hasExternalId(field) {
|
|
1717
|
+
const args = getInputFields(field) ?? field.args;
|
|
1718
|
+
return args.some((a) => a.name === "externalId");
|
|
1719
|
+
}
|
|
1720
|
+
function resultSubscriptions(schema) {
|
|
1721
|
+
const pairs = /* @__PURE__ */ new Map();
|
|
1722
|
+
const mutations = schema.getMutationType()?.getFields() ?? {};
|
|
1723
|
+
for (const [name, field] of Object.entries(schema.getSubscriptionType()?.getFields() ?? {})) {
|
|
1724
|
+
const mutation = field.description?.match(/(?:result|outcome) of an? `(\w+)` call/)?.[1];
|
|
1725
|
+
if (!mutation || !mutations[mutation]) continue;
|
|
1726
|
+
if (!field.args.some((a) => a.name === "externalId") || !hasExternalId(mutations[mutation])) continue;
|
|
1727
|
+
pairs.set(mutation, name);
|
|
1728
|
+
}
|
|
1729
|
+
return pairs;
|
|
1730
|
+
}
|
|
1731
|
+
function printResult(fieldName, result, opts) {
|
|
1732
|
+
if (result == null) {
|
|
1733
|
+
if (actingAsApplication()) {
|
|
1734
|
+
info(`${fieldName} answers for people, and you are acting as an application.`);
|
|
1735
|
+
hint("`sl whoami` reports what the token identifies; `sl use me` switches back.");
|
|
1736
|
+
} else {
|
|
1737
|
+
warn("No results returned.");
|
|
1738
|
+
hint("The query succeeded but the server returned null.");
|
|
1739
|
+
hint("Try different arguments or check that the resource exists.");
|
|
1740
|
+
}
|
|
1741
|
+
} else if (isJsonMode(opts)) {
|
|
1742
|
+
printJson(result);
|
|
1743
|
+
} else {
|
|
1744
|
+
const rendered = formatResult(result);
|
|
1745
|
+
if (rendered !== null) info(rendered);
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
function secondsOption(raw, fallback, flag) {
|
|
1749
|
+
if (raw === void 0) return fallback;
|
|
1750
|
+
const seconds = Number(raw);
|
|
1751
|
+
if (!Number.isFinite(seconds) || seconds <= 0) {
|
|
1752
|
+
error(`${flag} takes a number of seconds, not "${String(raw)}".`);
|
|
1753
|
+
process.exit(2);
|
|
1754
|
+
}
|
|
1755
|
+
return seconds;
|
|
1756
|
+
}
|
|
1757
|
+
async function listen(query, variables, requestOptions, seconds) {
|
|
1758
|
+
const controller = new AbortController();
|
|
1759
|
+
let expired = false;
|
|
1760
|
+
const timer = setTimeout(() => {
|
|
1761
|
+
expired = true;
|
|
1762
|
+
controller.abort();
|
|
1763
|
+
}, seconds * 1e3);
|
|
1764
|
+
const open = () => graphqlSubscribe(query, variables, { ...requestOptions, signal: controller.signal });
|
|
1765
|
+
const first = await open();
|
|
1766
|
+
async function* events() {
|
|
1767
|
+
let current = first;
|
|
1768
|
+
for (; ; ) {
|
|
1769
|
+
try {
|
|
1770
|
+
yield* current.events;
|
|
1771
|
+
return;
|
|
1772
|
+
} catch (err) {
|
|
1773
|
+
if (expired || !isDroppedStream(err)) throw err;
|
|
1774
|
+
current = await open();
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
return {
|
|
1779
|
+
events: events(),
|
|
1780
|
+
stop: () => {
|
|
1781
|
+
clearTimeout(timer);
|
|
1782
|
+
controller.abort();
|
|
1783
|
+
},
|
|
1784
|
+
timedOut: () => expired
|
|
1785
|
+
};
|
|
1786
|
+
}
|
|
1787
|
+
function isAbort(err) {
|
|
1788
|
+
return err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError");
|
|
1789
|
+
}
|
|
1790
|
+
function isDroppedStream(err) {
|
|
1791
|
+
if (!(err instanceof Error) || isAbort(err)) return false;
|
|
1792
|
+
const code = err.cause?.code;
|
|
1793
|
+
return err.message === "terminated" || code === "UND_ERR_SOCKET" || code === "ECONNRESET";
|
|
1794
|
+
}
|
|
1795
|
+
function buildCommand(schema, fieldName, kind, description, service, resultSubscription) {
|
|
1796
|
+
const rootType = rootTypeOf(schema, kind);
|
|
1402
1797
|
if (!rootType) throw new Error(`No ${kind} type in schema`);
|
|
1403
1798
|
const field = rootType.getFields()[fieldName];
|
|
1404
1799
|
if (!field) throw new Error(`Unknown ${kind} field: ${fieldName}`);
|
|
@@ -1414,10 +1809,12 @@ function buildCommand(schema, fieldName, kind, description, service) {
|
|
|
1414
1809
|
const requiresCompanyId = cliArgs.some((a) => a.name === "companyId" && a.required);
|
|
1415
1810
|
for (const a of cliArgs) {
|
|
1416
1811
|
const placeholder = enumListOf(a.type) ? "a,b|all|none..." : isStructuredInput(a.type) ? "json" : kebab(a.name);
|
|
1417
|
-
const flag = `--${
|
|
1812
|
+
const flag = `--${flagNameFor(fieldName, a.name)} <${placeholder}>`;
|
|
1418
1813
|
const isContext = a.name in CONTEXT_FIELDS;
|
|
1419
1814
|
if (isContext) {
|
|
1420
1815
|
cmd.option(flag, `${describeArg(a)} (from context if omitted)`);
|
|
1816
|
+
} else if (resultSubscription && a.name === "externalId") {
|
|
1817
|
+
cmd.option(flag, `${describeArg(a)} (generated if omitted)`);
|
|
1421
1818
|
} else if (a.required) {
|
|
1422
1819
|
cmd.requiredOption(flag, describeArg(a));
|
|
1423
1820
|
} else {
|
|
@@ -1425,6 +1822,20 @@ function buildCommand(schema, fieldName, kind, description, service) {
|
|
|
1425
1822
|
}
|
|
1426
1823
|
}
|
|
1427
1824
|
cmd.option("--depth <depth>", "Selection depth (default: 0)", parseInt).option("--fields <fields>", "Comma-separated fields to include").option("--exclude <fields>", "Comma-separated fields to exclude").option("--total-count", "Also count every match, not just this page (slow on a broad filter)");
|
|
1825
|
+
if (kind === "subscription") {
|
|
1826
|
+
cmd.option("--once", "Stop after the first event").option(
|
|
1827
|
+
"--timeout <seconds>",
|
|
1828
|
+
`Give up after this many seconds (default: ${DEFAULT_SUBSCRIPTION_TIMEOUT_SECONDS})`
|
|
1829
|
+
);
|
|
1830
|
+
}
|
|
1831
|
+
if (resultSubscription) {
|
|
1832
|
+
cmd.addOption(
|
|
1833
|
+
new Option(
|
|
1834
|
+
"--wait [seconds]",
|
|
1835
|
+
`Subscribe to \`${resultSubscription}\`, send this mutation, and print the result it delivers. --fields, --exclude and --depth then select the result`
|
|
1836
|
+
).preset(String(DEFAULT_WAIT_SECONDS))
|
|
1837
|
+
);
|
|
1838
|
+
}
|
|
1428
1839
|
cmd.action(async function() {
|
|
1429
1840
|
const opts = this.optsWithGlobals();
|
|
1430
1841
|
const ctx = getUserContext();
|
|
@@ -1437,13 +1848,19 @@ function buildCommand(schema, fieldName, kind, description, service) {
|
|
|
1437
1848
|
process.exit(2);
|
|
1438
1849
|
}
|
|
1439
1850
|
if (argumentCompanyId) opts.companyId = argumentCompanyId;
|
|
1851
|
+
const waiting = resultSubscription !== void 0 && opts.wait !== void 0;
|
|
1852
|
+
const generatedExternalId = resultSubscription !== void 0 && typeof opts.externalId !== "string";
|
|
1853
|
+
if (generatedExternalId) opts.externalId = `sl-${randomUUID()}`;
|
|
1854
|
+
if (waiting && opts.async === void 0 && cliArgs.some((a) => a.name === "async")) opts.async = "true";
|
|
1440
1855
|
const collectArgs = () => {
|
|
1441
1856
|
const out = {};
|
|
1442
1857
|
for (const a of cliArgs) {
|
|
1443
|
-
const
|
|
1858
|
+
const flagName = flagNameFor(fieldName, a.name);
|
|
1859
|
+
const given = opts[optionKey(flagName)];
|
|
1860
|
+
const raw = Array.isArray(given) ? given.join(",") : given;
|
|
1444
1861
|
if (raw != null) {
|
|
1445
1862
|
try {
|
|
1446
|
-
out[a.name] = coerceValue(raw, a.type,
|
|
1863
|
+
out[a.name] = coerceValue(raw, a.type, flagName);
|
|
1447
1864
|
} catch (coerceError) {
|
|
1448
1865
|
error(coerceError.message);
|
|
1449
1866
|
hint("Run the command with --help to see the expected shape of each argument.");
|
|
@@ -1454,42 +1871,79 @@ function buildCommand(schema, fieldName, kind, description, service) {
|
|
|
1454
1871
|
return out;
|
|
1455
1872
|
};
|
|
1456
1873
|
const variables = useInputWrapper ? { input: collectArgs() } : collectArgs();
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1874
|
+
const selection = {
|
|
1875
|
+
depth: opts.depth,
|
|
1876
|
+
fields: opts.fields?.split(","),
|
|
1877
|
+
exclude: opts.exclude?.split(","),
|
|
1878
|
+
totalCount: opts.totalCount === true
|
|
1879
|
+
};
|
|
1880
|
+
const build2 = (buildKind, buildField, buildVariables, select = true) => {
|
|
1881
|
+
try {
|
|
1882
|
+
return buildQuery(schema, buildKind, buildField, buildVariables, select ? selection : {});
|
|
1883
|
+
} catch (buildError) {
|
|
1884
|
+
if (!(buildError instanceof UnknownFieldError)) throw buildError;
|
|
1885
|
+
error(buildError.message);
|
|
1886
|
+
hint(`Did you mean: ${buildError.suggestions.join(", ")}?`);
|
|
1887
|
+
process.exit(2);
|
|
1888
|
+
}
|
|
1889
|
+
};
|
|
1890
|
+
const requestOptions = { endpoint: opts.endpoint, company: acting, companyId: actingId, subgraph: service };
|
|
1891
|
+
if (kind === "subscription") {
|
|
1892
|
+
const seconds = secondsOption(opts.timeout, DEFAULT_SUBSCRIPTION_TIMEOUT_SECONDS, "--timeout");
|
|
1893
|
+
const { query: query2, fieldName: fName2 } = build2("subscription", fieldName, variables);
|
|
1894
|
+
const stream = await listen(query2, variables, requestOptions, seconds);
|
|
1895
|
+
try {
|
|
1896
|
+
for await (const data2 of stream.events) {
|
|
1897
|
+
printResult(fieldName, data2[fName2], opts);
|
|
1898
|
+
if (opts.once) break;
|
|
1899
|
+
}
|
|
1900
|
+
} catch (err) {
|
|
1901
|
+
if (!isAbort(err) || !stream.timedOut()) throw err;
|
|
1902
|
+
warn(`No more events within ${seconds}s.`);
|
|
1903
|
+
process.exit(TIMED_OUT_EXIT_CODE);
|
|
1904
|
+
} finally {
|
|
1905
|
+
stream.stop();
|
|
1906
|
+
}
|
|
1907
|
+
return;
|
|
1470
1908
|
}
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
companyId: actingId,
|
|
1476
|
-
subgraph: service
|
|
1477
|
-
});
|
|
1478
|
-
const result = data[fName];
|
|
1479
|
-
if (result == null) {
|
|
1480
|
-
if (actingAsApplication()) {
|
|
1481
|
-
info(`${fieldName} answers for people, and you are acting as an application.`);
|
|
1482
|
-
hint("`sl whoami` reports what the token identifies; `sl use me` switches back.");
|
|
1483
|
-
} else {
|
|
1484
|
-
warn("No results returned.");
|
|
1485
|
-
hint("The query succeeded but the server returned null.");
|
|
1486
|
-
hint("Try different arguments or check that the resource exists.");
|
|
1909
|
+
if (waiting && resultSubscription) {
|
|
1910
|
+
const seconds = secondsOption(opts.wait, DEFAULT_WAIT_SECONDS, "--wait");
|
|
1911
|
+
if (!requestOptions.companyId && !actingAsApplication()) {
|
|
1912
|
+
requestOptions.companyId = await personalCompanyId();
|
|
1487
1913
|
}
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1914
|
+
const externalId = opts.externalId;
|
|
1915
|
+
const subscriptionVariables = { externalId };
|
|
1916
|
+
const { query: subscriptionQuery, fieldName: subscriptionField } = build2(
|
|
1917
|
+
"subscription",
|
|
1918
|
+
resultSubscription,
|
|
1919
|
+
subscriptionVariables
|
|
1920
|
+
);
|
|
1921
|
+
const stream = await listen(subscriptionQuery, subscriptionVariables, requestOptions, seconds);
|
|
1922
|
+
try {
|
|
1923
|
+
const { query: query2 } = build2(kind, fieldName, variables, false);
|
|
1924
|
+
await graphqlRaw(query2, variables, requestOptions);
|
|
1925
|
+
for await (const data2 of stream.events) {
|
|
1926
|
+
printResult(resultSubscription, data2[subscriptionField], opts);
|
|
1927
|
+
return;
|
|
1928
|
+
}
|
|
1929
|
+
warn(`${resultSubscription} closed without delivering a result.`);
|
|
1930
|
+
process.exit(1);
|
|
1931
|
+
} catch (err) {
|
|
1932
|
+
if (!isAbort(err) || !stream.timedOut()) throw err;
|
|
1933
|
+
warn(`No result within ${seconds}s. The request was accepted and may still complete.`);
|
|
1934
|
+
hint(`Wait longer with --wait <seconds>, or read the result later; its external id is ${externalId}.`);
|
|
1935
|
+
process.exit(TIMED_OUT_EXIT_CODE);
|
|
1936
|
+
} finally {
|
|
1937
|
+
stream.stop();
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
const { query, fieldName: fName } = build2(kind, fieldName, variables);
|
|
1941
|
+
const data = await graphqlRaw(query, variables, requestOptions);
|
|
1942
|
+
printResult(fieldName, data[fName], opts);
|
|
1943
|
+
if (generatedExternalId && resultSubscription) {
|
|
1944
|
+
hint(
|
|
1945
|
+
`Its result arrives on ${kebab(resultSubscription)} --external-id ${String(opts.externalId)}, or pass --wait.`
|
|
1946
|
+
);
|
|
1493
1947
|
}
|
|
1494
1948
|
});
|
|
1495
1949
|
return cmd;
|
|
@@ -1497,21 +1951,24 @@ function buildCommand(schema, fieldName, kind, description, service) {
|
|
|
1497
1951
|
function deriveServiceMap(schema, fieldServices) {
|
|
1498
1952
|
const map = /* @__PURE__ */ new Map();
|
|
1499
1953
|
function ensure(service) {
|
|
1500
|
-
if (!map.has(service)) map.set(service, { queries: [], mutations: [] });
|
|
1954
|
+
if (!map.has(service)) map.set(service, { queries: [], mutations: [], subscriptions: [] });
|
|
1501
1955
|
return map.get(service);
|
|
1502
1956
|
}
|
|
1503
1957
|
const rootTypes = [
|
|
1504
1958
|
{ kind: "queries", type: schema.getQueryType() },
|
|
1505
|
-
{ kind: "mutations", type: schema.getMutationType() }
|
|
1959
|
+
{ kind: "mutations", type: schema.getMutationType() },
|
|
1960
|
+
{ kind: "subscriptions", type: schema.getSubscriptionType() }
|
|
1506
1961
|
];
|
|
1507
1962
|
for (const { kind, type } of rootTypes) {
|
|
1508
1963
|
if (!type) continue;
|
|
1509
1964
|
const services = fieldServices.get(type.name);
|
|
1510
1965
|
if (!services) continue;
|
|
1511
|
-
|
|
1966
|
+
const fields = type.getFields();
|
|
1967
|
+
for (const [fieldName, field] of Object.entries(fields)) {
|
|
1512
1968
|
if (SKIP_FIELDS.has(fieldName) || fieldName.startsWith("__")) continue;
|
|
1969
|
+
if (supersededBy(field, fields)) continue;
|
|
1513
1970
|
const returnType = unwrap2(field.type);
|
|
1514
|
-
if (
|
|
1971
|
+
if (isInterfaceType(returnType) || isUnionType(returnType)) continue;
|
|
1515
1972
|
const service = services.get(fieldName);
|
|
1516
1973
|
if (!service) continue;
|
|
1517
1974
|
ensure(service)[kind].push({ fieldName, description: field.description ?? "" });
|
|
@@ -1520,27 +1977,31 @@ function deriveServiceMap(schema, fieldServices) {
|
|
|
1520
1977
|
for (const entry of map.values()) {
|
|
1521
1978
|
entry.queries.sort((a, b) => a.fieldName.localeCompare(b.fieldName));
|
|
1522
1979
|
entry.mutations.sort((a, b) => a.fieldName.localeCompare(b.fieldName));
|
|
1980
|
+
entry.subscriptions.sort((a, b) => a.fieldName.localeCompare(b.fieldName));
|
|
1523
1981
|
}
|
|
1524
1982
|
return map;
|
|
1525
1983
|
}
|
|
1526
1984
|
function buildOperationCommands(schema, fieldServices) {
|
|
1527
1985
|
const serviceMap = deriveServiceMap(schema, fieldServices);
|
|
1986
|
+
const pairs = resultSubscriptions(schema);
|
|
1528
1987
|
const operations = [];
|
|
1529
1988
|
const nameCounts = /* @__PURE__ */ new Map();
|
|
1530
1989
|
for (const entry of serviceMap.values()) {
|
|
1531
|
-
for (const op of [...entry.queries, ...entry.mutations]) {
|
|
1990
|
+
for (const op of [...entry.queries, ...entry.mutations, ...entry.subscriptions]) {
|
|
1532
1991
|
nameCounts.set(op.fieldName, (nameCounts.get(op.fieldName) ?? 0) + 1);
|
|
1533
1992
|
}
|
|
1534
1993
|
}
|
|
1535
1994
|
for (const [service, entry] of serviceMap) {
|
|
1536
1995
|
const kinds = [
|
|
1537
1996
|
{ kind: "query", ops: entry.queries },
|
|
1538
|
-
{ kind: "mutation", ops: entry.mutations }
|
|
1997
|
+
{ kind: "mutation", ops: entry.mutations },
|
|
1998
|
+
{ kind: "subscription", ops: entry.subscriptions }
|
|
1539
1999
|
];
|
|
1540
2000
|
for (const { kind, ops } of kinds) {
|
|
1541
2001
|
for (const op of ops) {
|
|
1542
2002
|
try {
|
|
1543
|
-
const
|
|
2003
|
+
const paired = kind === "mutation" ? pairs.get(op.fieldName) : void 0;
|
|
2004
|
+
const command = buildCommand(schema, op.fieldName, kind, op.description, service, paired);
|
|
1544
2005
|
if ((nameCounts.get(op.fieldName) ?? 0) > 1) {
|
|
1545
2006
|
command.name(`${kebab(op.fieldName)}-${kind}`);
|
|
1546
2007
|
}
|
|
@@ -1559,11 +2020,16 @@ function formatOperationList(operations, search) {
|
|
|
1559
2020
|
return search ? `No operation matching "${search}".` : "No operations available. The endpoint is not a composed supergraph, so no subgraph mapping is exposed.";
|
|
1560
2021
|
}
|
|
1561
2022
|
const lines = [];
|
|
1562
|
-
|
|
2023
|
+
const headings = {
|
|
2024
|
+
query: "Queries",
|
|
2025
|
+
mutation: "Mutations",
|
|
2026
|
+
subscription: "Subscriptions"
|
|
2027
|
+
};
|
|
2028
|
+
for (const kind of ["query", "mutation", "subscription"]) {
|
|
1563
2029
|
const group = matching.filter((op) => op.kind === kind);
|
|
1564
2030
|
if (group.length === 0) continue;
|
|
1565
2031
|
const width = Math.max(...group.map((op) => op.command.name().length));
|
|
1566
|
-
lines.push(`${kind
|
|
2032
|
+
lines.push(`${headings[kind]}:`);
|
|
1567
2033
|
for (const op of group) {
|
|
1568
2034
|
lines.push(` ${op.command.name().padEnd(width)} ${op.service}`);
|
|
1569
2035
|
}
|
|
@@ -1573,7 +2039,7 @@ function formatOperationList(operations, search) {
|
|
|
1573
2039
|
}
|
|
1574
2040
|
|
|
1575
2041
|
// src/commands/login.ts
|
|
1576
|
-
import { Command as Command3 } from "commander";
|
|
2042
|
+
import { Command as Command3, Option as Option2 } from "commander";
|
|
1577
2043
|
|
|
1578
2044
|
// src/graphql/operations/common.ts
|
|
1579
2045
|
var Me = gql(`
|
|
@@ -1601,18 +2067,28 @@ function openBrowser(url) {
|
|
|
1601
2067
|
}
|
|
1602
2068
|
|
|
1603
2069
|
// src/commands/login.ts
|
|
1604
|
-
var
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
"
|
|
1608
|
-
"
|
|
1609
|
-
"
|
|
1610
|
-
"
|
|
1611
|
-
"
|
|
1612
|
-
"
|
|
1613
|
-
"billing/offer:*"
|
|
2070
|
+
var SERVICES = ["atlas", "core", "signals", "billing", "outreach", "hermes"];
|
|
2071
|
+
var ADMIN_API_SCOPES = SERVICES.map((service) => `${service}/*:read`);
|
|
2072
|
+
var USER_API_SCOPES = [
|
|
2073
|
+
"atlas/organization:read",
|
|
2074
|
+
"atlas/reveal:read",
|
|
2075
|
+
"outreach/channel_account:read",
|
|
2076
|
+
"outreach/channel_account:write",
|
|
2077
|
+
"signals/watcher:read",
|
|
2078
|
+
"signals/watcher:write"
|
|
1614
2079
|
];
|
|
1615
|
-
var
|
|
2080
|
+
var ELEVATION_API_SCOPES = {
|
|
2081
|
+
sales: ["atlas/*:read", "billing/offer:*"],
|
|
2082
|
+
admin: ADMIN_API_SCOPES,
|
|
2083
|
+
superadmin: [...ADMIN_API_SCOPES, ...SERVICES.map((service) => `${service}/*:*`)]
|
|
2084
|
+
};
|
|
2085
|
+
var DEFAULT_ELEVATION = "admin";
|
|
2086
|
+
var DEFAULT_SCOPE = `openid profile email offline_access ${USER_API_SCOPES.join(" ")}`;
|
|
2087
|
+
function scopeForLogin(scope, scopeIsDefault, level) {
|
|
2088
|
+
if (!level) return scope;
|
|
2089
|
+
const requested = scopeIsDefault ? `openid profile email ${[...USER_API_SCOPES, ...ELEVATION_API_SCOPES[level]].join(" ")}` : scope;
|
|
2090
|
+
return requested.split(" ").filter((name) => name && name !== "offline_access").join(" ");
|
|
2091
|
+
}
|
|
1616
2092
|
function sleep(ms) {
|
|
1617
2093
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1618
2094
|
}
|
|
@@ -1635,11 +2111,30 @@ function reportScopeGrant(requestedScope, accessToken) {
|
|
|
1635
2111
|
hint("tenant you logged into, not a CLI setting. Ask an administrator, then re-run `sl login`.");
|
|
1636
2112
|
}
|
|
1637
2113
|
var loginCommand = new Command3("login").summary("Log in to your Sortlist account").description(
|
|
1638
|
-
|
|
1639
|
-
|
|
2114
|
+
`Log in to your Sortlist account
|
|
2115
|
+
|
|
2116
|
+
Opens a browser to complete authentication, then saves your
|
|
2117
|
+
credentials locally. If you belong to multiple companies, you'll
|
|
2118
|
+
be prompted to pick one.
|
|
2119
|
+
|
|
2120
|
+
Examples:
|
|
2121
|
+
sl login Log in with the user scopes, no staff scope
|
|
2122
|
+
sl login --no-browser Print the login URL instead of opening it
|
|
2123
|
+
sl login --elevate=sales Sales scopes, for a limited time
|
|
2124
|
+
sl login --elevate Admin (read) scopes, for a limited time
|
|
2125
|
+
sl login --elevate=superadmin Superadmin (write) scopes, for a limited time
|
|
2126
|
+
|
|
2127
|
+
An elevated token lasts at most ${ELEVATION_MAX_SECONDS / 60} minutes, is never refreshed, and sits
|
|
2128
|
+
beside your session: once it expires, or after \`sl logout --elevated\`,
|
|
2129
|
+
commands fall back to the plain login.`
|
|
2130
|
+
).option("--scope <scope>", "OAuth scope", DEFAULT_SCOPE).option("--no-browser", "Print the login URL instead of opening a browser").addOption(
|
|
2131
|
+
new Option2("--elevate [level]", "Get a short-lived token with staff scopes").choices(Object.keys(ELEVATION_API_SCOPES)).preset(DEFAULT_ELEVATION)
|
|
2132
|
+
).action(async function() {
|
|
1640
2133
|
const opts = this.optsWithGlobals();
|
|
1641
|
-
|
|
1642
|
-
const
|
|
2134
|
+
const level = opts.elevate;
|
|
2135
|
+
const scope = scopeForLogin(opts.scope, this.getOptionValueSource("scope") === "default", level);
|
|
2136
|
+
info(level ? `Starting device authorization for ${level} elevation...` : "Starting device authorization...");
|
|
2137
|
+
const authData = await graphqlUnauthenticated(DeviceAuthorize, { input: { scope } }, opts.endpoint);
|
|
1643
2138
|
const device = authData.deviceAuthorize;
|
|
1644
2139
|
if (!device) {
|
|
1645
2140
|
error("Device authorization failed \u2014 the server returned an empty response.");
|
|
@@ -1698,6 +2193,14 @@ var loginCommand = new Command3("login").summary("Log in to your Sortlist accoun
|
|
|
1698
2193
|
hint("Run `sl login` to try again.");
|
|
1699
2194
|
process.exit(2);
|
|
1700
2195
|
}
|
|
2196
|
+
if (level && token.accessToken && token.expiresIn) {
|
|
2197
|
+
const elevated = saveElevatedCredentials(token.accessToken, token.expiresIn, level);
|
|
2198
|
+
success(`Elevated to ${level} until ${new Date(elevated.expiresAt * 1e3).toLocaleTimeString()}.`);
|
|
2199
|
+
reportScopeGrant(scope, token.accessToken);
|
|
2200
|
+
if (!loadCredentials()) hint("You have no regular session: once this expires, run `sl login`.");
|
|
2201
|
+
hint("Run `sl logout --elevated` to drop it sooner.");
|
|
2202
|
+
return;
|
|
2203
|
+
}
|
|
1701
2204
|
if (token.accessToken && token.refreshToken && token.idToken && token.expiresIn) {
|
|
1702
2205
|
saveCredentials({
|
|
1703
2206
|
accessToken: token.accessToken,
|
|
@@ -1705,8 +2208,9 @@ var loginCommand = new Command3("login").summary("Log in to your Sortlist accoun
|
|
|
1705
2208
|
idToken: token.idToken,
|
|
1706
2209
|
expiresAt: Math.floor(Date.now() / 1e3) + token.expiresIn
|
|
1707
2210
|
});
|
|
2211
|
+
clearElevatedCredentials();
|
|
1708
2212
|
success("Logged in successfully.");
|
|
1709
|
-
reportScopeGrant(
|
|
2213
|
+
reportScopeGrant(scope, token.accessToken);
|
|
1710
2214
|
await setupUserContext(opts.endpoint);
|
|
1711
2215
|
return;
|
|
1712
2216
|
}
|
|
@@ -1719,10 +2223,16 @@ var loginCommand = new Command3("login").summary("Log in to your Sortlist accoun
|
|
|
1719
2223
|
// src/commands/logout.ts
|
|
1720
2224
|
import { Command as Command4 } from "commander";
|
|
1721
2225
|
var logoutCommand = new Command4("logout").summary("Log out and remove stored credentials").description(
|
|
1722
|
-
"Log out and remove stored credentials\n\nDeletes the saved tokens from ~/.sortlist/credentials.json and\nopens the Auth0 logout URL in your browser so the next `sl login`\ndoesn't silently reuse the previous account.\n\nExamples:\n sl logout Clear credentials and log out of Auth0\n sl logout --no-browser Only clear local credentials"
|
|
1723
|
-
).option("--no-browser", "Skip opening the Auth0 logout URL in a browser").action(async function() {
|
|
2226
|
+
"Log out and remove stored credentials\n\nDeletes the saved tokens from ~/.sortlist/credentials.json and\nopens the Auth0 logout URL in your browser so the next `sl login`\ndoesn't silently reuse the previous account.\n\nExamples:\n sl logout Clear credentials and log out of Auth0\n sl logout --no-browser Only clear local credentials\n sl logout --elevated Drop the elevated token, keep your session"
|
|
2227
|
+
).option("--no-browser", "Skip opening the Auth0 logout URL in a browser").option("--elevated", "Only drop the token from `sl login --elevate`").action(async function() {
|
|
1724
2228
|
const opts = this.optsWithGlobals();
|
|
2229
|
+
if (opts.elevated) {
|
|
2230
|
+
if (clearElevatedCredentials()) success("Elevation dropped \u2014 back to your regular session.");
|
|
2231
|
+
else info("No elevated token to drop.");
|
|
2232
|
+
return;
|
|
2233
|
+
}
|
|
1725
2234
|
clearCredentials();
|
|
2235
|
+
clearElevatedCredentials();
|
|
1726
2236
|
clearIdentity();
|
|
1727
2237
|
const hadSession = clearApplicationSession();
|
|
1728
2238
|
success("Logged out \u2014 credentials removed.");
|
|
@@ -1767,6 +2277,11 @@ Examples:
|
|
|
1767
2277
|
}
|
|
1768
2278
|
return;
|
|
1769
2279
|
}
|
|
2280
|
+
const elevated = loadElevatedCredentials();
|
|
2281
|
+
if (elevated) {
|
|
2282
|
+
process.stdout.write(elevated.accessToken);
|
|
2283
|
+
return;
|
|
2284
|
+
}
|
|
1770
2285
|
const creds = ensureAuthenticated();
|
|
1771
2286
|
if (isExpired(creds)) {
|
|
1772
2287
|
error("Your access token has expired.");
|
|
@@ -1854,6 +2369,13 @@ function sessionName() {
|
|
|
1854
2369
|
|
|
1855
2370
|
// src/commands/whoami.ts
|
|
1856
2371
|
import { Command as Command7 } from "commander";
|
|
2372
|
+
function apiScopes(accessToken) {
|
|
2373
|
+
return accessToken ? grantedScopes(accessToken).filter((scope) => scope.includes("/")) : [];
|
|
2374
|
+
}
|
|
2375
|
+
function currentElevation() {
|
|
2376
|
+
const elevated = loadElevatedCredentials();
|
|
2377
|
+
return elevated ? { level: elevated.level, until: new Date(elevated.expiresAt * 1e3).toISOString() } : null;
|
|
2378
|
+
}
|
|
1857
2379
|
var whoamiCommand = new Command7("whoami").summary("Show what the CLI is currently acting as").description(
|
|
1858
2380
|
"Show what the CLI is currently acting as\n\nReports a person or an application, matching what every command\nauthenticates as. Use --json for machine-readable output.\n\nExamples:\n sl whoami Show the current identity\n sl whoami --json Output the full object as JSON"
|
|
1859
2381
|
).action(async function() {
|
|
@@ -1935,18 +2457,24 @@ var whoamiCommand = new Command7("whoami").summary("Show what the CLI is current
|
|
|
1935
2457
|
hint("Retry in a moment; if it persists, re-run `sl login` or report it.");
|
|
1936
2458
|
process.exit(1);
|
|
1937
2459
|
}
|
|
2460
|
+
const elevation = currentElevation();
|
|
2461
|
+
const scopes = apiScopes(storedUserAccessToken());
|
|
1938
2462
|
if (isJsonMode(opts)) {
|
|
1939
|
-
printJson({ kind: "person", ...user });
|
|
2463
|
+
printJson({ kind: "person", ...user, elevation, scopes });
|
|
1940
2464
|
return;
|
|
1941
2465
|
}
|
|
1942
|
-
info(
|
|
2466
|
+
info(elevation ? `Acting as yourself, elevated to ${elevation.level}.
|
|
2467
|
+
` : "Acting as yourself.\n");
|
|
1943
2468
|
info(
|
|
1944
2469
|
formatResult({
|
|
1945
2470
|
name: [user.firstName, user.lastName].filter(Boolean).join(" ") || null,
|
|
1946
2471
|
email: user.email,
|
|
1947
|
-
id: user.id
|
|
2472
|
+
id: user.id,
|
|
2473
|
+
...elevation && { "elevated until": elevation.until },
|
|
2474
|
+
scopes: scopes.length > 0 ? scopes.join(" ") : "none"
|
|
1948
2475
|
}) ?? ""
|
|
1949
2476
|
);
|
|
2477
|
+
if (elevation) hint("Run `sl logout --elevated` to drop the elevation now.");
|
|
1950
2478
|
});
|
|
1951
2479
|
|
|
1952
2480
|
// src/graphql/introspection.ts
|
|
@@ -2031,13 +2559,15 @@ function parseIntrospection(raw) {
|
|
|
2031
2559
|
}
|
|
2032
2560
|
return { fieldServices, services };
|
|
2033
2561
|
}
|
|
2034
|
-
function currentAccessToken() {
|
|
2035
|
-
|
|
2562
|
+
async function currentAccessToken() {
|
|
2563
|
+
const machine = clientCredentials();
|
|
2564
|
+
if (machine) return fetchClientCredentialsToken(machine);
|
|
2565
|
+
return loadApplicationSession()?.accessToken ?? storedUserAccessToken();
|
|
2036
2566
|
}
|
|
2037
2567
|
async function getIntrospectedSchema(endpointOverride2) {
|
|
2038
2568
|
if (cached2) return cached2;
|
|
2039
2569
|
const endpoint = getEndpoint(endpointOverride2);
|
|
2040
|
-
const token = currentAccessToken();
|
|
2570
|
+
const token = await currentAccessToken();
|
|
2041
2571
|
const fromCache = readCache(endpoint, token);
|
|
2042
2572
|
if (fromCache) {
|
|
2043
2573
|
const usable = build(fromCache.introspection, fromCache.raw);
|
|
@@ -2076,7 +2606,7 @@ async function refreshSchema(endpointOverride2) {
|
|
|
2076
2606
|
cached2 = null;
|
|
2077
2607
|
discardCache();
|
|
2078
2608
|
const endpoint = getEndpoint(endpointOverride2);
|
|
2079
|
-
const token = currentAccessToken();
|
|
2609
|
+
const token = await currentAccessToken();
|
|
2080
2610
|
const { introspection, raw } = await fetchIntrospection(endpoint, token);
|
|
2081
2611
|
const built = build(introspection, raw);
|
|
2082
2612
|
if (!built) {
|