@sortlist/cli 0.38.0 → 0.39.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 CHANGED
@@ -173,7 +173,7 @@ function getEndpoint(override) {
173
173
  }
174
174
  function getUserContext() {
175
175
  const config = loadConfig();
176
- return { companyId: config.companyId };
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.companyId) info(`Company ID: ${config.companyId}`);
241
+ if (config.company) info(`Company: ${config.company}`);
242
242
  }
243
243
  });
244
- var SETTABLE_KEYS = [...isLocalDev ? ["endpoint"] : [], "companyId", "tokenEndpoint"];
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,27 @@ import {
290
290
  // src/graphql/client.ts
291
291
  import { print } from "graphql";
292
292
 
293
+ // src/lib/token-claims.ts
294
+ function tokenClaims(accessToken) {
295
+ try {
296
+ const payload = accessToken.split(".")[1];
297
+ if (!payload) return null;
298
+ return JSON.parse(Buffer.from(payload, "base64url").toString("utf-8"));
299
+ } catch {
300
+ return null;
301
+ }
302
+ }
303
+ function grantedScopes(accessToken) {
304
+ const scope = tokenClaims(accessToken)?.scope;
305
+ return typeof scope === "string" ? scope.split(" ").filter(Boolean) : [];
306
+ }
307
+ function servicesWithoutScope(requestedScope, accessToken) {
308
+ const serviceOf2 = (scope) => scope.includes("/") ? scope.split("/")[0] : null;
309
+ const granted = new Set(grantedScopes(accessToken).map(serviceOf2).filter(Boolean));
310
+ const requested = new Set(requestedScope.split(" ").map(serviceOf2).filter(Boolean));
311
+ return [...requested].filter((service) => !granted.has(service)).sort();
312
+ }
313
+
293
314
  // src/lib/client-credentials.ts
294
315
  var cached = null;
295
316
  function clientCredentials() {
@@ -301,15 +322,14 @@ function clientCredentials() {
301
322
  var CLAIM_NAMESPACE = "https://sortlist.com/";
302
323
  function applicationIdentity(accessToken) {
303
324
  try {
304
- const payload = accessToken.split(".")[1];
305
- if (!payload) return null;
306
- const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf-8"));
325
+ const claims = tokenClaims(accessToken);
326
+ if (!claims) return null;
307
327
  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)
328
+ applicationId: String(claims[`${CLAIM_NAMESPACE}application_id`]),
329
+ credentialId: String(claims[`${CLAIM_NAMESPACE}credential_id`]),
330
+ companyId: String(claims[`${CLAIM_NAMESPACE}company_id`]),
331
+ sub: String(claims.sub),
332
+ expiresAt: new Date(Number(claims.exp) * 1e3)
313
333
  };
314
334
  } catch {
315
335
  return null;
@@ -347,6 +367,36 @@ async function fetchClientCredentialsToken(credentials) {
347
367
  return cached.accessToken;
348
368
  }
349
369
 
370
+ // src/lib/company.ts
371
+ function isCompanyId(value) {
372
+ try {
373
+ return Buffer.from(value, "base64url").toString("utf8").startsWith("Company/");
374
+ } catch {
375
+ return false;
376
+ }
377
+ }
378
+ var COMPANY_BY_SLUG = `query CompanyBySlug($slug: String!) { company(slug: $slug) { id } }`;
379
+ var resolved = /* @__PURE__ */ new Map();
380
+ async function lookupCompanyId(slug) {
381
+ const data = await graphqlRaw(COMPANY_BY_SLUG, { slug }, { withoutCompany: true });
382
+ const id = data.company?.id;
383
+ if (typeof id === "string") return id;
384
+ error(`No company with slug "${slug}" among yours.`);
385
+ hint("`sl companies` lists the companies you belong to, with their slugs and ids.");
386
+ process.exit(2);
387
+ }
388
+ async function resolveCompanyId(opts) {
389
+ const value = opts.company ?? opts.ctx?.company;
390
+ if (!value) return void 0;
391
+ if (isCompanyId(value)) return value;
392
+ let pending = resolved.get(value);
393
+ if (!pending) {
394
+ pending = lookupCompanyId(value);
395
+ resolved.set(value, pending);
396
+ }
397
+ return pending;
398
+ }
399
+
350
400
  // src/lib/sentry.ts
351
401
  import * as Sentry from "@sentry/node";
352
402
  var SENTRY_DSN = "https://306d2e4389b8baa0bf14e587c2ceff04@o27611.ingest.us.sentry.io/4511229468409856";
@@ -582,6 +632,16 @@ function codeOf(errors) {
582
632
  }
583
633
  return null;
584
634
  }
635
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
636
+ function subrequestStatus(errors) {
637
+ for (const { extensions } of errors) {
638
+ const http = extensions?.http;
639
+ if (typeof http === "object" && http !== null && typeof http.status === "number") {
640
+ return http.status;
641
+ }
642
+ }
643
+ return null;
644
+ }
585
645
  function humanise(code) {
586
646
  const words = code.toLowerCase().replaceAll("_", " ");
587
647
  return words.charAt(0).toUpperCase() + words.slice(1) + ".";
@@ -647,6 +707,39 @@ function reportGraphqlErrors(errors, options, attempt) {
647
707
  if (verbose) for (const gqlError of errors) info(`[debug] ${gqlError.message}`);
648
708
  process.exit(4);
649
709
  }
710
+ if (subrequestStatus(errors) === 401) {
711
+ const service = serviceOf(errors);
712
+ const where = service ?? "The subgraph";
713
+ error(`${where} did not accept your token.`);
714
+ if (actingAsApplication()) {
715
+ hint("The application token has expired or was signed with a key Hermes no longer publishes");
716
+ hint("(a local Hermes mints a fresh key on every restart). Run `sl use application <id>` again.");
717
+ } else {
718
+ hint("Run `sl login` again; `sl whoami` shows what the CLI is acting as.");
719
+ }
720
+ if (verbose) for (const gqlError of errors) info(`[debug] ${JSON.stringify(gqlError)}`);
721
+ process.exit(4);
722
+ }
723
+ if (subrequestStatus(errors) === 403) {
724
+ const service = serviceOf(errors);
725
+ const where = service ?? "The subgraph";
726
+ const company = options.company ?? getUserContext().company ?? options.companyId;
727
+ if (company && UUID.test(company)) {
728
+ error(`${where} refused ${company}: that is a raw uuid, not a company id.`);
729
+ hint("Pass its slug, or the id `sl companies` lists.");
730
+ } else if (company) {
731
+ error(`${where} refused to act for company ${company}.`);
732
+ hint("Your token does not list that company, or Hermes no longer knows you as one of its members.");
733
+ hint("`sl whoami` shows what the CLI is acting as;");
734
+ hint("pick one of your companies with --company or `sl config set company <slug|id>`.");
735
+ } else {
736
+ error(`${where} refused this request: it names no company to act for.`);
737
+ hint("Pick one of your companies with --company or `sl config set company <slug|id>`;");
738
+ hint("`sl companies` lists them. Join one first if the list is empty.");
739
+ }
740
+ if (verbose) for (const gqlError of errors) info(`[debug] ${JSON.stringify(gqlError)}`);
741
+ process.exit(4);
742
+ }
650
743
  const code = codeOf(errors);
651
744
  if (code !== null && code !== "DOWNSTREAM_SERVICE_ERROR") {
652
745
  error(humanise(code));
@@ -695,6 +788,8 @@ async function executeQuery(query, variables, options = {}) {
695
788
  if (authenticated) {
696
789
  const { token, kind } = await resolveAccessToken(options, attempt);
697
790
  headers["Authorization"] = `Bearer ${token}`;
791
+ const companyId = options.withoutCompany ? void 0 : options.companyId ?? await resolveCompanyId({ ctx: getUserContext() });
792
+ if (companyId) headers["X-Company-Id"] = companyId;
698
793
  if (attempt.verbose) info(`[debug] ${kind} token: ...${token.slice(-8)}`);
699
794
  }
700
795
  let res;
@@ -774,19 +869,10 @@ function buildSelections(type, schema, depth, exclude, prefix, visited) {
774
869
  const fields = type.getFields();
775
870
  const lines = [];
776
871
  const isPayload = PAYLOAD_TYPE_PATTERN.test(type.name);
777
- if (type.name.endsWith("Connection") && fields.nodes && fields.pageInfo) {
872
+ if (isConnection(type)) {
778
873
  const nodesType = unwrap(fields.nodes.type);
779
874
  const nodeSelections = buildSelections(nodesType, schema, depth, exclude, `${prefix}nodes.`, new Set(visited));
780
- if (nodeSelections.length === 0) return [];
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;
875
+ return connectionSelections(type, nodeSelections);
790
876
  }
791
877
  for (const [name, field] of Object.entries(fields)) {
792
878
  if (name.startsWith("__")) continue;
@@ -801,7 +887,7 @@ function buildSelections(type, schema, depth, exclude, prefix, visited) {
801
887
  } else if (isObjectType(namedType) && depth > 0) {
802
888
  const subSelections = buildSelections(namedType, schema, depth - 1, exclude, `${fullPath}.`, new Set(visited));
803
889
  if (subSelections.length > 0) {
804
- lines.push(`${name} {`);
890
+ lines.push(`${fieldCall(name, field)} {`);
805
891
  for (const sel of subSelections) lines.push(` ${sel}`);
806
892
  lines.push(`}`);
807
893
  }
@@ -809,6 +895,95 @@ function buildSelections(type, schema, depth, exclude, prefix, visited) {
809
895
  }
810
896
  return lines;
811
897
  }
898
+ var NESTED_PAGE_SIZE = 10;
899
+ function fieldCall(name, field) {
900
+ const named = unwrap(field.type);
901
+ const pageable = isObjectType(named) && isConnection(named) && field.args.some((a) => a.name === "first");
902
+ return pageable ? `${name}(first: ${NESTED_PAGE_SIZE})` : name;
903
+ }
904
+ function isConnection(type) {
905
+ const fields = type.getFields();
906
+ return type.name.endsWith("Connection") && Boolean(fields.nodes) && Boolean(fields.pageInfo);
907
+ }
908
+ function selectableFields(type) {
909
+ return Object.values(type.getFields()).filter(
910
+ (field) => !field.name.startsWith("__") && !field.args.some((a) => isNonNullType(a.type) && a.defaultValue === void 0)
911
+ );
912
+ }
913
+ function edgeExtras(connection) {
914
+ const edgesField = connection.getFields().edges;
915
+ if (!edgesField) return null;
916
+ const edge = unwrap(edgesField.type);
917
+ if (!isObjectType(edge)) return null;
918
+ const lines = [];
919
+ for (const field of selectableFields(edge)) {
920
+ if (field.name === "node" || field.name === "cursor" || field.name === "id") continue;
921
+ const named = unwrap(field.type);
922
+ if (isLeaf(named)) {
923
+ lines.push(field.name);
924
+ } else if (isObjectType(named)) {
925
+ const leaves = selectableFields(named).filter((sub) => isLeaf(unwrap(sub.type))).map((sub) => sub.name);
926
+ if (leaves.length > 0) lines.push(`${field.name} { ${leaves.join(" ")} }`);
927
+ }
928
+ }
929
+ return lines.length === 0 ? null : { edge, lines };
930
+ }
931
+ function connectionSelections(connection, nodeSelections) {
932
+ if (nodeSelections.length === 0) return [];
933
+ const lines = [];
934
+ const extras = edgeExtras(connection);
935
+ if (extras) {
936
+ lines.push("edges {");
937
+ lines.push(" node {");
938
+ for (const sel of nodeSelections) lines.push(` ${sel}`);
939
+ lines.push(" }");
940
+ for (const extra of extras.lines) lines.push(` ${extra}`);
941
+ lines.push("}");
942
+ } else {
943
+ lines.push("nodes {");
944
+ for (const sel of nodeSelections) lines.push(` ${sel}`);
945
+ lines.push("}");
946
+ }
947
+ lines.push("pageInfo {");
948
+ lines.push(" hasNextPage");
949
+ lines.push(" endCursor");
950
+ lines.push("}");
951
+ if (connection.getFields().totalCount) lines.push("totalCount");
952
+ for (const extra of connectionExtras(connection)) lines.push(extra);
953
+ return lines;
954
+ }
955
+ var CONNECTION_PLUMBING = /* @__PURE__ */ new Set(["edges", "nodes", "pageInfo", "totalCount", "approximateTotalCount"]);
956
+ function connectionExtras(connection) {
957
+ return selectableFields(connection).filter((field) => !CONNECTION_PLUMBING.has(field.name)).flatMap((field) => {
958
+ const named = unwrap(field.type);
959
+ if (isLeaf(named)) return [field.name];
960
+ if (!isObjectType(named)) return [];
961
+ const inner = selectableFields(named).flatMap((sub) => {
962
+ const subType = unwrap(sub.type);
963
+ if (isLeaf(subType)) return [sub.name];
964
+ if (!isObjectType(subType)) return [];
965
+ const leaves = selectableFields(subType).filter((leaf) => isLeaf(unwrap(leaf.type)));
966
+ return leaves.length === 0 ? [] : [`${sub.name} { ${leaves.map((leaf) => leaf.name).join(" ")} }`];
967
+ });
968
+ return inner.length === 0 ? [] : [`${field.name} { ${inner.join(" ")} }`];
969
+ });
970
+ }
971
+ var UnknownFieldError = class extends Error {
972
+ field;
973
+ suggestions;
974
+ constructor(field, type) {
975
+ const names = Object.keys(type.getFields()).filter((name) => !name.startsWith("__"));
976
+ const needle = field.toLowerCase();
977
+ const suggestions = names.filter((name) => {
978
+ const candidate = name.toLowerCase();
979
+ return candidate.includes(needle) || needle.includes(candidate);
980
+ });
981
+ super(`${type.name} has no field "${field}".`);
982
+ this.name = "UnknownFieldError";
983
+ this.field = field;
984
+ this.suggestions = suggestions.length > 0 ? suggestions : names;
985
+ }
986
+ };
812
987
  function buildQuery(schema, kind, fieldName, variables, options = {}) {
813
988
  const rootType = kind === "query" ? schema.getQueryType() : schema.getMutationType();
814
989
  if (!rootType) throw new Error(`No ${kind} type in schema`);
@@ -853,20 +1028,11 @@ ${selectionBody}
853
1028
  function buildFieldsFromList(type, schema, fieldPaths) {
854
1029
  if (!isObjectType(type)) return [];
855
1030
  const fields = type.getFields();
856
- if (type.name.endsWith("Connection") && fields.nodes && fields.pageInfo) {
1031
+ if (isConnection(type)) {
857
1032
  const nodesType = unwrap(fields.nodes.type);
858
- const nodeSelections = buildFieldsFromList(nodesType, schema, fieldPaths);
859
- if (nodeSelections.length === 0) return [];
860
- const lines2 = [];
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;
1033
+ const withId = isObjectType(nodesType) && nodesType.getFields().id && !fieldPaths.includes("id");
1034
+ const nodeSelections = buildFieldsFromList(nodesType, schema, withId ? ["id", ...fieldPaths] : fieldPaths);
1035
+ return connectionSelections(type, nodeSelections);
870
1036
  }
871
1037
  const lines = [];
872
1038
  const grouped = /* @__PURE__ */ new Map();
@@ -877,14 +1043,14 @@ function buildFieldsFromList(type, schema, fieldPaths) {
877
1043
  }
878
1044
  for (const [name, subPaths] of grouped) {
879
1045
  const field = fields[name];
880
- if (!field) continue;
1046
+ if (!field) throw new UnknownFieldError(name, type);
881
1047
  const namedType = unwrap(field.type);
882
1048
  if (isLeaf(namedType)) {
883
1049
  lines.push(name);
884
1050
  } else if (isObjectType(namedType) && subPaths.length > 0) {
885
1051
  const subSelections = buildFieldsFromList(namedType, schema, subPaths);
886
1052
  if (subSelections.length > 0) {
887
- lines.push(`${name} {`);
1053
+ lines.push(`${fieldCall(name, field)} {`);
888
1054
  for (const sel of subSelections) lines.push(` ${sel}`);
889
1055
  lines.push(`}`);
890
1056
  }
@@ -893,28 +1059,60 @@ function buildFieldsFromList(type, schema, fieldPaths) {
893
1059
  return lines;
894
1060
  }
895
1061
 
896
- // src/lib/company.ts
897
- function resolveCompanyId(opts) {
898
- return opts.companyId || opts.ctx?.companyId;
899
- }
900
-
901
1062
  // src/lib/render.ts
902
1063
  var INDENT = " ";
1064
+ var CONNECTION_PLUMBING2 = /* @__PURE__ */ new Set([
1065
+ "edges",
1066
+ "nodes",
1067
+ "pageInfo",
1068
+ "totalCount",
1069
+ "approximateTotalCount",
1070
+ "__typename"
1071
+ ]);
903
1072
  function isRecord(value) {
904
1073
  return typeof value === "object" && value !== null && !Array.isArray(value);
905
1074
  }
1075
+ function rowOf(edge) {
1076
+ if (!isRecord(edge) || !isRecord(edge.node)) return isRecord(edge) ? edge.node : edge;
1077
+ const { node, cursor: _cursor, __typename: _typename, ...extras } = edge;
1078
+ const said = Object.entries(extras).filter(
1079
+ ([, value]) => value != null && !(Array.isArray(value) && value.length === 0)
1080
+ );
1081
+ return { ...node, ...Object.fromEntries(said) };
1082
+ }
906
1083
  function asConnection(value) {
907
- if (!isRecord(value) || !Array.isArray(value.nodes)) return null;
908
- return value;
1084
+ if (!isRecord(value)) return null;
1085
+ if (Array.isArray(value.nodes)) return value;
1086
+ if (Array.isArray(value.edges)) return { ...value, nodes: value.edges.map(rowOf) };
1087
+ return null;
909
1088
  }
910
1089
  function formatScalar(value) {
911
1090
  if (value === null || value === void 0) return "\u2014";
912
1091
  if (typeof value === "boolean") return value ? "yes" : "no";
913
1092
  if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) {
914
- return value.slice(0, 16).replace("T", " ");
1093
+ return value.slice(0, 19).replace("T", " ");
915
1094
  }
916
1095
  return String(value);
917
1096
  }
1097
+ function isFlatRecord(value) {
1098
+ return isRecord(value) && Object.values(value).every((v) => !isRecord(v) && !Array.isArray(v));
1099
+ }
1100
+ var isDeadline = (key) => /Until$/.test(key);
1101
+ function formatDeadline(value) {
1102
+ return typeof value === "string" && value !== "" ? `until ${formatScalar(value)}` : "\u2014";
1103
+ }
1104
+ function formatFlatRows(rows, indent) {
1105
+ const keys = Object.keys(rows[0]).filter((key) => key !== "__typename");
1106
+ const ordered = [...keys.filter((key) => !isDeadline(key)), ...keys.filter(isDeadline)];
1107
+ const cells = rows.map(
1108
+ (row) => ordered.map((key) => isDeadline(key) ? formatDeadline(row[key]) : formatScalar(row[key]))
1109
+ );
1110
+ const widths = ordered.map((_, column) => Math.max(...cells.map((row) => (row[column] ?? "").length)));
1111
+ return cells.map(
1112
+ (row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" ")
1113
+ ).join(`
1114
+ ${indent}`);
1115
+ }
918
1116
  function summarise(key, value) {
919
1117
  const connection = asConnection(value);
920
1118
  if (connection) {
@@ -928,13 +1126,21 @@ function summarise(key, value) {
928
1126
  }
929
1127
  return null;
930
1128
  }
931
- function formatRecord(record, indent) {
932
- const entries = Object.entries(record).filter(([key]) => key !== "__typename");
1129
+ function titleOf(record) {
1130
+ return typeof record.id === "string" && record.id !== "" ? record.id : null;
1131
+ }
1132
+ function formatRecord(record, indent, titled = false) {
1133
+ const title = titled ? titleOf(record) : null;
1134
+ const isFlatRows = (value) => Array.isArray(value) && value.length > 0 && value.every(isFlatRecord);
1135
+ 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
1136
  const width = Math.max(0, ...entries.map(([key]) => key.length));
934
- return entries.map(([key, value]) => {
935
- const rendered = summarise(key, value) ?? formatScalar(value);
1137
+ const valueIndent = `${indent}${"".padEnd(width)} `;
1138
+ const body = entries.map(([key, value]) => {
1139
+ const rendered = isFlatRows(value) ? formatFlatRows(value, valueIndent) : summarise(key, value) ?? formatScalar(value);
936
1140
  return `${indent}${key.padEnd(width)} ${rendered}`;
937
1141
  }).join("\n");
1142
+ return title === null ? body : `${indent.slice(INDENT.length)}${title}
1143
+ ${body}`;
938
1144
  }
939
1145
  function formatFooter(connection) {
940
1146
  const shown = connection.nodes.length;
@@ -945,21 +1151,27 @@ function formatFooter(connection) {
945
1151
  const counted = total === void 0 ? `${shown}` : `${shown} of ${total}`;
946
1152
  return more ? `${counted} \u2014 more available, pass --after ${connection.pageInfo?.endCursor}` : counted;
947
1153
  }
1154
+ function formatConnectionExtras(connection) {
1155
+ return Object.entries(connection).filter(([key, value]) => !CONNECTION_PLUMBING2.has(key) && value != null).map(
1156
+ ([key, value]) => isRecord(value) ? `${key}
1157
+ ${formatRecord(value, INDENT)}` : `${key} ${formatScalar(value)}`
1158
+ );
1159
+ }
948
1160
  function formatResult(result) {
949
1161
  const connection = asConnection(result);
950
1162
  if (connection) {
951
1163
  if (connection.nodes.length === 0) return "No results.";
952
1164
  const blocks = connection.nodes.map(
953
- (node) => isRecord(node) ? formatRecord(node, INDENT) : `${INDENT}${formatScalar(node)}`
1165
+ (node) => isRecord(node) ? formatRecord(node, INDENT, true) : `${INDENT}${formatScalar(node)}`
954
1166
  );
955
- const footer = formatFooter(connection);
956
- return footer ? `${blocks.join("\n\n")}
957
-
958
- ${footer}` : blocks.join("\n\n");
1167
+ const tail = [formatFooter(connection), ...formatConnectionExtras(result)].filter(
1168
+ (part) => part !== null
1169
+ );
1170
+ return [blocks.join("\n\n"), ...tail].join("\n\n");
959
1171
  }
960
1172
  if (Array.isArray(result)) {
961
1173
  if (result.length === 0) return "No results.";
962
- return result.map((item) => isRecord(item) ? formatRecord(item, INDENT) : formatScalar(item)).join("\n\n");
1174
+ return result.map((item) => isRecord(item) ? formatRecord(item, INDENT, true) : formatScalar(item)).join("\n\n");
963
1175
  }
964
1176
  if (isRecord(result)) return formatRecord(result, "");
965
1177
  return result === null || result === void 0 ? null : formatScalar(result);
@@ -1002,7 +1214,41 @@ function isStructuredInput(type) {
1002
1214
  if (isListType2(type)) return true;
1003
1215
  return isInputObjectType(type);
1004
1216
  }
1217
+ function enumListOf(type) {
1218
+ const listless = isNonNullType2(type) ? type.ofType : type;
1219
+ if (!isListType2(listless)) return null;
1220
+ const inner = unwrap2(listless.ofType);
1221
+ return isEnumType2(inner) ? inner : null;
1222
+ }
1223
+ function commonPrefix(values) {
1224
+ if (values.length < 2) return "";
1225
+ let prefix = values[0];
1226
+ for (const value of values) while (!value.startsWith(prefix)) prefix = prefix.slice(0, -1);
1227
+ const cut = prefix.lastIndexOf("_");
1228
+ return cut === -1 ? "" : prefix.slice(0, cut + 1);
1229
+ }
1230
+ function coerceEnumList(raw, enumType, flagName) {
1231
+ const names = enumType.getValues().map((value) => value.name);
1232
+ if (raw.trim() === "all") return names;
1233
+ if (raw.trim() === "none") return [];
1234
+ const prefix = commonPrefix(names);
1235
+ return raw.split(",").filter((part) => part.trim() !== "").map((part) => {
1236
+ const wanted = part.trim().replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
1237
+ const match = names.find((name) => name === wanted || name === `${prefix}${wanted}`);
1238
+ if (match === void 0) {
1239
+ const short = names.map(
1240
+ (name) => name.slice(prefix.length).toLowerCase().replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())
1241
+ );
1242
+ throw new Error(
1243
+ `--${flagName} does not know "${part.trim()}". One or more of: ${short.join(", ")}, all, or none.`
1244
+ );
1245
+ }
1246
+ return match;
1247
+ });
1248
+ }
1005
1249
  function coerceValue(raw, type, flagName) {
1250
+ const enumList = enumListOf(type);
1251
+ if (enumList && !raw.trim().startsWith("[")) return coerceEnumList(raw, enumList, flagName);
1006
1252
  if (isStructuredInput(type)) {
1007
1253
  try {
1008
1254
  return JSON.parse(raw);
@@ -1106,7 +1352,10 @@ function describeArg(arg) {
1106
1352
  const parts = [];
1107
1353
  if (arg.description) parts.push(arg.description.replace(/\s+/g, " ").trim());
1108
1354
  const typeSig = renderType(arg.type);
1109
- parts.push(isStructuredInput(arg.type) ? `${typeSig} (JSON)` : typeSig);
1355
+ const enumList = enumListOf(arg.type);
1356
+ parts.push(
1357
+ enumList ? `${typeSig} (comma-separated, all, or none)` : isStructuredInput(arg.type) ? `${typeSig} (JSON)` : typeSig
1358
+ );
1110
1359
  const named = unwrap2(arg.type);
1111
1360
  const shape = describeStructuredType(named);
1112
1361
  if (shape) parts.push(shape);
@@ -1131,7 +1380,7 @@ function buildCommand(schema, fieldName, kind, description, service) {
1131
1380
  const cmd = new Command2(kebab(fieldName)).description(description);
1132
1381
  const requiresCompanyId = cliArgs.some((a) => a.name === "companyId" && a.required);
1133
1382
  for (const a of cliArgs) {
1134
- const placeholder = isStructuredInput(a.type) ? "json" : kebab(a.name);
1383
+ const placeholder = enumListOf(a.type) ? "a,b|all|none..." : isStructuredInput(a.type) ? "json" : kebab(a.name);
1135
1384
  const flag = `--${kebab(a.name)} <${placeholder}>`;
1136
1385
  const isContext = a.name in CONTEXT_FIELDS;
1137
1386
  if (isContext) {
@@ -1145,23 +1394,20 @@ function buildCommand(schema, fieldName, kind, description, service) {
1145
1394
  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
1395
  cmd.action(async function() {
1147
1396
  const opts = this.optsWithGlobals();
1148
- const needsContext = cliArgs.some((a) => a.name in CONTEXT_FIELDS);
1149
- const ctx = needsContext ? getUserContext() : void 0;
1150
- const resolvedCompanyId = resolveCompanyId({
1151
- companyId: typeof opts.companyId === "string" ? opts.companyId : void 0,
1152
- ctx
1153
- });
1154
- if (requiresCompanyId && !resolvedCompanyId) {
1397
+ const ctx = getUserContext();
1398
+ const acting = typeof opts.company === "string" ? opts.company : void 0;
1399
+ const actingId = await resolveCompanyId({ company: acting, ctx });
1400
+ const argumentCompanyId = typeof opts.companyId === "string" ? await resolveCompanyId({ company: opts.companyId, ctx }) : actingId;
1401
+ if (requiresCompanyId && !argumentCompanyId) {
1155
1402
  error("No company selected.");
1156
- hint("Pass --company-id <id> or set one with `sl config set companyId <id>`.");
1403
+ hint("Pass --company-id <slug|id>, or act for one with --company or `sl config set company <slug|id>`.");
1157
1404
  process.exit(2);
1158
1405
  }
1159
- if (resolvedCompanyId) opts.companyId = resolvedCompanyId;
1406
+ if (argumentCompanyId) opts.companyId = argumentCompanyId;
1160
1407
  const collectArgs = () => {
1161
1408
  const out = {};
1162
1409
  for (const a of cliArgs) {
1163
- const raw = opts[a.name];
1164
- const ctxProp = CONTEXT_FIELDS[a.name];
1410
+ const raw = Array.isArray(opts[a.name]) ? opts[a.name].join(",") : opts[a.name];
1165
1411
  if (raw != null) {
1166
1412
  try {
1167
1413
  out[a.name] = coerceValue(raw, a.type, kebab(a.name));
@@ -1170,19 +1416,31 @@ function buildCommand(schema, fieldName, kind, description, service) {
1170
1416
  hint("Run the command with --help to see the expected shape of each argument.");
1171
1417
  process.exit(2);
1172
1418
  }
1173
- } else if (ctxProp && ctx) {
1174
- out[a.name] = ctx[ctxProp];
1175
1419
  }
1176
1420
  }
1177
1421
  return out;
1178
1422
  };
1179
1423
  const variables = useInputWrapper ? { input: collectArgs() } : collectArgs();
1180
- const { query, fieldName: fName } = buildQuery(schema, kind, fieldName, variables, {
1181
- depth: opts.depth,
1182
- fields: opts.fields?.split(","),
1183
- exclude: opts.exclude?.split(",")
1424
+ let built;
1425
+ try {
1426
+ built = buildQuery(schema, kind, fieldName, variables, {
1427
+ depth: opts.depth,
1428
+ fields: opts.fields?.split(","),
1429
+ exclude: opts.exclude?.split(",")
1430
+ });
1431
+ } catch (buildError) {
1432
+ if (!(buildError instanceof UnknownFieldError)) throw buildError;
1433
+ error(buildError.message);
1434
+ hint(`Did you mean: ${buildError.suggestions.join(", ")}?`);
1435
+ process.exit(2);
1436
+ }
1437
+ const { query, fieldName: fName } = built;
1438
+ const data = await graphqlRaw(query, variables, {
1439
+ endpoint: opts.endpoint,
1440
+ company: acting,
1441
+ companyId: actingId,
1442
+ subgraph: service
1184
1443
  });
1185
- const data = await graphqlRaw(query, variables, { endpoint: opts.endpoint, subgraph: service });
1186
1444
  const result = data[fName];
1187
1445
  if (result == null) {
1188
1446
  if (actingAsApplication()) {
@@ -1332,6 +1590,16 @@ async function setupUserContext(endpoint) {
1332
1590
  info(` User: ${user.firstName} ${user.lastName} <${user.email}>`);
1333
1591
  hint("Run `sl whoami` to verify.");
1334
1592
  }
1593
+ function reportScopeGrant(requestedScope, accessToken) {
1594
+ const missing = servicesWithoutScope(requestedScope, accessToken);
1595
+ if (missing.length === 0) return;
1596
+ warn(`No scope granted for: ${missing.join(", ")}.`);
1597
+ info(" Their commands will not appear in `sl --help`, and their fields are");
1598
+ info(" filtered out of the schema this CLI builds itself from.");
1599
+ hint("Auth0 grants requested scopes by exact string match against your assigned");
1600
+ hint("permissions and drops the rest silently \u2014 this is a role assignment in the");
1601
+ hint("tenant you logged into, not a CLI setting. Ask an administrator, then re-run `sl login`.");
1602
+ }
1335
1603
  var loginCommand = new Command3("login").summary("Log in to your Sortlist account").description(
1336
1604
  "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
1605
  ).option("--scope <scope>", "OAuth scope", DEFAULT_SCOPE).option("--no-browser", "Print the login URL instead of opening a browser").action(async function() {
@@ -1404,6 +1672,7 @@ var loginCommand = new Command3("login").summary("Log in to your Sortlist accoun
1404
1672
  expiresAt: Math.floor(Date.now() / 1e3) + token.expiresIn
1405
1673
  });
1406
1674
  success("Logged in successfully.");
1675
+ reportScopeGrant(opts.scope, token.accessToken);
1407
1676
  await setupUserContext(opts.endpoint);
1408
1677
  return;
1409
1678
  }
@@ -1902,7 +2171,7 @@ Operation names are unique across the supergraph, so they are not namespaced:
1902
2171
  var program = new Command8().name("sl").configureOutput({
1903
2172
  writeOut: (str) => process.stdout.write(colorizeHelp(str)),
1904
2173
  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");
2174
+ }).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
2175
  program.addCommand(loginCommand);
1907
2176
  program.addCommand(logoutCommand);
1908
2177
  program.addCommand(whoamiCommand);