@sortlist/cli 0.38.0 → 0.40.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 +69 -19
- package/dist/index.js +365 -88
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -173,7 +173,7 @@ function getEndpoint(override) {
|
|
|
173
173
|
}
|
|
174
174
|
function getUserContext() {
|
|
175
175
|
const config = loadConfig();
|
|
176
|
-
return {
|
|
176
|
+
return { company: config.company };
|
|
177
177
|
}
|
|
178
178
|
|
|
179
179
|
// src/lib/env.ts
|
|
@@ -228,7 +228,7 @@ var ENVIRONMENTS = [
|
|
|
228
228
|
}
|
|
229
229
|
];
|
|
230
230
|
var configCommand = new Command("config").summary("View or update CLI configuration").description(
|
|
231
|
-
"View or update CLI configuration\n\nManage your company context and credentials.\n\nExamples:\n sl config show See current endpoint and company\n" + (isLocalDev ? " sl config set endpoint <url> Point to a custom endpoint\n" : "") + " sl config reset Clear all config and credentials"
|
|
231
|
+
"View or update CLI configuration\n\nManage your company context and credentials.\n\nExamples:\n sl config show See current endpoint and company\n sl config set company <slug|id> Act for that company on every command\n" + (isLocalDev ? " sl config set endpoint <url> Point to a custom endpoint\n" : "") + " sl config reset Clear all config and credentials"
|
|
232
232
|
);
|
|
233
233
|
configCommand.command("show").description("Show current configuration").action(function() {
|
|
234
234
|
const opts = this.optsWithGlobals();
|
|
@@ -238,10 +238,10 @@ configCommand.command("show").description("Show current configuration").action(f
|
|
|
238
238
|
} else {
|
|
239
239
|
info(`Endpoint: ${config.endpoint}`);
|
|
240
240
|
if (config.tokenEndpoint) info(`Token endpoint: ${config.tokenEndpoint}`);
|
|
241
|
-
if (config.
|
|
241
|
+
if (config.company) info(`Company: ${config.company}`);
|
|
242
242
|
}
|
|
243
243
|
});
|
|
244
|
-
var SETTABLE_KEYS = [...isLocalDev ? ["endpoint"] : [], "
|
|
244
|
+
var SETTABLE_KEYS = [...isLocalDev ? ["endpoint"] : [], "company", "tokenEndpoint"];
|
|
245
245
|
configCommand.command("set <key> <value>").description(`Set a config value (${SETTABLE_KEYS.join(", ")})`).action((key, value) => {
|
|
246
246
|
if (!SETTABLE_KEYS.includes(key)) {
|
|
247
247
|
error(`Unknown config key: "${key}".`);
|
|
@@ -290,6 +290,40 @@ import {
|
|
|
290
290
|
// src/graphql/client.ts
|
|
291
291
|
import { print } from "graphql";
|
|
292
292
|
|
|
293
|
+
// src/lib/api-headers.ts
|
|
294
|
+
var API_CLIENT = "sl-cli";
|
|
295
|
+
function userAgent() {
|
|
296
|
+
return `${API_CLIENT}/${pkg.version} (node/${process.versions.node})`;
|
|
297
|
+
}
|
|
298
|
+
function baseRequestHeaders() {
|
|
299
|
+
return {
|
|
300
|
+
"Content-Type": "application/json",
|
|
301
|
+
"X-API-Client": API_CLIENT,
|
|
302
|
+
"User-Agent": userAgent()
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// src/lib/token-claims.ts
|
|
307
|
+
function tokenClaims(accessToken) {
|
|
308
|
+
try {
|
|
309
|
+
const payload = accessToken.split(".")[1];
|
|
310
|
+
if (!payload) return null;
|
|
311
|
+
return JSON.parse(Buffer.from(payload, "base64url").toString("utf-8"));
|
|
312
|
+
} catch {
|
|
313
|
+
return null;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
function grantedScopes(accessToken) {
|
|
317
|
+
const scope = tokenClaims(accessToken)?.scope;
|
|
318
|
+
return typeof scope === "string" ? scope.split(" ").filter(Boolean) : [];
|
|
319
|
+
}
|
|
320
|
+
function servicesWithoutScope(requestedScope, accessToken) {
|
|
321
|
+
const serviceOf2 = (scope) => scope.includes("/") ? scope.split("/")[0] : null;
|
|
322
|
+
const granted = new Set(grantedScopes(accessToken).map(serviceOf2).filter(Boolean));
|
|
323
|
+
const requested = new Set(requestedScope.split(" ").map(serviceOf2).filter(Boolean));
|
|
324
|
+
return [...requested].filter((service) => !granted.has(service)).sort();
|
|
325
|
+
}
|
|
326
|
+
|
|
293
327
|
// src/lib/client-credentials.ts
|
|
294
328
|
var cached = null;
|
|
295
329
|
function clientCredentials() {
|
|
@@ -301,15 +335,14 @@ function clientCredentials() {
|
|
|
301
335
|
var CLAIM_NAMESPACE = "https://sortlist.com/";
|
|
302
336
|
function applicationIdentity(accessToken) {
|
|
303
337
|
try {
|
|
304
|
-
const
|
|
305
|
-
if (!
|
|
306
|
-
const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf-8"));
|
|
338
|
+
const claims = tokenClaims(accessToken);
|
|
339
|
+
if (!claims) return null;
|
|
307
340
|
return {
|
|
308
|
-
applicationId: claims[`${CLAIM_NAMESPACE}application_id`],
|
|
309
|
-
credentialId: claims[`${CLAIM_NAMESPACE}credential_id`],
|
|
310
|
-
companyId: claims[`${CLAIM_NAMESPACE}company_id`],
|
|
311
|
-
sub: claims.sub,
|
|
312
|
-
expiresAt: new Date(claims.exp * 1e3)
|
|
341
|
+
applicationId: String(claims[`${CLAIM_NAMESPACE}application_id`]),
|
|
342
|
+
credentialId: String(claims[`${CLAIM_NAMESPACE}credential_id`]),
|
|
343
|
+
companyId: String(claims[`${CLAIM_NAMESPACE}company_id`]),
|
|
344
|
+
sub: String(claims.sub),
|
|
345
|
+
expiresAt: new Date(Number(claims.exp) * 1e3)
|
|
313
346
|
};
|
|
314
347
|
} catch {
|
|
315
348
|
return null;
|
|
@@ -347,6 +380,36 @@ async function fetchClientCredentialsToken(credentials) {
|
|
|
347
380
|
return cached.accessToken;
|
|
348
381
|
}
|
|
349
382
|
|
|
383
|
+
// src/lib/company.ts
|
|
384
|
+
function isCompanyId(value) {
|
|
385
|
+
try {
|
|
386
|
+
return Buffer.from(value, "base64url").toString("utf8").startsWith("Company/");
|
|
387
|
+
} catch {
|
|
388
|
+
return false;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
var COMPANY_BY_SLUG = `query CompanyBySlug($slug: String!) { company(slug: $slug) { id } }`;
|
|
392
|
+
var resolved = /* @__PURE__ */ new Map();
|
|
393
|
+
async function lookupCompanyId(slug) {
|
|
394
|
+
const data = await graphqlRaw(COMPANY_BY_SLUG, { slug }, { withoutCompany: true });
|
|
395
|
+
const id = data.company?.id;
|
|
396
|
+
if (typeof id === "string") return id;
|
|
397
|
+
error(`No company with slug "${slug}" among yours.`);
|
|
398
|
+
hint("`sl companies` lists the companies you belong to, with their slugs and ids.");
|
|
399
|
+
process.exit(2);
|
|
400
|
+
}
|
|
401
|
+
async function resolveCompanyId(opts) {
|
|
402
|
+
const value = opts.company ?? opts.ctx?.company;
|
|
403
|
+
if (!value) return void 0;
|
|
404
|
+
if (isCompanyId(value)) return value;
|
|
405
|
+
let pending = resolved.get(value);
|
|
406
|
+
if (!pending) {
|
|
407
|
+
pending = lookupCompanyId(value);
|
|
408
|
+
resolved.set(value, pending);
|
|
409
|
+
}
|
|
410
|
+
return pending;
|
|
411
|
+
}
|
|
412
|
+
|
|
350
413
|
// src/lib/sentry.ts
|
|
351
414
|
import * as Sentry from "@sentry/node";
|
|
352
415
|
var SENTRY_DSN = "https://306d2e4389b8baa0bf14e587c2ceff04@o27611.ingest.us.sentry.io/4511229468409856";
|
|
@@ -487,7 +550,7 @@ var GraphQLRequestError = class extends Error {
|
|
|
487
550
|
async function refreshAccessToken(creds, endpoint) {
|
|
488
551
|
const res = await fetch(endpoint, {
|
|
489
552
|
method: "POST",
|
|
490
|
-
headers:
|
|
553
|
+
headers: baseRequestHeaders(),
|
|
491
554
|
body: JSON.stringify({
|
|
492
555
|
query: print(RefreshToken),
|
|
493
556
|
variables: { input: { refreshToken: creds.refreshToken } }
|
|
@@ -582,6 +645,16 @@ function codeOf(errors) {
|
|
|
582
645
|
}
|
|
583
646
|
return null;
|
|
584
647
|
}
|
|
648
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
649
|
+
function subrequestStatus(errors) {
|
|
650
|
+
for (const { extensions } of errors) {
|
|
651
|
+
const http = extensions?.http;
|
|
652
|
+
if (typeof http === "object" && http !== null && typeof http.status === "number") {
|
|
653
|
+
return http.status;
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
return null;
|
|
657
|
+
}
|
|
585
658
|
function humanise(code) {
|
|
586
659
|
const words = code.toLowerCase().replaceAll("_", " ");
|
|
587
660
|
return words.charAt(0).toUpperCase() + words.slice(1) + ".";
|
|
@@ -647,6 +720,39 @@ function reportGraphqlErrors(errors, options, attempt) {
|
|
|
647
720
|
if (verbose) for (const gqlError of errors) info(`[debug] ${gqlError.message}`);
|
|
648
721
|
process.exit(4);
|
|
649
722
|
}
|
|
723
|
+
if (subrequestStatus(errors) === 401) {
|
|
724
|
+
const service = serviceOf(errors);
|
|
725
|
+
const where = service ?? "The subgraph";
|
|
726
|
+
error(`${where} did not accept your token.`);
|
|
727
|
+
if (actingAsApplication()) {
|
|
728
|
+
hint("The application token has expired or was signed with a key Hermes no longer publishes");
|
|
729
|
+
hint("(a local Hermes mints a fresh key on every restart). Run `sl use application <id>` again.");
|
|
730
|
+
} else {
|
|
731
|
+
hint("Run `sl login` again; `sl whoami` shows what the CLI is acting as.");
|
|
732
|
+
}
|
|
733
|
+
if (verbose) for (const gqlError of errors) info(`[debug] ${JSON.stringify(gqlError)}`);
|
|
734
|
+
process.exit(4);
|
|
735
|
+
}
|
|
736
|
+
if (subrequestStatus(errors) === 403) {
|
|
737
|
+
const service = serviceOf(errors);
|
|
738
|
+
const where = service ?? "The subgraph";
|
|
739
|
+
const company = options.company ?? getUserContext().company ?? options.companyId;
|
|
740
|
+
if (company && UUID.test(company)) {
|
|
741
|
+
error(`${where} refused ${company}: that is a raw uuid, not a company id.`);
|
|
742
|
+
hint("Pass its slug, or the id `sl companies` lists.");
|
|
743
|
+
} else if (company) {
|
|
744
|
+
error(`${where} refused to act for company ${company}.`);
|
|
745
|
+
hint("Your token does not list that company, or Hermes no longer knows you as one of its members.");
|
|
746
|
+
hint("`sl whoami` shows what the CLI is acting as;");
|
|
747
|
+
hint("pick one of your companies with --company or `sl config set company <slug|id>`.");
|
|
748
|
+
} else {
|
|
749
|
+
error(`${where} refused this request: it names no company to act for.`);
|
|
750
|
+
hint("Pick one of your companies with --company or `sl config set company <slug|id>`;");
|
|
751
|
+
hint("`sl companies` lists them. Join one first if the list is empty.");
|
|
752
|
+
}
|
|
753
|
+
if (verbose) for (const gqlError of errors) info(`[debug] ${JSON.stringify(gqlError)}`);
|
|
754
|
+
process.exit(4);
|
|
755
|
+
}
|
|
650
756
|
const code = codeOf(errors);
|
|
651
757
|
if (code !== null && code !== "DOWNSTREAM_SERVICE_ERROR") {
|
|
652
758
|
error(humanise(code));
|
|
@@ -688,13 +794,12 @@ async function executeQuery(query, variables, options = {}) {
|
|
|
688
794
|
level: "info"
|
|
689
795
|
});
|
|
690
796
|
if (attempt.verbose) logRequest(query, variables, attempt);
|
|
691
|
-
const headers =
|
|
692
|
-
"Content-Type": "application/json",
|
|
693
|
-
"X-API-Client": "sl-cli"
|
|
694
|
-
};
|
|
797
|
+
const headers = baseRequestHeaders();
|
|
695
798
|
if (authenticated) {
|
|
696
799
|
const { token, kind } = await resolveAccessToken(options, attempt);
|
|
697
800
|
headers["Authorization"] = `Bearer ${token}`;
|
|
801
|
+
const companyId = options.withoutCompany ? void 0 : options.companyId ?? await resolveCompanyId({ ctx: getUserContext() });
|
|
802
|
+
if (companyId) headers["X-Company-Id"] = companyId;
|
|
698
803
|
if (attempt.verbose) info(`[debug] ${kind} token: ...${token.slice(-8)}`);
|
|
699
804
|
}
|
|
700
805
|
let res;
|
|
@@ -755,6 +860,7 @@ import {
|
|
|
755
860
|
isScalarType,
|
|
756
861
|
isUnionType
|
|
757
862
|
} from "graphql";
|
|
863
|
+
var CLI_OPERATION_PREFIX = "SlCli_";
|
|
758
864
|
function unwrap(type) {
|
|
759
865
|
if (isNonNullType(type)) return unwrap(type.ofType);
|
|
760
866
|
if (isListType(type)) return unwrap(type.ofType);
|
|
@@ -774,19 +880,10 @@ function buildSelections(type, schema, depth, exclude, prefix, visited) {
|
|
|
774
880
|
const fields = type.getFields();
|
|
775
881
|
const lines = [];
|
|
776
882
|
const isPayload = PAYLOAD_TYPE_PATTERN.test(type.name);
|
|
777
|
-
if (type
|
|
883
|
+
if (isConnection(type)) {
|
|
778
884
|
const nodesType = unwrap(fields.nodes.type);
|
|
779
885
|
const nodeSelections = buildSelections(nodesType, schema, depth, exclude, `${prefix}nodes.`, new Set(visited));
|
|
780
|
-
|
|
781
|
-
lines.push(`nodes {`);
|
|
782
|
-
for (const sel of nodeSelections) lines.push(` ${sel}`);
|
|
783
|
-
lines.push(`}`);
|
|
784
|
-
lines.push(`pageInfo {`);
|
|
785
|
-
lines.push(` hasNextPage`);
|
|
786
|
-
lines.push(` endCursor`);
|
|
787
|
-
lines.push(`}`);
|
|
788
|
-
if (fields.totalCount) lines.push(`totalCount`);
|
|
789
|
-
return lines;
|
|
886
|
+
return connectionSelections(type, nodeSelections);
|
|
790
887
|
}
|
|
791
888
|
for (const [name, field] of Object.entries(fields)) {
|
|
792
889
|
if (name.startsWith("__")) continue;
|
|
@@ -801,7 +898,7 @@ function buildSelections(type, schema, depth, exclude, prefix, visited) {
|
|
|
801
898
|
} else if (isObjectType(namedType) && depth > 0) {
|
|
802
899
|
const subSelections = buildSelections(namedType, schema, depth - 1, exclude, `${fullPath}.`, new Set(visited));
|
|
803
900
|
if (subSelections.length > 0) {
|
|
804
|
-
lines.push(`${name} {`);
|
|
901
|
+
lines.push(`${fieldCall(name, field)} {`);
|
|
805
902
|
for (const sel of subSelections) lines.push(` ${sel}`);
|
|
806
903
|
lines.push(`}`);
|
|
807
904
|
}
|
|
@@ -809,6 +906,95 @@ function buildSelections(type, schema, depth, exclude, prefix, visited) {
|
|
|
809
906
|
}
|
|
810
907
|
return lines;
|
|
811
908
|
}
|
|
909
|
+
var NESTED_PAGE_SIZE = 10;
|
|
910
|
+
function fieldCall(name, field) {
|
|
911
|
+
const named = unwrap(field.type);
|
|
912
|
+
const pageable = isObjectType(named) && isConnection(named) && field.args.some((a) => a.name === "first");
|
|
913
|
+
return pageable ? `${name}(first: ${NESTED_PAGE_SIZE})` : name;
|
|
914
|
+
}
|
|
915
|
+
function isConnection(type) {
|
|
916
|
+
const fields = type.getFields();
|
|
917
|
+
return type.name.endsWith("Connection") && Boolean(fields.nodes) && Boolean(fields.pageInfo);
|
|
918
|
+
}
|
|
919
|
+
function selectableFields(type) {
|
|
920
|
+
return Object.values(type.getFields()).filter(
|
|
921
|
+
(field) => !field.name.startsWith("__") && !field.args.some((a) => isNonNullType(a.type) && a.defaultValue === void 0)
|
|
922
|
+
);
|
|
923
|
+
}
|
|
924
|
+
function edgeExtras(connection) {
|
|
925
|
+
const edgesField = connection.getFields().edges;
|
|
926
|
+
if (!edgesField) return null;
|
|
927
|
+
const edge = unwrap(edgesField.type);
|
|
928
|
+
if (!isObjectType(edge)) return null;
|
|
929
|
+
const lines = [];
|
|
930
|
+
for (const field of selectableFields(edge)) {
|
|
931
|
+
if (field.name === "node" || field.name === "cursor" || field.name === "id") continue;
|
|
932
|
+
const named = unwrap(field.type);
|
|
933
|
+
if (isLeaf(named)) {
|
|
934
|
+
lines.push(field.name);
|
|
935
|
+
} else if (isObjectType(named)) {
|
|
936
|
+
const leaves = selectableFields(named).filter((sub) => isLeaf(unwrap(sub.type))).map((sub) => sub.name);
|
|
937
|
+
if (leaves.length > 0) lines.push(`${field.name} { ${leaves.join(" ")} }`);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
return lines.length === 0 ? null : { edge, lines };
|
|
941
|
+
}
|
|
942
|
+
function connectionSelections(connection, nodeSelections) {
|
|
943
|
+
if (nodeSelections.length === 0) return [];
|
|
944
|
+
const lines = [];
|
|
945
|
+
const extras = edgeExtras(connection);
|
|
946
|
+
if (extras) {
|
|
947
|
+
lines.push("edges {");
|
|
948
|
+
lines.push(" node {");
|
|
949
|
+
for (const sel of nodeSelections) lines.push(` ${sel}`);
|
|
950
|
+
lines.push(" }");
|
|
951
|
+
for (const extra of extras.lines) lines.push(` ${extra}`);
|
|
952
|
+
lines.push("}");
|
|
953
|
+
} else {
|
|
954
|
+
lines.push("nodes {");
|
|
955
|
+
for (const sel of nodeSelections) lines.push(` ${sel}`);
|
|
956
|
+
lines.push("}");
|
|
957
|
+
}
|
|
958
|
+
lines.push("pageInfo {");
|
|
959
|
+
lines.push(" hasNextPage");
|
|
960
|
+
lines.push(" endCursor");
|
|
961
|
+
lines.push("}");
|
|
962
|
+
if (connection.getFields().totalCount) lines.push("totalCount");
|
|
963
|
+
for (const extra of connectionExtras(connection)) lines.push(extra);
|
|
964
|
+
return lines;
|
|
965
|
+
}
|
|
966
|
+
var CONNECTION_PLUMBING = /* @__PURE__ */ new Set(["edges", "nodes", "pageInfo", "totalCount", "approximateTotalCount"]);
|
|
967
|
+
function connectionExtras(connection) {
|
|
968
|
+
return selectableFields(connection).filter((field) => !CONNECTION_PLUMBING.has(field.name)).flatMap((field) => {
|
|
969
|
+
const named = unwrap(field.type);
|
|
970
|
+
if (isLeaf(named)) return [field.name];
|
|
971
|
+
if (!isObjectType(named)) return [];
|
|
972
|
+
const inner = selectableFields(named).flatMap((sub) => {
|
|
973
|
+
const subType = unwrap(sub.type);
|
|
974
|
+
if (isLeaf(subType)) return [sub.name];
|
|
975
|
+
if (!isObjectType(subType)) return [];
|
|
976
|
+
const leaves = selectableFields(subType).filter((leaf) => isLeaf(unwrap(leaf.type)));
|
|
977
|
+
return leaves.length === 0 ? [] : [`${sub.name} { ${leaves.map((leaf) => leaf.name).join(" ")} }`];
|
|
978
|
+
});
|
|
979
|
+
return inner.length === 0 ? [] : [`${field.name} { ${inner.join(" ")} }`];
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
var UnknownFieldError = class extends Error {
|
|
983
|
+
field;
|
|
984
|
+
suggestions;
|
|
985
|
+
constructor(field, type) {
|
|
986
|
+
const names = Object.keys(type.getFields()).filter((name) => !name.startsWith("__"));
|
|
987
|
+
const needle = field.toLowerCase();
|
|
988
|
+
const suggestions = names.filter((name) => {
|
|
989
|
+
const candidate = name.toLowerCase();
|
|
990
|
+
return candidate.includes(needle) || needle.includes(candidate);
|
|
991
|
+
});
|
|
992
|
+
super(`${type.name} has no field "${field}".`);
|
|
993
|
+
this.name = "UnknownFieldError";
|
|
994
|
+
this.field = field;
|
|
995
|
+
this.suggestions = suggestions.length > 0 ? suggestions : names;
|
|
996
|
+
}
|
|
997
|
+
};
|
|
812
998
|
function buildQuery(schema, kind, fieldName, variables, options = {}) {
|
|
813
999
|
const rootType = kind === "query" ? schema.getQueryType() : schema.getMutationType();
|
|
814
1000
|
if (!rootType) throw new Error(`No ${kind} type in schema`);
|
|
@@ -844,7 +1030,7 @@ ${body}
|
|
|
844
1030
|
}`;
|
|
845
1031
|
}
|
|
846
1032
|
}
|
|
847
|
-
const opName = ucfirst(fieldName)
|
|
1033
|
+
const opName = `${CLI_OPERATION_PREFIX}${ucfirst(fieldName)}`;
|
|
848
1034
|
const query = `${kind} ${opName}${varDefs} {
|
|
849
1035
|
${selectionBody}
|
|
850
1036
|
}`;
|
|
@@ -853,20 +1039,11 @@ ${selectionBody}
|
|
|
853
1039
|
function buildFieldsFromList(type, schema, fieldPaths) {
|
|
854
1040
|
if (!isObjectType(type)) return [];
|
|
855
1041
|
const fields = type.getFields();
|
|
856
|
-
if (type
|
|
1042
|
+
if (isConnection(type)) {
|
|
857
1043
|
const nodesType = unwrap(fields.nodes.type);
|
|
858
|
-
const
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
lines2.push("nodes {");
|
|
862
|
-
for (const sel of nodeSelections) lines2.push(` ${sel}`);
|
|
863
|
-
lines2.push("}");
|
|
864
|
-
lines2.push("pageInfo {");
|
|
865
|
-
lines2.push(" hasNextPage");
|
|
866
|
-
lines2.push(" endCursor");
|
|
867
|
-
lines2.push("}");
|
|
868
|
-
if (fields.totalCount) lines2.push("totalCount");
|
|
869
|
-
return lines2;
|
|
1044
|
+
const withId = isObjectType(nodesType) && nodesType.getFields().id && !fieldPaths.includes("id");
|
|
1045
|
+
const nodeSelections = buildFieldsFromList(nodesType, schema, withId ? ["id", ...fieldPaths] : fieldPaths);
|
|
1046
|
+
return connectionSelections(type, nodeSelections);
|
|
870
1047
|
}
|
|
871
1048
|
const lines = [];
|
|
872
1049
|
const grouped = /* @__PURE__ */ new Map();
|
|
@@ -877,14 +1054,14 @@ function buildFieldsFromList(type, schema, fieldPaths) {
|
|
|
877
1054
|
}
|
|
878
1055
|
for (const [name, subPaths] of grouped) {
|
|
879
1056
|
const field = fields[name];
|
|
880
|
-
if (!field)
|
|
1057
|
+
if (!field) throw new UnknownFieldError(name, type);
|
|
881
1058
|
const namedType = unwrap(field.type);
|
|
882
1059
|
if (isLeaf(namedType)) {
|
|
883
1060
|
lines.push(name);
|
|
884
1061
|
} else if (isObjectType(namedType) && subPaths.length > 0) {
|
|
885
1062
|
const subSelections = buildFieldsFromList(namedType, schema, subPaths);
|
|
886
1063
|
if (subSelections.length > 0) {
|
|
887
|
-
lines.push(`${name} {`);
|
|
1064
|
+
lines.push(`${fieldCall(name, field)} {`);
|
|
888
1065
|
for (const sel of subSelections) lines.push(` ${sel}`);
|
|
889
1066
|
lines.push(`}`);
|
|
890
1067
|
}
|
|
@@ -893,28 +1070,60 @@ function buildFieldsFromList(type, schema, fieldPaths) {
|
|
|
893
1070
|
return lines;
|
|
894
1071
|
}
|
|
895
1072
|
|
|
896
|
-
// src/lib/company.ts
|
|
897
|
-
function resolveCompanyId(opts) {
|
|
898
|
-
return opts.companyId || opts.ctx?.companyId;
|
|
899
|
-
}
|
|
900
|
-
|
|
901
1073
|
// src/lib/render.ts
|
|
902
1074
|
var INDENT = " ";
|
|
1075
|
+
var CONNECTION_PLUMBING2 = /* @__PURE__ */ new Set([
|
|
1076
|
+
"edges",
|
|
1077
|
+
"nodes",
|
|
1078
|
+
"pageInfo",
|
|
1079
|
+
"totalCount",
|
|
1080
|
+
"approximateTotalCount",
|
|
1081
|
+
"__typename"
|
|
1082
|
+
]);
|
|
903
1083
|
function isRecord(value) {
|
|
904
1084
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
905
1085
|
}
|
|
1086
|
+
function rowOf(edge) {
|
|
1087
|
+
if (!isRecord(edge) || !isRecord(edge.node)) return isRecord(edge) ? edge.node : edge;
|
|
1088
|
+
const { node, cursor: _cursor, __typename: _typename, ...extras } = edge;
|
|
1089
|
+
const said = Object.entries(extras).filter(
|
|
1090
|
+
([, value]) => value != null && !(Array.isArray(value) && value.length === 0)
|
|
1091
|
+
);
|
|
1092
|
+
return { ...node, ...Object.fromEntries(said) };
|
|
1093
|
+
}
|
|
906
1094
|
function asConnection(value) {
|
|
907
|
-
if (!isRecord(value)
|
|
908
|
-
return value;
|
|
1095
|
+
if (!isRecord(value)) return null;
|
|
1096
|
+
if (Array.isArray(value.nodes)) return value;
|
|
1097
|
+
if (Array.isArray(value.edges)) return { ...value, nodes: value.edges.map(rowOf) };
|
|
1098
|
+
return null;
|
|
909
1099
|
}
|
|
910
1100
|
function formatScalar(value) {
|
|
911
1101
|
if (value === null || value === void 0) return "\u2014";
|
|
912
1102
|
if (typeof value === "boolean") return value ? "yes" : "no";
|
|
913
1103
|
if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) {
|
|
914
|
-
return value.slice(0,
|
|
1104
|
+
return value.slice(0, 19).replace("T", " ");
|
|
915
1105
|
}
|
|
916
1106
|
return String(value);
|
|
917
1107
|
}
|
|
1108
|
+
function isFlatRecord(value) {
|
|
1109
|
+
return isRecord(value) && Object.values(value).every((v) => !isRecord(v) && !Array.isArray(v));
|
|
1110
|
+
}
|
|
1111
|
+
var isDeadline = (key) => /Until$/.test(key);
|
|
1112
|
+
function formatDeadline(value) {
|
|
1113
|
+
return typeof value === "string" && value !== "" ? `until ${formatScalar(value)}` : "\u2014";
|
|
1114
|
+
}
|
|
1115
|
+
function formatFlatRows(rows, indent) {
|
|
1116
|
+
const keys = Object.keys(rows[0]).filter((key) => key !== "__typename");
|
|
1117
|
+
const ordered = [...keys.filter((key) => !isDeadline(key)), ...keys.filter(isDeadline)];
|
|
1118
|
+
const cells = rows.map(
|
|
1119
|
+
(row) => ordered.map((key) => isDeadline(key) ? formatDeadline(row[key]) : formatScalar(row[key]))
|
|
1120
|
+
);
|
|
1121
|
+
const widths = ordered.map((_, column) => Math.max(...cells.map((row) => (row[column] ?? "").length)));
|
|
1122
|
+
return cells.map(
|
|
1123
|
+
(row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" ")
|
|
1124
|
+
).join(`
|
|
1125
|
+
${indent}`);
|
|
1126
|
+
}
|
|
918
1127
|
function summarise(key, value) {
|
|
919
1128
|
const connection = asConnection(value);
|
|
920
1129
|
if (connection) {
|
|
@@ -928,13 +1137,21 @@ function summarise(key, value) {
|
|
|
928
1137
|
}
|
|
929
1138
|
return null;
|
|
930
1139
|
}
|
|
931
|
-
function
|
|
932
|
-
|
|
1140
|
+
function titleOf(record) {
|
|
1141
|
+
return typeof record.id === "string" && record.id !== "" ? record.id : null;
|
|
1142
|
+
}
|
|
1143
|
+
function formatRecord(record, indent, titled = false) {
|
|
1144
|
+
const title = titled ? titleOf(record) : null;
|
|
1145
|
+
const isFlatRows = (value) => Array.isArray(value) && value.length > 0 && value.every(isFlatRecord);
|
|
1146
|
+
const entries = Object.entries(record).filter(([key]) => key !== "__typename" && (title === null || key !== "id")).sort(([, a], [, b]) => Number(Array.isArray(a)) - Number(Array.isArray(b)));
|
|
933
1147
|
const width = Math.max(0, ...entries.map(([key]) => key.length));
|
|
934
|
-
|
|
935
|
-
|
|
1148
|
+
const valueIndent = `${indent}${"".padEnd(width)} `;
|
|
1149
|
+
const body = entries.map(([key, value]) => {
|
|
1150
|
+
const rendered = isFlatRows(value) ? formatFlatRows(value, valueIndent) : summarise(key, value) ?? formatScalar(value);
|
|
936
1151
|
return `${indent}${key.padEnd(width)} ${rendered}`;
|
|
937
1152
|
}).join("\n");
|
|
1153
|
+
return title === null ? body : `${indent.slice(INDENT.length)}${title}
|
|
1154
|
+
${body}`;
|
|
938
1155
|
}
|
|
939
1156
|
function formatFooter(connection) {
|
|
940
1157
|
const shown = connection.nodes.length;
|
|
@@ -945,21 +1162,27 @@ function formatFooter(connection) {
|
|
|
945
1162
|
const counted = total === void 0 ? `${shown}` : `${shown} of ${total}`;
|
|
946
1163
|
return more ? `${counted} \u2014 more available, pass --after ${connection.pageInfo?.endCursor}` : counted;
|
|
947
1164
|
}
|
|
1165
|
+
function formatConnectionExtras(connection) {
|
|
1166
|
+
return Object.entries(connection).filter(([key, value]) => !CONNECTION_PLUMBING2.has(key) && value != null).map(
|
|
1167
|
+
([key, value]) => isRecord(value) ? `${key}
|
|
1168
|
+
${formatRecord(value, INDENT)}` : `${key} ${formatScalar(value)}`
|
|
1169
|
+
);
|
|
1170
|
+
}
|
|
948
1171
|
function formatResult(result) {
|
|
949
1172
|
const connection = asConnection(result);
|
|
950
1173
|
if (connection) {
|
|
951
1174
|
if (connection.nodes.length === 0) return "No results.";
|
|
952
1175
|
const blocks = connection.nodes.map(
|
|
953
|
-
(node) => isRecord(node) ? formatRecord(node, INDENT) : `${INDENT}${formatScalar(node)}`
|
|
1176
|
+
(node) => isRecord(node) ? formatRecord(node, INDENT, true) : `${INDENT}${formatScalar(node)}`
|
|
954
1177
|
);
|
|
955
|
-
const
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
1178
|
+
const tail = [formatFooter(connection), ...formatConnectionExtras(result)].filter(
|
|
1179
|
+
(part) => part !== null
|
|
1180
|
+
);
|
|
1181
|
+
return [blocks.join("\n\n"), ...tail].join("\n\n");
|
|
959
1182
|
}
|
|
960
1183
|
if (Array.isArray(result)) {
|
|
961
1184
|
if (result.length === 0) return "No results.";
|
|
962
|
-
return result.map((item) => isRecord(item) ? formatRecord(item, INDENT) : formatScalar(item)).join("\n\n");
|
|
1185
|
+
return result.map((item) => isRecord(item) ? formatRecord(item, INDENT, true) : formatScalar(item)).join("\n\n");
|
|
963
1186
|
}
|
|
964
1187
|
if (isRecord(result)) return formatRecord(result, "");
|
|
965
1188
|
return result === null || result === void 0 ? null : formatScalar(result);
|
|
@@ -1002,7 +1225,41 @@ function isStructuredInput(type) {
|
|
|
1002
1225
|
if (isListType2(type)) return true;
|
|
1003
1226
|
return isInputObjectType(type);
|
|
1004
1227
|
}
|
|
1228
|
+
function enumListOf(type) {
|
|
1229
|
+
const listless = isNonNullType2(type) ? type.ofType : type;
|
|
1230
|
+
if (!isListType2(listless)) return null;
|
|
1231
|
+
const inner = unwrap2(listless.ofType);
|
|
1232
|
+
return isEnumType2(inner) ? inner : null;
|
|
1233
|
+
}
|
|
1234
|
+
function commonPrefix(values) {
|
|
1235
|
+
if (values.length < 2) return "";
|
|
1236
|
+
let prefix = values[0];
|
|
1237
|
+
for (const value of values) while (!value.startsWith(prefix)) prefix = prefix.slice(0, -1);
|
|
1238
|
+
const cut = prefix.lastIndexOf("_");
|
|
1239
|
+
return cut === -1 ? "" : prefix.slice(0, cut + 1);
|
|
1240
|
+
}
|
|
1241
|
+
function coerceEnumList(raw, enumType, flagName) {
|
|
1242
|
+
const names = enumType.getValues().map((value) => value.name);
|
|
1243
|
+
if (raw.trim() === "all") return names;
|
|
1244
|
+
if (raw.trim() === "none") return [];
|
|
1245
|
+
const prefix = commonPrefix(names);
|
|
1246
|
+
return raw.split(",").filter((part) => part.trim() !== "").map((part) => {
|
|
1247
|
+
const wanted = part.trim().replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
|
|
1248
|
+
const match = names.find((name) => name === wanted || name === `${prefix}${wanted}`);
|
|
1249
|
+
if (match === void 0) {
|
|
1250
|
+
const short = names.map(
|
|
1251
|
+
(name) => name.slice(prefix.length).toLowerCase().replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())
|
|
1252
|
+
);
|
|
1253
|
+
throw new Error(
|
|
1254
|
+
`--${flagName} does not know "${part.trim()}". One or more of: ${short.join(", ")}, all, or none.`
|
|
1255
|
+
);
|
|
1256
|
+
}
|
|
1257
|
+
return match;
|
|
1258
|
+
});
|
|
1259
|
+
}
|
|
1005
1260
|
function coerceValue(raw, type, flagName) {
|
|
1261
|
+
const enumList = enumListOf(type);
|
|
1262
|
+
if (enumList && !raw.trim().startsWith("[")) return coerceEnumList(raw, enumList, flagName);
|
|
1006
1263
|
if (isStructuredInput(type)) {
|
|
1007
1264
|
try {
|
|
1008
1265
|
return JSON.parse(raw);
|
|
@@ -1106,7 +1363,10 @@ function describeArg(arg) {
|
|
|
1106
1363
|
const parts = [];
|
|
1107
1364
|
if (arg.description) parts.push(arg.description.replace(/\s+/g, " ").trim());
|
|
1108
1365
|
const typeSig = renderType(arg.type);
|
|
1109
|
-
|
|
1366
|
+
const enumList = enumListOf(arg.type);
|
|
1367
|
+
parts.push(
|
|
1368
|
+
enumList ? `${typeSig} (comma-separated, all, or none)` : isStructuredInput(arg.type) ? `${typeSig} (JSON)` : typeSig
|
|
1369
|
+
);
|
|
1110
1370
|
const named = unwrap2(arg.type);
|
|
1111
1371
|
const shape = describeStructuredType(named);
|
|
1112
1372
|
if (shape) parts.push(shape);
|
|
@@ -1131,7 +1391,7 @@ function buildCommand(schema, fieldName, kind, description, service) {
|
|
|
1131
1391
|
const cmd = new Command2(kebab(fieldName)).description(description);
|
|
1132
1392
|
const requiresCompanyId = cliArgs.some((a) => a.name === "companyId" && a.required);
|
|
1133
1393
|
for (const a of cliArgs) {
|
|
1134
|
-
const placeholder = isStructuredInput(a.type) ? "json" : kebab(a.name);
|
|
1394
|
+
const placeholder = enumListOf(a.type) ? "a,b|all|none..." : isStructuredInput(a.type) ? "json" : kebab(a.name);
|
|
1135
1395
|
const flag = `--${kebab(a.name)} <${placeholder}>`;
|
|
1136
1396
|
const isContext = a.name in CONTEXT_FIELDS;
|
|
1137
1397
|
if (isContext) {
|
|
@@ -1145,23 +1405,20 @@ function buildCommand(schema, fieldName, kind, description, service) {
|
|
|
1145
1405
|
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");
|
|
1146
1406
|
cmd.action(async function() {
|
|
1147
1407
|
const opts = this.optsWithGlobals();
|
|
1148
|
-
const
|
|
1149
|
-
const
|
|
1150
|
-
const
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
});
|
|
1154
|
-
if (requiresCompanyId && !resolvedCompanyId) {
|
|
1408
|
+
const ctx = getUserContext();
|
|
1409
|
+
const acting = typeof opts.company === "string" ? opts.company : void 0;
|
|
1410
|
+
const actingId = await resolveCompanyId({ company: acting, ctx });
|
|
1411
|
+
const argumentCompanyId = typeof opts.companyId === "string" ? await resolveCompanyId({ company: opts.companyId, ctx }) : actingId;
|
|
1412
|
+
if (requiresCompanyId && !argumentCompanyId) {
|
|
1155
1413
|
error("No company selected.");
|
|
1156
|
-
hint("Pass --company-id <id
|
|
1414
|
+
hint("Pass --company-id <slug|id>, or act for one with --company or `sl config set company <slug|id>`.");
|
|
1157
1415
|
process.exit(2);
|
|
1158
1416
|
}
|
|
1159
|
-
if (
|
|
1417
|
+
if (argumentCompanyId) opts.companyId = argumentCompanyId;
|
|
1160
1418
|
const collectArgs = () => {
|
|
1161
1419
|
const out = {};
|
|
1162
1420
|
for (const a of cliArgs) {
|
|
1163
|
-
const raw = opts[a.name];
|
|
1164
|
-
const ctxProp = CONTEXT_FIELDS[a.name];
|
|
1421
|
+
const raw = Array.isArray(opts[a.name]) ? opts[a.name].join(",") : opts[a.name];
|
|
1165
1422
|
if (raw != null) {
|
|
1166
1423
|
try {
|
|
1167
1424
|
out[a.name] = coerceValue(raw, a.type, kebab(a.name));
|
|
@@ -1170,19 +1427,31 @@ function buildCommand(schema, fieldName, kind, description, service) {
|
|
|
1170
1427
|
hint("Run the command with --help to see the expected shape of each argument.");
|
|
1171
1428
|
process.exit(2);
|
|
1172
1429
|
}
|
|
1173
|
-
} else if (ctxProp && ctx) {
|
|
1174
|
-
out[a.name] = ctx[ctxProp];
|
|
1175
1430
|
}
|
|
1176
1431
|
}
|
|
1177
1432
|
return out;
|
|
1178
1433
|
};
|
|
1179
1434
|
const variables = useInputWrapper ? { input: collectArgs() } : collectArgs();
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1435
|
+
let built;
|
|
1436
|
+
try {
|
|
1437
|
+
built = buildQuery(schema, kind, fieldName, variables, {
|
|
1438
|
+
depth: opts.depth,
|
|
1439
|
+
fields: opts.fields?.split(","),
|
|
1440
|
+
exclude: opts.exclude?.split(",")
|
|
1441
|
+
});
|
|
1442
|
+
} catch (buildError) {
|
|
1443
|
+
if (!(buildError instanceof UnknownFieldError)) throw buildError;
|
|
1444
|
+
error(buildError.message);
|
|
1445
|
+
hint(`Did you mean: ${buildError.suggestions.join(", ")}?`);
|
|
1446
|
+
process.exit(2);
|
|
1447
|
+
}
|
|
1448
|
+
const { query, fieldName: fName } = built;
|
|
1449
|
+
const data = await graphqlRaw(query, variables, {
|
|
1450
|
+
endpoint: opts.endpoint,
|
|
1451
|
+
company: acting,
|
|
1452
|
+
companyId: actingId,
|
|
1453
|
+
subgraph: service
|
|
1184
1454
|
});
|
|
1185
|
-
const data = await graphqlRaw(query, variables, { endpoint: opts.endpoint, subgraph: service });
|
|
1186
1455
|
const result = data[fName];
|
|
1187
1456
|
if (result == null) {
|
|
1188
1457
|
if (actingAsApplication()) {
|
|
@@ -1332,6 +1601,16 @@ async function setupUserContext(endpoint) {
|
|
|
1332
1601
|
info(` User: ${user.firstName} ${user.lastName} <${user.email}>`);
|
|
1333
1602
|
hint("Run `sl whoami` to verify.");
|
|
1334
1603
|
}
|
|
1604
|
+
function reportScopeGrant(requestedScope, accessToken) {
|
|
1605
|
+
const missing = servicesWithoutScope(requestedScope, accessToken);
|
|
1606
|
+
if (missing.length === 0) return;
|
|
1607
|
+
warn(`No scope granted for: ${missing.join(", ")}.`);
|
|
1608
|
+
info(" Their commands will not appear in `sl --help`, and their fields are");
|
|
1609
|
+
info(" filtered out of the schema this CLI builds itself from.");
|
|
1610
|
+
hint("Auth0 grants requested scopes by exact string match against your assigned");
|
|
1611
|
+
hint("permissions and drops the rest silently \u2014 this is a role assignment in the");
|
|
1612
|
+
hint("tenant you logged into, not a CLI setting. Ask an administrator, then re-run `sl login`.");
|
|
1613
|
+
}
|
|
1335
1614
|
var loginCommand = new Command3("login").summary("Log in to your Sortlist account").description(
|
|
1336
1615
|
"Log in to your Sortlist account\n\nOpens a browser to complete authentication, then saves your\ncredentials locally. If you belong to multiple companies, you'll\nbe prompted to pick one.\n\nExamples:\n sl login Log in with default settings\n sl login --no-browser Print the login URL instead of opening it"
|
|
1337
1616
|
).option("--scope <scope>", "OAuth scope", DEFAULT_SCOPE).option("--no-browser", "Print the login URL instead of opening a browser").action(async function() {
|
|
@@ -1404,6 +1683,7 @@ var loginCommand = new Command3("login").summary("Log in to your Sortlist accoun
|
|
|
1404
1683
|
expiresAt: Math.floor(Date.now() / 1e3) + token.expiresIn
|
|
1405
1684
|
});
|
|
1406
1685
|
success("Logged in successfully.");
|
|
1686
|
+
reportScopeGrant(opts.scope, token.accessToken);
|
|
1407
1687
|
await setupUserContext(opts.endpoint);
|
|
1408
1688
|
return;
|
|
1409
1689
|
}
|
|
@@ -1690,10 +1970,7 @@ function writeCache(endpoint, token, introspection, raw) {
|
|
|
1690
1970
|
}
|
|
1691
1971
|
}
|
|
1692
1972
|
async function fetchIntrospection(endpoint, token) {
|
|
1693
|
-
const headers =
|
|
1694
|
-
"Content-Type": "application/json",
|
|
1695
|
-
"X-API-Client": "sl-cli"
|
|
1696
|
-
};
|
|
1973
|
+
const headers = baseRequestHeaders();
|
|
1697
1974
|
if (token) headers["Authorization"] = `Bearer ${token}`;
|
|
1698
1975
|
const res = await fetch(endpoint, {
|
|
1699
1976
|
method: "POST",
|
|
@@ -1902,7 +2179,7 @@ Operation names are unique across the supergraph, so they are not namespaced:
|
|
|
1902
2179
|
var program = new Command8().name("sl").configureOutput({
|
|
1903
2180
|
writeOut: (str) => process.stdout.write(colorizeHelp(str)),
|
|
1904
2181
|
writeErr: (str) => process.stderr.write(colorizeHelp(str))
|
|
1905
|
-
}).description(BASE_DESCRIPTION).version(pkg.version).option("--endpoint <url>", "Override the federation endpoint URL").option("--json", "Output as JSON (auto-enabled when stdout is not a TTY)").option("--no-color", "Disable colored output");
|
|
2182
|
+
}).description(BASE_DESCRIPTION).version(pkg.version).option("--endpoint <url>", "Override the federation endpoint URL").option("--company <slug|id>", "Act for this company, by slug or id; must be one you belong to").option("--json", "Output as JSON (auto-enabled when stdout is not a TTY)").option("--no-color", "Disable colored output");
|
|
1906
2183
|
program.addCommand(loginCommand);
|
|
1907
2184
|
program.addCommand(logoutCommand);
|
|
1908
2185
|
program.addCommand(whoamiCommand);
|