@sortlist/cli 0.62.0 → 0.64.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
@@ -1,3 +1,21 @@
1
+ import {
2
+ ResultNotDeliveredError,
3
+ RouterError,
4
+ UnknownFieldError,
5
+ buildIntrospected,
6
+ buildQuery,
7
+ codeOf,
8
+ createRouterClient,
9
+ fetchIntrospection,
10
+ isAbort,
11
+ listOperations,
12
+ listen,
13
+ nextPageCursor,
14
+ runOperation,
15
+ serviceOf,
16
+ unwrap
17
+ } from "./chunk-RCCV6ET2.js";
18
+
1
19
  // src/index.ts
2
20
  import { Command as Command10 } from "commander";
3
21
 
@@ -720,20 +738,22 @@ async function resolveAccessToken(options, attempt) {
720
738
  }
721
739
  return { token: creds.accessToken, kind: "user" };
722
740
  }
723
- function reportHttpFailure(res, body, attempt) {
741
+ function reportHttpFailure(failure, attempt) {
724
742
  const { operationName, endpoint, throwOnError, verbose } = attempt;
725
- captureException2(new Error(`${operationName} failed: HTTP ${res.status}`), {
743
+ const status = failure.httpStatus;
744
+ const body = failure.body ?? "";
745
+ captureException2(new Error(`${operationName} failed: HTTP ${status}`), {
726
746
  operationName,
727
- httpStatus: res.status,
747
+ httpStatus: status,
728
748
  endpoint
729
749
  });
730
750
  if (throwOnError) {
731
- throw new GraphQLRequestError(`${operationName} failed: HTTP ${res.status} ${res.statusText}`, {
751
+ throw new GraphQLRequestError(`${operationName} failed: HTTP ${status} ${failure.statusText}`, {
732
752
  operationName,
733
- httpStatus: res.status
753
+ httpStatus: status
734
754
  });
735
755
  }
736
- error(`${operationName} failed: HTTP ${res.status} ${res.statusText}`);
756
+ error(`${operationName} failed: HTTP ${status} ${failure.statusText}`);
737
757
  hint("Check your network connection and endpoint: sl config show");
738
758
  if (verbose) info(`[debug] Response body: ${body}`);
739
759
  process.exit(3);
@@ -741,13 +761,6 @@ function reportHttpFailure(res, body, attempt) {
741
761
  function hasFieldError(errors) {
742
762
  return errors.some((e) => e.message.includes("Failed to implement") || e.message.includes("undefined method"));
743
763
  }
744
- function codeOf(errors) {
745
- for (const { extensions } of errors) {
746
- const code = extensions?.code;
747
- if (typeof code === "string") return code;
748
- }
749
- return null;
750
- }
751
764
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
752
765
  var CALLBACK_STATUS_NOT_OK = "SUBGRAPH_HTTP_CALLBACK_STATUS_CODE_NOT_OK";
753
766
  var QUERY_LIMIT_CODES = /* @__PURE__ */ new Set(["QUERY_TOO_COMPLEX", "QUERY_TOO_DEEP"]);
@@ -819,17 +832,6 @@ function describe(errors) {
819
832
  function messageLines(errors) {
820
833
  return errors.map((e) => e.message).filter((message) => message !== ROUTER_PLACEHOLDER);
821
834
  }
822
- function serviceOf(errors) {
823
- for (const { extensions } of errors) {
824
- const service = extensions?.service;
825
- if (typeof service === "string") return service;
826
- }
827
- return null;
828
- }
829
- function hasResolvedField(data) {
830
- if (data === null || data === void 0) return false;
831
- return Object.values(data).some((value) => value !== null);
832
- }
833
835
  function reportGraphqlErrors(errors, options, attempt) {
834
836
  const { operationName, throwOnError, verbose } = attempt;
835
837
  captureException2(new Error(`${operationName} GraphQL errors`), {
@@ -937,18 +939,26 @@ function startAttempt(query, variables, options) {
937
939
  if (attempt.verbose) logRequest(query, variables, attempt);
938
940
  return attempt;
939
941
  }
940
- async function requestHeaders(options, attempt) {
941
- const headers = baseRequestHeaders();
942
- if (!(options.authenticated ?? true)) return { headers, options };
942
+ async function requestIdentity(options, attempt) {
943
+ if (!(options.authenticated ?? true)) return { options };
943
944
  const { token, kind } = await resolveAccessToken(options, attempt);
944
- headers["Authorization"] = `Bearer ${token}`;
945
945
  const { companyId, personal: personal2 } = await actingCompany2(options, kind, {
946
946
  named: async () => options.companyId ?? await resolveCompanyId({ ctx: getUserContext() }),
947
947
  personal: personalCompanyId
948
948
  });
949
- if (companyId) headers["X-Company-Id"] = companyId;
950
949
  if (attempt.verbose) info(`[debug] ${kind} token: ...${token.slice(-8)}`);
951
- return { headers, options: { ...options, actingForPersonalCompany: personal2 } };
950
+ return { token, companyId, options: { ...options, actingForPersonalCompany: personal2 } };
951
+ }
952
+ async function routerClient(options, attempt, onPartialErrors) {
953
+ const { token, companyId, options: sent } = await requestIdentity(options, attempt);
954
+ const client = createRouterClient({
955
+ endpoint: attempt.endpoint,
956
+ token,
957
+ companyId,
958
+ headers: baseRequestHeaders(),
959
+ onPartialErrors
960
+ });
961
+ return { client, sent };
952
962
  }
953
963
  async function actingCompany2(options, kind, lookup) {
954
964
  if (options.withoutCompany) return { companyId: void 0, personal: false };
@@ -957,128 +967,68 @@ async function actingCompany2(options, kind, lookup) {
957
967
  const personal2 = await lookup.personal();
958
968
  return { companyId: personal2, personal: personal2 !== void 0 };
959
969
  }
960
- async function executeQuery(query, variables, options = {}) {
961
- const attempt = startAttempt(query, variables, options);
962
- const { headers, options: sent } = await requestHeaders(options, attempt);
963
- let res;
964
- try {
965
- res = await fetch(attempt.endpoint, {
966
- method: "POST",
967
- headers,
968
- body: JSON.stringify({ query, variables })
969
- });
970
- } catch (err) {
971
- reportUnreachable(err, {
970
+ function reportRouterFailure(failure, sent, attempt, { graphqlFirst } = { graphqlFirst: false }) {
971
+ if (failure.kind === "unreachable") {
972
+ reportUnreachable(failure.cause, {
972
973
  endpoint: attempt.endpoint,
973
974
  operationName: attempt.operationName,
974
975
  throwOnError: attempt.throwOnError
975
976
  });
976
977
  }
977
- if (!res.ok) reportHttpFailure(res, await res.text(), attempt);
978
- const json = await res.json();
979
- if (json.errors?.length) {
980
- if (!hasResolvedField(json.data)) reportGraphqlErrors(json.errors, sent, attempt);
981
- for (const gqlError of json.errors) warn(gqlError.message);
982
- if (hasFieldError(json.errors)) {
978
+ const reportsHttp = failure.httpStatus !== void 0 && !(graphqlFirst && failure.graphqlErrors.length > 0);
979
+ if (reportsHttp) reportHttpFailure(failure, attempt);
980
+ return reportGraphqlErrors(failure.graphqlErrors, sent, attempt);
981
+ }
982
+ function warnPartialErrors(errors) {
983
+ for (const gqlError of errors) warn(gqlError.message);
984
+ }
985
+ async function executeQuery(query, variables, options = {}) {
986
+ const attempt = startAttempt(query, variables, options);
987
+ const { client, sent } = await routerClient(options, attempt, (errors) => {
988
+ warnPartialErrors(errors);
989
+ if (hasFieldError(errors)) {
983
990
  hint("Use --fields to select specific fields, or --exclude to skip broken ones.");
984
991
  }
985
- return json.data;
986
- }
987
- if (!json.data) {
988
- if (attempt.throwOnError) {
989
- throw new GraphQLRequestError(`${attempt.operationName}: no data returned from API.`, {
990
- operationName: attempt.operationName
991
- });
992
- }
993
- error(`${attempt.operationName}: no data returned from API.`);
994
- hint("This usually means the server returned an empty response.");
995
- hint("Verify your endpoint: sl config show");
996
- process.exit(1);
997
- }
998
- return json.data;
999
- }
1000
- async function* parseEventStream(chunks) {
1001
- const decoder = new TextDecoder();
1002
- let buffer = "";
1003
- for await (const chunk of chunks) {
1004
- buffer += typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true });
1005
- buffer = buffer.replaceAll("\r\n", "\n");
1006
- let boundary = buffer.indexOf("\n\n");
1007
- while (boundary !== -1) {
1008
- const block = buffer.slice(0, boundary);
1009
- buffer = buffer.slice(boundary + 2);
1010
- const parsed = parseEventBlock(block);
1011
- if (parsed) yield parsed;
1012
- boundary = buffer.indexOf("\n\n");
1013
- }
1014
- }
1015
- const rest = parseEventBlock(buffer);
1016
- if (rest) yield rest;
1017
- }
1018
- function parseEventBlock(block) {
1019
- let event = "message";
1020
- const data = [];
1021
- for (const line of block.split("\n")) {
1022
- if (line === "" || line.startsWith(":")) continue;
1023
- const colon = line.indexOf(":");
1024
- const field = colon === -1 ? line : line.slice(0, colon);
1025
- const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
1026
- if (field === "event") event = value;
1027
- if (field === "data") data.push(value);
1028
- }
1029
- return data.length > 0 || event !== "message" ? { event, data: data.join("\n") } : null;
1030
- }
1031
- async function openEventStream(query, variables, options, attempt) {
1032
- const { headers, options: sent } = await requestHeaders(options, attempt);
1033
- headers["Accept"] = "text/event-stream";
1034
- let res;
992
+ });
1035
993
  try {
1036
- res = await fetch(attempt.endpoint, {
1037
- method: "POST",
1038
- headers,
1039
- body: JSON.stringify({ query, variables }),
1040
- signal: options.signal
1041
- });
994
+ return await client.execute(query, variables);
1042
995
  } catch (err) {
1043
- reportUnreachable(err, {
1044
- endpoint: attempt.endpoint,
1045
- operationName: attempt.operationName,
1046
- throwOnError: attempt.throwOnError
1047
- });
996
+ if (!(err instanceof RouterError)) throw err;
997
+ if (err.kind === "no_data") reportNoData(attempt);
998
+ return reportRouterFailure(err, sent, attempt);
1048
999
  }
1049
- if (!res.ok) {
1050
- const body = await res.text();
1051
- const errors = parseErrors(body);
1052
- if (errors) reportGraphqlErrors(errors, sent, attempt);
1053
- reportHttpFailure(res, body, attempt);
1054
- }
1055
- return { res, sent };
1056
1000
  }
1057
- function parseErrors(body) {
1058
- try {
1059
- const errors = JSON.parse(body).errors;
1060
- return errors?.length ? errors : null;
1061
- } catch {
1062
- return null;
1001
+ function reportNoData(attempt) {
1002
+ if (attempt.throwOnError) {
1003
+ throw new GraphQLRequestError(`${attempt.operationName}: no data returned from API.`, {
1004
+ operationName: attempt.operationName
1005
+ });
1063
1006
  }
1007
+ error(`${attempt.operationName}: no data returned from API.`);
1008
+ hint("This usually means the server returned an empty response.");
1009
+ hint("Verify your endpoint: sl config show");
1010
+ process.exit(1);
1064
1011
  }
1065
- async function* subscriptionEvents(res, options, attempt) {
1066
- if (!res.body) return;
1067
- for await (const { event, data } of parseEventStream(res.body)) {
1068
- if (event === "complete") return;
1069
- if (event !== "next" && event !== "message") continue;
1070
- const payload = JSON.parse(data);
1071
- if (payload.errors?.length && !hasResolvedField(payload.data)) {
1072
- reportGraphqlErrors(payload.errors, options, attempt);
1073
- }
1074
- for (const gqlError of payload.errors ?? []) warn(gqlError.message);
1075
- if (payload.data) yield payload.data;
1012
+ async function* subscriptionEvents(events, options, attempt) {
1013
+ try {
1014
+ yield* events;
1015
+ } catch (err) {
1016
+ if (err instanceof RouterError && err.graphqlErrors.length > 0)
1017
+ reportGraphqlErrors(err.graphqlErrors, options, attempt);
1018
+ throw err;
1076
1019
  }
1077
1020
  }
1078
1021
  async function graphqlSubscribe(query, variables, options = {}) {
1079
1022
  const attempt = startAttempt(query, variables, options);
1080
- const { res, sent } = await openEventStream(query, variables, options, attempt);
1081
- return { events: subscriptionEvents(res, sent, attempt) };
1023
+ const { client, sent } = await routerClient(options, attempt, warnPartialErrors);
1024
+ let events;
1025
+ try {
1026
+ events = await client.openSubscription(query, variables, options.signal);
1027
+ } catch (err) {
1028
+ if (!(err instanceof RouterError)) throw err;
1029
+ return reportRouterFailure(err, sent, attempt, { graphqlFirst: true });
1030
+ }
1031
+ return { events: subscriptionEvents(events, sent, attempt) };
1082
1032
  }
1083
1033
  async function graphql(document, variables, options = {}) {
1084
1034
  return executeQuery(print(document), variables, options);
@@ -1424,360 +1374,17 @@ var connectLinkedinCommand = new Command2("connect-linkedin").summary("Sign a Li
1424
1374
  import { randomUUID } from "crypto";
1425
1375
  import { Command as Command3, Option } from "commander";
1426
1376
  import {
1427
- isEnumType as isEnumType2,
1428
- isInputObjectType,
1429
- isInterfaceType,
1430
- isListType as isListType2,
1431
- isNonNullType as isNonNullType2,
1432
- isObjectType as isObjectType2,
1433
- isScalarType as isScalarType2,
1434
- isUnionType
1435
- } from "graphql";
1436
-
1437
- // src/graphql/query-builder.ts
1438
- import {
1439
- isAbstractType,
1440
1377
  isEnumType,
1378
+ isInputObjectType,
1441
1379
  isListType,
1442
1380
  isNonNullType,
1443
1381
  isObjectType,
1444
1382
  isScalarType
1445
1383
  } from "graphql";
1446
- var CLI_OPERATION_PREFIX = "SlCli_";
1447
- function unwrap(type) {
1448
- if (isNonNullType(type)) return unwrap(type.ofType);
1449
- if (isListType(type)) return unwrap(type.ofType);
1450
- return type;
1451
- }
1452
- function isLeaf(type) {
1453
- return isScalarType(type) || isEnumType(type);
1454
- }
1455
- function ucfirst(s) {
1456
- return s.charAt(0).toUpperCase() + s.slice(1);
1457
- }
1458
- var PAYLOAD_TYPE_PATTERN = /(?:Response|Payload|MutationPayload)$/;
1459
- var PAYLOAD_PLUMBING = /* @__PURE__ */ new Set(["id", "clientMutationId"]);
1460
- function effectiveDepth(returnType, depth) {
1461
- return isObjectType(returnType) && PAYLOAD_TYPE_PATTERN.test(returnType.name) ? depth + 1 : depth;
1462
- }
1463
- function buildSelections(type, schema, depth, exclude, prefix, totalCount, visited) {
1464
- if (!isObjectType(type)) return [];
1465
- if (visited.has(type.name)) return [];
1466
- visited.add(type.name);
1467
- const fields = type.getFields();
1468
- const lines = [];
1469
- const isPayload = PAYLOAD_TYPE_PATTERN.test(type.name);
1470
- if (isConnection(type)) {
1471
- const nodesType = unwrap(fields.nodes.type);
1472
- const nodeSelections = buildSelections(
1473
- nodesType,
1474
- schema,
1475
- depth,
1476
- exclude,
1477
- `${prefix}nodes.`,
1478
- totalCount,
1479
- new Set(visited)
1480
- );
1481
- return connectionSelections(type, nodeSelections, totalCount);
1482
- }
1483
- for (const [name, field] of Object.entries(fields)) {
1484
- if (name.startsWith("__")) continue;
1485
- if (isPayload && PAYLOAD_PLUMBING.has(name)) continue;
1486
- const fullPath = `${prefix}${name}`;
1487
- if (exclude.has(fullPath) || exclude.has(name)) continue;
1488
- if (!isAutoSelectable(field)) continue;
1489
- const namedType = unwrap(field.type);
1490
- if (isLeaf(namedType)) {
1491
- lines.push(name);
1492
- } else if (isObjectType(namedType) && isConnection(namedType) && field.args.length === 0) {
1493
- const pageSelections = buildSelections(
1494
- namedType,
1495
- schema,
1496
- depth,
1497
- exclude,
1498
- `${fullPath}.`,
1499
- totalCount,
1500
- new Set(visited)
1501
- );
1502
- if (pageSelections.length > 0) {
1503
- lines.push(`${name} {`);
1504
- for (const sel of pageSelections) lines.push(` ${sel}`);
1505
- lines.push(`}`);
1506
- }
1507
- } else if (isObjectType(namedType) && depth > 0) {
1508
- const subSelections = buildSelections(
1509
- namedType,
1510
- schema,
1511
- depth - 1,
1512
- exclude,
1513
- `${fullPath}.`,
1514
- totalCount,
1515
- new Set(visited)
1516
- );
1517
- if (subSelections.length > 0) {
1518
- lines.push(`${fieldCall(name, field)} {`);
1519
- for (const sel of subSelections) lines.push(` ${sel}`);
1520
- lines.push(`}`);
1521
- }
1522
- } else if (isAbstractType(namedType) && depth > 0) {
1523
- lines.push(`${name} {`);
1524
- for (const sel of abstractSelections(
1525
- namedType,
1526
- schema,
1527
- depth - 1,
1528
- exclude,
1529
- `${fullPath}.`,
1530
- totalCount,
1531
- visited
1532
- )) {
1533
- lines.push(` ${sel}`);
1534
- }
1535
- lines.push(`}`);
1536
- }
1537
- }
1538
- return lines;
1539
- }
1540
- function abstractSelections(type, schema, depth, exclude, prefix, totalCount, visited) {
1541
- const lines = ["__typename"];
1542
- for (const member of schema.getPossibleTypes(type)) {
1543
- const memberSelections = buildSelections(member, schema, depth, exclude, prefix, totalCount, new Set(visited));
1544
- if (memberSelections.length === 0) continue;
1545
- lines.push(`... on ${member.name} {`);
1546
- for (const sel of memberSelections) lines.push(` ${sel}`);
1547
- lines.push(`}`);
1548
- }
1549
- return lines;
1550
- }
1551
- var NESTED_PAGE_SIZE = 10;
1552
- function fieldCall(name, field) {
1553
- const named = unwrap(field.type);
1554
- const pageable = isObjectType(named) && isConnection(named) && field.args.some((a) => a.name === "first");
1555
- return pageable ? `${name}(first: ${NESTED_PAGE_SIZE})` : name;
1556
- }
1557
- function deliveredPageField(type) {
1558
- const pages = Object.values(type.getFields()).filter((field) => {
1559
- const named = unwrap(field.type);
1560
- return isObjectType(named) && isConnection(named) && field.args.length === 0;
1561
- });
1562
- return pages.length === 1 ? pages[0] : null;
1563
- }
1564
- function isConnection(type) {
1565
- const fields = type.getFields();
1566
- return Boolean(fields.nodes) && Boolean(fields.pageInfo);
1567
- }
1568
- function isAutoSelectable(field) {
1569
- if (field.name.startsWith("__") || field.deprecationReason != null) return false;
1570
- return !field.args.some((a) => isNonNullType(a.type) && a.defaultValue === void 0);
1571
- }
1572
- function selectableFields(type) {
1573
- return Object.values(type.getFields()).filter(isAutoSelectable);
1574
- }
1575
- function edgeExtras(connection) {
1576
- const edgesField = connection.getFields().edges;
1577
- if (!edgesField) return null;
1578
- const edge = unwrap(edgesField.type);
1579
- if (!isObjectType(edge)) return null;
1580
- const lines = [];
1581
- for (const field of selectableFields(edge)) {
1582
- if (field.name === "node" || field.name === "cursor" || field.name === "id") continue;
1583
- const named = unwrap(field.type);
1584
- if (isLeaf(named)) {
1585
- lines.push(field.name);
1586
- } else if (isObjectType(named)) {
1587
- const leaves = selectableFields(named).filter((sub) => isLeaf(unwrap(sub.type))).map((sub) => sub.name);
1588
- if (leaves.length > 0) lines.push(`${field.name} { ${leaves.join(" ")} }`);
1589
- }
1590
- }
1591
- return lines.length === 0 ? null : { edge, lines };
1592
- }
1593
- function connectionSelections(connection, nodeSelections, totalCount) {
1594
- if (nodeSelections.length === 0) return [];
1595
- const lines = [];
1596
- const extras = edgeExtras(connection);
1597
- if (extras) {
1598
- lines.push("edges {");
1599
- lines.push(" node {");
1600
- for (const sel of nodeSelections) lines.push(` ${sel}`);
1601
- lines.push(" }");
1602
- for (const extra of extras.lines) lines.push(` ${extra}`);
1603
- lines.push("}");
1604
- } else {
1605
- lines.push("nodes {");
1606
- for (const sel of nodeSelections) lines.push(` ${sel}`);
1607
- lines.push("}");
1608
- }
1609
- lines.push("pageInfo {");
1610
- lines.push(" hasNextPage");
1611
- lines.push(" endCursor");
1612
- lines.push("}");
1613
- if (totalCount && connection.getFields().totalCount) lines.push("totalCount");
1614
- for (const extra of connectionExtras(connection)) lines.push(extra);
1615
- return lines;
1616
- }
1617
- var CONNECTION_PLUMBING = /* @__PURE__ */ new Set(["edges", "nodes", "pageInfo", "totalCount", "approximateTotalCount"]);
1618
- function isConnectionExtraPath(connection, nodesType, path9) {
1619
- const [top] = path9.split(".");
1620
- if (CONNECTION_PLUMBING.has(top)) return false;
1621
- if (isObjectType(nodesType) && nodesType.getFields()[top]) return false;
1622
- return Boolean(connection.getFields()[top]);
1623
- }
1624
- function connectionExtras(connection) {
1625
- return selectableFields(connection).filter((field) => !CONNECTION_PLUMBING.has(field.name)).flatMap((field) => {
1626
- const named = unwrap(field.type);
1627
- if (isLeaf(named)) return [field.name];
1628
- if (!isObjectType(named)) return [];
1629
- const inner = selectableFields(named).flatMap((sub) => {
1630
- const subType = unwrap(sub.type);
1631
- if (isLeaf(subType)) return [sub.name];
1632
- if (!isObjectType(subType)) return [];
1633
- const leaves = selectableFields(subType).filter((leaf) => isLeaf(unwrap(leaf.type)));
1634
- return leaves.length === 0 ? [] : [`${sub.name} { ${leaves.map((leaf) => leaf.name).join(" ")} }`];
1635
- });
1636
- return inner.length === 0 ? [] : [`${field.name} { ${inner.join(" ")} }`];
1637
- });
1638
- }
1639
- function fieldNamesOf(type) {
1640
- return isObjectType(type) ? Object.keys(type.getFields()) : [];
1641
- }
1642
- var UnknownFieldError = class extends Error {
1643
- field;
1644
- suggestions;
1645
- constructor(field, type, candidates = fieldNamesOf(type)) {
1646
- const names = candidates.filter((name) => !name.startsWith("__"));
1647
- const needle = field.toLowerCase();
1648
- const suggestions = names.filter((name) => {
1649
- const candidate = name.toLowerCase();
1650
- return candidate.includes(needle) || needle.includes(candidate);
1651
- });
1652
- super(`${type.name} has no field "${field}".`);
1653
- this.name = "UnknownFieldError";
1654
- this.field = field;
1655
- this.suggestions = suggestions.length > 0 ? suggestions : names;
1656
- }
1657
- };
1658
- function rootTypeOf(schema, kind) {
1659
- if (kind === "query") return schema.getQueryType();
1660
- if (kind === "mutation") return schema.getMutationType();
1661
- return schema.getSubscriptionType();
1662
- }
1663
- function buildQuery(schema, kind, fieldName, variables, options = {}) {
1664
- const rootType = rootTypeOf(schema, kind);
1665
- if (!rootType) throw new Error(`No ${kind} type in schema`);
1666
- const field = rootType.getFields()[fieldName];
1667
- if (!field) throw new Error(`Unknown ${kind} field: ${fieldName}`);
1668
- const returnType = unwrap(field.type);
1669
- const depth = effectiveDepth(returnType, options.depth ?? 0);
1670
- const exclude = new Set(options.exclude ?? []);
1671
- const wantsTotalCount = options.totalCount === true;
1672
- const allArgs = field.args;
1673
- const varDefsInner = allArgs.map((a) => `$${a.name}: ${a.type.toString()}`).join(", ");
1674
- const fieldArgsInner = allArgs.map((a) => `${a.name}: $${a.name}`).join(", ");
1675
- const varDefs = allArgs.length > 0 ? `(${varDefsInner})` : "";
1676
- const fieldArgs = allArgs.length > 0 ? `(${fieldArgsInner})` : "";
1677
- let selectionBody;
1678
- if (isLeaf(returnType)) {
1679
- selectionBody = ` ${fieldName}${fieldArgs}`;
1680
- } else if (isAbstractType(returnType)) {
1681
- const indent = " ";
1682
- const body = abstractSelections(returnType, schema, depth, exclude, "", wantsTotalCount, /* @__PURE__ */ new Set()).map((s) => `${indent}${s}`).join("\n");
1683
- selectionBody = ` ${fieldName}${fieldArgs} {
1684
- ${body}
1685
- }`;
1686
- } else {
1687
- let selections;
1688
- if (options.fields && options.fields.length > 0) {
1689
- selections = buildFieldsFromList(returnType, schema, options.fields, wantsTotalCount);
1690
- } else {
1691
- selections = buildSelections(returnType, schema, depth, exclude, "", wantsTotalCount, /* @__PURE__ */ new Set());
1692
- }
1693
- if (selections.length === 0) {
1694
- selectionBody = ` ${fieldName}${fieldArgs} {
1695
- __typename
1696
- }`;
1697
- } else {
1698
- const indent = " ";
1699
- const body = selections.map((s) => `${indent}${s}`).join("\n");
1700
- selectionBody = ` ${fieldName}${fieldArgs} {
1701
- ${body}
1702
- }`;
1703
- }
1704
- }
1705
- const opName = `${CLI_OPERATION_PREFIX}${ucfirst(fieldName)}`;
1706
- const query = `${kind} ${opName}${varDefs} {
1707
- ${selectionBody}
1708
- }`;
1709
- return { query, variables, fieldName };
1710
- }
1711
- function buildFieldsFromList(type, schema, requestedPaths, totalCount) {
1712
- if (!isObjectType(type)) return [];
1713
- const fields = type.getFields();
1714
- const page = deliveredPageField(type);
1715
- const fieldPaths = page ? requestedPaths.map((path9) => fields[path9.split(".")[0]] ? path9 : `${page.name}.${path9}`) : requestedPaths;
1716
- if (isConnection(type)) {
1717
- const nodesType = unwrap(fields.nodes.type);
1718
- const nodePaths = fieldPaths.filter((path9) => !isConnectionExtraPath(type, nodesType, path9));
1719
- const withId = isObjectType(nodesType) && nodesType.getFields().id && !nodePaths.includes("id");
1720
- const nodeSelections = buildFieldsFromList(
1721
- nodesType,
1722
- schema,
1723
- withId ? ["id", ...nodePaths] : nodePaths,
1724
- totalCount
1725
- );
1726
- return connectionSelections(type, nodeSelections, totalCount);
1727
- }
1728
- const lines = [];
1729
- const grouped = /* @__PURE__ */ new Map();
1730
- for (const fp of fieldPaths) {
1731
- const [top, ...rest] = fp.split(".");
1732
- if (!grouped.has(top)) grouped.set(top, []);
1733
- if (rest.length > 0) grouped.get(top).push(rest.join("."));
1734
- }
1735
- for (const [name, subPaths] of grouped) {
1736
- const field = fields[name];
1737
- if (!field) throw new UnknownFieldError(name, type);
1738
- const namedType = unwrap(field.type);
1739
- if (isLeaf(namedType)) {
1740
- lines.push(name);
1741
- } else if (isObjectType(namedType) && subPaths.length > 0) {
1742
- const subSelections = buildFieldsFromList(namedType, schema, subPaths, totalCount);
1743
- if (subSelections.length > 0) {
1744
- lines.push(`${fieldCall(name, field)} {`);
1745
- for (const sel of subSelections) lines.push(` ${sel}`);
1746
- lines.push(`}`);
1747
- }
1748
- } else if (isAbstractType(namedType)) {
1749
- lines.push(`${name} {`);
1750
- for (const sel of abstractFieldsFromList(namedType, schema, subPaths, totalCount)) lines.push(` ${sel}`);
1751
- lines.push(`}`);
1752
- }
1753
- }
1754
- return lines;
1755
- }
1756
- function abstractFieldsFromList(type, schema, subPaths, totalCount) {
1757
- const members = schema.getPossibleTypes(type);
1758
- if (subPaths.length === 0) {
1759
- return abstractSelections(type, schema, 0, /* @__PURE__ */ new Set(), "", totalCount, /* @__PURE__ */ new Set());
1760
- }
1761
- const lines = ["__typename"];
1762
- const claimed = /* @__PURE__ */ new Set();
1763
- for (const member of members) {
1764
- const known = subPaths.filter((fp) => Boolean(member.getFields()[fp.split(".")[0]]));
1765
- if (known.length === 0) continue;
1766
- for (const fp of known) claimed.add(fp);
1767
- lines.push(`... on ${member.name} {`);
1768
- for (const sel of buildFieldsFromList(member, schema, known, totalCount)) lines.push(` ${sel}`);
1769
- lines.push(`}`);
1770
- }
1771
- const unknown = subPaths.find((fp) => !claimed.has(fp));
1772
- if (unknown !== void 0) {
1773
- throw new UnknownFieldError(unknown.split(".")[0], type, members.flatMap(fieldNamesOf));
1774
- }
1775
- return lines;
1776
- }
1777
1384
 
1778
1385
  // src/lib/render.ts
1779
1386
  var INDENT = " ";
1780
- var CONNECTION_PLUMBING2 = /* @__PURE__ */ new Set([
1387
+ var CONNECTION_PLUMBING = /* @__PURE__ */ new Set([
1781
1388
  "edges",
1782
1389
  "nodes",
1783
1390
  "pageInfo",
@@ -1876,7 +1483,7 @@ function formatFooter(connection) {
1876
1483
  return more ? `${counted} \u2014 more available, pass --after ${connection.pageInfo?.endCursor}` : counted;
1877
1484
  }
1878
1485
  function formatConnectionExtras(connection) {
1879
- return Object.entries(connection).filter(([key, value]) => !CONNECTION_PLUMBING2.has(key) && value != null).map(
1486
+ return Object.entries(connection).filter(([key, value]) => !CONNECTION_PLUMBING.has(key) && value != null).map(
1880
1487
  ([key, value]) => isRecord(value) ? `${key}
1881
1488
  ${formatRecord(value, INDENT)}` : `${key} ${formatScalar(value)}`
1882
1489
  );
@@ -1905,12 +1512,6 @@ function formatResult(result) {
1905
1512
  var CONTEXT_FIELDS = {
1906
1513
  companyId: "companyId"
1907
1514
  };
1908
- var SKIP_FIELDS = /* @__PURE__ */ new Set(["node", "nodes", "id", "_entities", "_service"]);
1909
- function unwrap2(type) {
1910
- if (isNonNullType2(type)) return unwrap2(type.ofType);
1911
- if (isListType2(type)) return unwrap2(type.ofType);
1912
- return type;
1913
- }
1914
1515
  var RESERVED_FLAGS = /* @__PURE__ */ new Set(["version", "help", "endpoint", "company", "json", "color", "no-color"]);
1915
1516
  function flagNameFor(fieldName, argName) {
1916
1517
  const name = kebab(argName);
@@ -1922,40 +1523,26 @@ function optionKey(flagName) {
1922
1523
  function kebab(s) {
1923
1524
  return s.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
1924
1525
  }
1925
- function getInputFields(field) {
1926
- if (field.args.length !== 1) return null;
1927
- const arg = field.args[0];
1928
- if (arg.name !== "input") return null;
1929
- const argType = unwrap2(arg.type);
1930
- if (!argType || !isInputObjectType(argType)) return null;
1931
- const fields = argType.getFields();
1932
- return Object.entries(fields).map(([name, f]) => ({
1933
- name,
1934
- type: f.type,
1935
- required: isNonNullType2(f.type),
1936
- description: f.description
1937
- }));
1938
- }
1939
1526
  function renderType(type) {
1940
- if (isNonNullType2(type)) return `${renderType(type.ofType)}!`;
1941
- if (isListType2(type)) return `[${renderType(type.ofType)}]`;
1527
+ if (isNonNullType(type)) return `${renderType(type.ofType)}!`;
1528
+ if (isListType(type)) return `[${renderType(type.ofType)}]`;
1942
1529
  return type.name;
1943
1530
  }
1944
1531
  function isStructuredInput(type) {
1945
- if (isNonNullType2(type)) return isStructuredInput(type.ofType);
1946
- if (isListType2(type)) return true;
1532
+ if (isNonNullType(type)) return isStructuredInput(type.ofType);
1533
+ if (isListType(type)) return true;
1947
1534
  return isInputObjectType(type);
1948
1535
  }
1949
1536
  function enumListOf(type) {
1950
- const listless = isNonNullType2(type) ? type.ofType : type;
1951
- if (!isListType2(listless)) return null;
1952
- const inner = unwrap2(listless.ofType);
1953
- return isEnumType2(inner) ? inner : null;
1537
+ const listless = isNonNullType(type) ? type.ofType : type;
1538
+ if (!isListType(listless)) return null;
1539
+ const inner = unwrap(listless.ofType);
1540
+ return isEnumType(inner) ? inner : null;
1954
1541
  }
1955
1542
  function enumOf(type) {
1956
- const listless = isNonNullType2(type) ? type.ofType : type;
1957
- if (isListType2(listless)) return null;
1958
- return isEnumType2(listless) ? listless : null;
1543
+ const listless = isNonNullType(type) ? type.ofType : type;
1544
+ if (isListType(listless)) return null;
1545
+ return isEnumType(listless) ? listless : null;
1959
1546
  }
1960
1547
  function commonPrefix(values) {
1961
1548
  if (values.length < 2) return "";
@@ -2004,7 +1591,7 @@ function coerceValue(raw, type, flagName) {
2004
1591
  if (enumList && !raw.trim().startsWith("[")) return coerceEnumList(raw, enumList, flagName);
2005
1592
  const enumValue = enumOf(type);
2006
1593
  if (enumValue) return coerceEnum(raw, enumValue, flagName);
2007
- const typeName = unwrap2(type).name;
1594
+ const typeName = unwrap(type).name;
2008
1595
  if (isStructuredInput(type) || typeName === "JSON" && /^\s*[[{]/.test(raw)) {
2009
1596
  try {
2010
1597
  return JSON.parse(raw);
@@ -2038,14 +1625,14 @@ function describeStructuredType(named) {
2038
1625
  const parts = fields.map((f) => `${f.name}: ${renderType(f.type)}`);
2039
1626
  return `{ ${parts.join(", ")} }`;
2040
1627
  }
2041
- if (isEnumType2(named)) {
1628
+ if (isEnumType(named)) {
2042
1629
  const values = named.getValues().map((v) => v.name);
2043
1630
  return `one of: ${values.join(" | ")}`;
2044
1631
  }
2045
1632
  return null;
2046
1633
  }
2047
1634
  function isInspectable(named) {
2048
- return isInputObjectType(named) || isEnumType2(named) || isObjectType2(named);
1635
+ return isInputObjectType(named) || isEnumType(named) || isObjectType(named);
2049
1636
  }
2050
1637
  function oneLineDescription(text) {
2051
1638
  return (text ?? "").replace(/\s+/g, " ").trim();
@@ -2067,7 +1654,7 @@ function formatTypeInspection(schema, typeName) {
2067
1654
  lines.push(note ? ` ${signature.padEnd(width)} ${note}` : ` ${signature}`);
2068
1655
  }
2069
1656
  };
2070
- if (isInputObjectType(named) || isObjectType2(named)) {
1657
+ if (isInputObjectType(named) || isObjectType(named)) {
2071
1658
  lines.push(header(isInputObjectType(named) ? "input" : "type"));
2072
1659
  pushFields(
2073
1660
  Object.values(named.getFields()).map((f) => ({
@@ -2076,22 +1663,22 @@ function formatTypeInspection(schema, typeName) {
2076
1663
  description: f.description
2077
1664
  }))
2078
1665
  );
2079
- } else if (isEnumType2(named)) {
1666
+ } else if (isEnumType(named)) {
2080
1667
  lines.push(header("enum"));
2081
1668
  for (const value of named.getValues()) {
2082
1669
  const note = oneLineDescription(value.description);
2083
1670
  lines.push(note ? ` ${value.name.padEnd(20)} ${note}` : ` ${value.name}`);
2084
1671
  }
2085
- } else if (isScalarType2(named)) {
1672
+ } else if (isScalarType(named)) {
2086
1673
  lines.push(header("scalar"));
2087
1674
  lines.push(" (scalar \u2014 pass a plain value)");
2088
1675
  } else {
2089
1676
  lines.push(header(""));
2090
1677
  }
2091
1678
  const nested = /* @__PURE__ */ new Set();
2092
- if (isInputObjectType(named) || isObjectType2(named)) {
1679
+ if (isInputObjectType(named) || isObjectType(named)) {
2093
1680
  for (const field of Object.values(named.getFields())) {
2094
- const fieldType = unwrap2(field.type);
1681
+ const fieldType = unwrap(field.type);
2095
1682
  if (isInspectable(fieldType) && fieldType.name !== named.name) nested.add(fieldType.name);
2096
1683
  }
2097
1684
  }
@@ -2111,10 +1698,10 @@ function describeArg(arg) {
2111
1698
  parts.push(
2112
1699
  enumList ? `${typeSig} (comma-separated, all, or none)` : isStructuredInput(arg.type) ? `${typeSig} (JSON)` : typeSig
2113
1700
  );
2114
- const named = unwrap2(arg.type);
1701
+ const named = unwrap(arg.type);
2115
1702
  const shape = describeStructuredType(named);
2116
1703
  if (shape) parts.push(shape);
2117
- if (isInputObjectType(named) || isEnumType2(named)) {
1704
+ if (isInputObjectType(named) || isEnumType(named)) {
2118
1705
  parts.push(`details: sl schema inspect ${named.name}`);
2119
1706
  }
2120
1707
  return parts.join(" \u2014 ");
@@ -2122,63 +1709,10 @@ function describeArg(arg) {
2122
1709
  var DEFAULT_SUBSCRIPTION_TIMEOUT_SECONDS = 300;
2123
1710
  var DEFAULT_WAIT_SECONDS = 120;
2124
1711
  var TIMED_OUT_EXIT_CODE = 5;
2125
- function supersededBy(field, siblings) {
2126
- const replacement = field.deprecationReason?.match(/`(\w+)`/)?.[1];
2127
- if (!replacement || SKIP_FIELDS.has(replacement)) return null;
2128
- const sibling = siblings[replacement];
2129
- return sibling && !sibling.deprecationReason ? replacement : null;
2130
- }
2131
- function argumentNames(field) {
2132
- return new Set((getInputFields(field) ?? field.args).map((a) => a.name));
2133
- }
2134
- var RESULT_OF_MUTATION = /(?:result|outcome) of an? `(\w+)` call|then call `(\w+)`/;
2135
- function resultSubscriptions(schema) {
2136
- const pairs = /* @__PURE__ */ new Map();
2137
- const mutations = schema.getMutationType()?.getFields() ?? {};
2138
- for (const [name, field] of Object.entries(schema.getSubscriptionType()?.getFields() ?? {})) {
2139
- const match = field.description?.match(RESULT_OF_MUTATION);
2140
- const mutation = match?.[1] ?? match?.[2];
2141
- if (!mutation || !mutations[mutation]) continue;
2142
- const mutationArguments = argumentNames(mutations[mutation]);
2143
- if (!field.args.some((a) => a.name === "externalId") || !mutationArguments.has("externalId")) continue;
2144
- if (field.args.some((a) => isNonNullType2(a.type) && !mutationArguments.has(a.name))) continue;
2145
- pairs.set(mutation, name);
2146
- }
2147
- return pairs;
2148
- }
2149
- function subscriptionVariablesFor(schema, subscription, mutationArguments, externalId) {
2150
- const variables = {};
2151
- for (const arg of schema.getSubscriptionType()?.getFields()[subscription]?.args ?? []) {
2152
- if (mutationArguments[arg.name] !== void 0) variables[arg.name] = mutationArguments[arg.name];
2153
- }
2154
- return { ...variables, externalId };
2155
- }
2156
- function isRecord2(value) {
2157
- return typeof value === "object" && value !== null;
2158
- }
2159
- function isStillFilling(result) {
2160
- return isRecord2(result) && result.status === "FILLING";
2161
- }
2162
- var PAGE_STATUS_FIELD = "status";
2163
- function deliversFillingPages(schema, subscriptionName) {
2164
- const field = schema.getSubscriptionType()?.getFields()[subscriptionName];
2165
- const returnType = field ? unwrap2(field.type) : null;
2166
- const status = returnType && isObjectType2(returnType) ? returnType.getFields()[PAGE_STATUS_FIELD] : void 0;
2167
- const statusType = status ? unwrap2(status.type) : null;
2168
- return Boolean(statusType && isEnumType2(statusType) && statusType.getValue("FILLING"));
2169
- }
2170
1712
  function shellWord(value) {
2171
1713
  if (/^[\w.:/@=+-]+$/.test(value)) return value;
2172
1714
  return "'" + value.replace(/'/g, "'\\''") + "'";
2173
1715
  }
2174
- function nextPageCursor(result) {
2175
- if (!isRecord2(result)) return null;
2176
- for (const value of Object.values(result)) {
2177
- const pageInfo = isRecord2(value) && isRecord2(value.pageInfo) ? value.pageInfo : null;
2178
- if (pageInfo?.hasNextPage === true && typeof pageInfo.endCursor === "string") return pageInfo.endCursor;
2179
- }
2180
- return null;
2181
- }
2182
1716
  function nextPageHint(commandName, externalId, page, result) {
2183
1717
  const cursor = nextPageCursor(result);
2184
1718
  if (!cursor) return null;
@@ -2211,57 +1745,39 @@ function secondsOption(raw, fallback, flag) {
2211
1745
  }
2212
1746
  return seconds;
2213
1747
  }
2214
- async function listen(query, variables, requestOptions, seconds) {
2215
- const controller = new AbortController();
2216
- let expired = false;
2217
- const timer = setTimeout(() => {
2218
- expired = true;
2219
- controller.abort();
2220
- }, seconds * 1e3);
2221
- const open = () => graphqlSubscribe(query, variables, { ...requestOptions, signal: controller.signal });
2222
- const first = await open();
2223
- async function* events() {
2224
- let current = first;
2225
- for (; ; ) {
2226
- try {
2227
- yield* current.events;
2228
- return;
2229
- } catch (err) {
2230
- if (expired || !isDroppedStream(err)) throw err;
2231
- current = await open();
2232
- }
2233
- }
2234
- }
1748
+ function routerClientFor(requestOptions) {
1749
+ const openSubscription = async (query, variables, signal) => (await graphqlSubscribe(query, variables, { ...requestOptions, signal })).events;
2235
1750
  return {
2236
- events: events(),
2237
- stop: () => {
2238
- clearTimeout(timer);
2239
- controller.abort();
2240
- },
2241
- timedOut: () => expired
1751
+ execute: (query, variables) => graphqlRaw(query, variables, requestOptions),
1752
+ openSubscription,
1753
+ async *subscribe(query, variables, signal) {
1754
+ yield* await openSubscription(query, variables, signal);
1755
+ }
2242
1756
  };
2243
1757
  }
2244
- function isAbort(err) {
2245
- return err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError");
1758
+ function reportUnknownField(buildError) {
1759
+ error(buildError.message);
1760
+ hint(`Did you mean: ${buildError.suggestions.join(", ")}?`);
1761
+ process.exit(2);
2246
1762
  }
2247
- function isDroppedStream(err) {
2248
- if (!(err instanceof Error) || isAbort(err)) return false;
2249
- const code = err.cause?.code;
2250
- return err.message === "terminated" || code === "UND_ERR_SOCKET" || code === "ECONNRESET";
2251
- }
2252
- function buildCommand(schema, fieldName, kind, description, service, resultSubscription, resultCommand) {
2253
- const rootType = rootTypeOf(schema, kind);
2254
- if (!rootType) throw new Error(`No ${kind} type in schema`);
2255
- const field = rootType.getFields()[fieldName];
2256
- if (!field) throw new Error(`Unknown ${kind} field: ${fieldName}`);
2257
- const inputFields = getInputFields(field);
2258
- const useInputWrapper = inputFields != null;
2259
- const cliArgs = useInputWrapper ? inputFields : field.args.map((a) => ({
2260
- name: a.name,
2261
- type: a.type,
2262
- required: isNonNullType2(a.type),
2263
- description: a.description
2264
- }));
1763
+ function reportingUnknownField(build) {
1764
+ try {
1765
+ return build();
1766
+ } catch (buildError) {
1767
+ if (!(buildError instanceof UnknownFieldError)) throw buildError;
1768
+ return reportUnknownField(buildError);
1769
+ }
1770
+ }
1771
+ function buildCommand(schema, spec, resultCommand) {
1772
+ const {
1773
+ fieldName,
1774
+ kind,
1775
+ description,
1776
+ service,
1777
+ resultSubscription,
1778
+ args: cliArgs,
1779
+ inputWrapper: useInputWrapper
1780
+ } = spec;
2265
1781
  const cmd = new Command3(kebab(fieldName)).description(description);
2266
1782
  const requiresCompanyId = cliArgs.some((a) => a.name === "companyId" && a.required);
2267
1783
  for (const a of cliArgs) {
@@ -2327,31 +1843,25 @@ function buildCommand(schema, fieldName, kind, description, service, resultSubsc
2327
1843
  }
2328
1844
  return out;
2329
1845
  };
2330
- const variables = useInputWrapper ? { input: collectArgs() } : collectArgs();
1846
+ const args = collectArgs();
2331
1847
  const selection = {
2332
1848
  depth: opts.depth,
2333
1849
  fields: opts.fields?.split(","),
2334
1850
  exclude: opts.exclude?.split(","),
2335
1851
  totalCount: opts.totalCount === true
2336
1852
  };
2337
- const build2 = (buildKind, buildField, buildVariables, select = true) => {
2338
- try {
2339
- return buildQuery(schema, buildKind, buildField, buildVariables, select ? selection : {});
2340
- } catch (buildError) {
2341
- if (!(buildError instanceof UnknownFieldError)) throw buildError;
2342
- error(buildError.message);
2343
- hint(`Did you mean: ${buildError.suggestions.join(", ")}?`);
2344
- process.exit(2);
2345
- }
2346
- };
2347
1853
  const requestOptions = { endpoint: opts.endpoint, company: acting, companyId: actingId, subgraph: service };
1854
+ const client = routerClientFor(requestOptions);
2348
1855
  if (kind === "subscription") {
2349
1856
  const seconds = secondsOption(opts.timeout, DEFAULT_SUBSCRIPTION_TIMEOUT_SECONDS, "--timeout");
2350
- const { query: query2, fieldName: fName2 } = build2("subscription", fieldName, variables);
2351
- const stream = await listen(query2, variables, requestOptions, seconds);
1857
+ const variables = useInputWrapper ? { input: args } : args;
1858
+ const { query, fieldName: fName } = reportingUnknownField(
1859
+ () => buildQuery(schema, "subscription", fieldName, variables, selection)
1860
+ );
1861
+ const stream = await listen(client, query, variables, seconds);
2352
1862
  try {
2353
- for await (const data2 of stream.events) {
2354
- printResult(fieldName, data2[fName2], opts);
1863
+ for await (const data of stream.events) {
1864
+ printResult(fieldName, data[fName], opts);
2355
1865
  if (opts.once) break;
2356
1866
  }
2357
1867
  } catch (err) {
@@ -2363,61 +1873,47 @@ function buildCommand(schema, fieldName, kind, description, service, resultSubsc
2363
1873
  }
2364
1874
  return;
2365
1875
  }
1876
+ const run = async (waitSeconds) => {
1877
+ try {
1878
+ return await runOperation({ schema, spec, args, selection, client, waitSeconds });
1879
+ } catch (runError) {
1880
+ if (runError instanceof UnknownFieldError) reportUnknownField(runError);
1881
+ if (runError instanceof ResultNotDeliveredError) {
1882
+ warn(runError.message);
1883
+ process.exit(1);
1884
+ }
1885
+ throw runError;
1886
+ }
1887
+ };
2366
1888
  if (waiting && resultSubscription) {
2367
1889
  const seconds = secondsOption(opts.wait, DEFAULT_WAIT_SECONDS, "--wait");
2368
1890
  const externalId = opts.externalId;
2369
- const mutationArguments = useInputWrapper ? variables.input : variables;
2370
- const subscriptionVariables = subscriptionVariablesFor(schema, resultSubscription, mutationArguments, externalId);
2371
- if (selection.fields && !selection.fields.includes(PAGE_STATUS_FIELD) && deliversFillingPages(schema, resultSubscription)) {
2372
- selection.fields = [...selection.fields, PAGE_STATUS_FIELD];
1891
+ const result2 = await run(seconds);
1892
+ if (result2.state === "filling" && result2.ended === "timeout") {
1893
+ printResult(resultSubscription, result2.data, opts);
1894
+ warn(`Still filling after ${seconds}s: what is above may still change.`);
1895
+ hint(`Wait longer with --wait <seconds>; its external id is ${externalId}.`);
1896
+ process.exit(TIMED_OUT_EXIT_CODE);
2373
1897
  }
2374
- const { query: subscriptionQuery, fieldName: subscriptionField } = build2(
2375
- "subscription",
2376
- resultSubscription,
2377
- subscriptionVariables
2378
- );
2379
- const stream = await listen(subscriptionQuery, subscriptionVariables, requestOptions, seconds);
2380
- let delivered;
2381
- try {
2382
- const { query: query2 } = build2(kind, fieldName, variables, false);
2383
- await graphqlRaw(query2, variables, requestOptions);
2384
- for await (const data2 of stream.events) {
2385
- delivered = data2[subscriptionField];
2386
- if (!isStillFilling(delivered)) break;
2387
- }
2388
- if (delivered === void 0) {
2389
- warn(`${resultSubscription} closed without delivering a result.`);
2390
- process.exit(1);
2391
- }
2392
- printResult(resultSubscription, delivered, opts);
2393
- const pageArgument = useInputWrapper ? variables.input.page : variables.page;
2394
- const takesPage = cliArgs.some((a) => a.name === "page");
2395
- const pageHint = takesPage ? nextPageHint(
2396
- invocation(service, this.name()),
2397
- externalId,
2398
- pageArgument,
2399
- delivered
2400
- ) : null;
2401
- if (pageHint) hint(pageHint);
2402
- return;
2403
- } catch (err) {
2404
- if (!isAbort(err) || !stream.timedOut()) throw err;
2405
- if (delivered !== void 0) {
2406
- printResult(resultSubscription, delivered, opts);
2407
- warn(`Still filling after ${seconds}s: what is above may still change.`);
2408
- hint(`Wait longer with --wait <seconds>; its external id is ${externalId}.`);
2409
- process.exit(TIMED_OUT_EXIT_CODE);
2410
- }
1898
+ if (result2.state === "pending") {
2411
1899
  warn(`No result within ${seconds}s. The request was accepted and may still complete.`);
2412
1900
  hint(`Wait longer with --wait <seconds>, or read the result later; its external id is ${externalId}.`);
2413
1901
  process.exit(TIMED_OUT_EXIT_CODE);
2414
- } finally {
2415
- stream.stop();
2416
1902
  }
1903
+ const delivered = result2.data;
1904
+ printResult(resultSubscription, delivered, opts);
1905
+ const takesPage = cliArgs.some((a) => a.name === "page");
1906
+ const pageHint = takesPage ? nextPageHint(
1907
+ invocation(service, this.name()),
1908
+ externalId,
1909
+ args.page,
1910
+ delivered
1911
+ ) : null;
1912
+ if (pageHint) hint(pageHint);
1913
+ return;
2417
1914
  }
2418
- const { query, fieldName: fName } = build2(kind, fieldName, variables);
2419
- const data = await graphqlRaw(query, variables, requestOptions);
2420
- printResult(fieldName, data[fName], opts);
1915
+ const result = await run();
1916
+ printResult(fieldName, "data" in result ? result.data : void 0, opts);
2421
1917
  if (generatedExternalId && resultCommand) {
2422
1918
  hint(`Its result arrives on sl ${resultCommand} --external-id ${String(opts.externalId)}, or pass --wait.`);
2423
1919
  } else if (generatedExternalId && resultSubscription) {
@@ -2426,39 +1922,6 @@ function buildCommand(schema, fieldName, kind, description, service, resultSubsc
2426
1922
  });
2427
1923
  return cmd;
2428
1924
  }
2429
- function deriveServiceMap(schema, fieldServices) {
2430
- const map = /* @__PURE__ */ new Map();
2431
- function ensure(service) {
2432
- if (!map.has(service)) map.set(service, { queries: [], mutations: [], subscriptions: [] });
2433
- return map.get(service);
2434
- }
2435
- const rootTypes = [
2436
- { kind: "queries", type: schema.getQueryType() },
2437
- { kind: "mutations", type: schema.getMutationType() },
2438
- { kind: "subscriptions", type: schema.getSubscriptionType() }
2439
- ];
2440
- for (const { kind, type } of rootTypes) {
2441
- if (!type) continue;
2442
- const services = fieldServices.get(type.name);
2443
- if (!services) continue;
2444
- const fields = type.getFields();
2445
- for (const [fieldName, field] of Object.entries(fields)) {
2446
- if (SKIP_FIELDS.has(fieldName) || fieldName.startsWith("__")) continue;
2447
- if (supersededBy(field, fields)) continue;
2448
- const returnType = unwrap2(field.type);
2449
- if (isInterfaceType(returnType) || isUnionType(returnType)) continue;
2450
- const service = services.get(fieldName);
2451
- if (!service) continue;
2452
- ensure(service)[kind].push({ fieldName, description: field.description ?? "" });
2453
- }
2454
- }
2455
- for (const entry of map.values()) {
2456
- entry.queries.sort((a, b) => a.fieldName.localeCompare(b.fieldName));
2457
- entry.mutations.sort((a, b) => a.fieldName.localeCompare(b.fieldName));
2458
- entry.subscriptions.sort((a, b) => a.fieldName.localeCompare(b.fieldName));
2459
- }
2460
- return map;
2461
- }
2462
1925
  function describeScopes(scopes) {
2463
1926
  return scopes.map((alternative) => alternative.join(" + ")).join(" or ");
2464
1927
  }
@@ -2485,45 +1948,36 @@ function legacyTopLevelCommands(schema, fieldServices, fieldScopes = /* @__PURE_
2485
1948
  return buildOperationCommands(schema, fieldServices, fieldScopes).filter((operation) => operation.service === LEGACY_TOP_LEVEL_SERVICE).map((operation) => operation.command);
2486
1949
  }
2487
1950
  function buildOperationCommands(schema, fieldServices, fieldScopes = /* @__PURE__ */ new Map()) {
2488
- const serviceMap = deriveServiceMap(schema, fieldServices);
2489
- const rootTypeNames = {
2490
- query: schema.getQueryType()?.name,
2491
- mutation: schema.getMutationType()?.name,
2492
- subscription: schema.getSubscriptionType()?.name
2493
- };
2494
- const pairs = resultSubscriptions(schema);
1951
+ const specs = listOperations({ schema, fieldServices, fieldScopes, services: /* @__PURE__ */ new Set() });
1952
+ const nameCounts = /* @__PURE__ */ new Map();
1953
+ const exposedSubscriptions = /* @__PURE__ */ new Set();
1954
+ for (const spec of specs) {
1955
+ const key = `${spec.service}/${spec.fieldName}`;
1956
+ nameCounts.set(key, (nameCounts.get(key) ?? 0) + 1);
1957
+ if (spec.kind === "subscription") exposedSubscriptions.add(key);
1958
+ }
2495
1959
  const operations = [];
2496
- for (const [service, entry] of serviceMap) {
2497
- const nameCounts = /* @__PURE__ */ new Map();
2498
- for (const op of [...entry.queries, ...entry.mutations, ...entry.subscriptions]) {
2499
- nameCounts.set(op.fieldName, (nameCounts.get(op.fieldName) ?? 0) + 1);
2500
- }
2501
- const exposedSubscriptions = new Set(entry.subscriptions.map((op) => op.fieldName));
2502
- const kinds = [
2503
- { kind: "query", ops: entry.queries },
2504
- { kind: "mutation", ops: entry.mutations },
2505
- { kind: "subscription", ops: entry.subscriptions }
2506
- ];
2507
- for (const { kind, ops } of kinds) {
2508
- for (const op of ops) {
2509
- try {
2510
- const paired = kind === "mutation" ? pairs.get(op.fieldName) : void 0;
2511
- const resultCommand = paired && exposedSubscriptions.has(paired) ? invocation(service, kebab(paired)) : void 0;
2512
- const command = buildCommand(schema, op.fieldName, kind, op.description, service, paired, resultCommand);
2513
- if ((nameCounts.get(op.fieldName) ?? 0) > 1) {
2514
- command.name(`${kebab(op.fieldName)}-${kind}`);
2515
- }
2516
- const rootTypeName = rootTypeNames[kind];
2517
- const scopes = rootTypeName ? fieldScopes.get(rootTypeName)?.get(op.fieldName) : void 0;
2518
- if (scopes) {
2519
- command.description(`Privileged: requires ${describeScopes(scopes)}.
1960
+ for (const spec of specs) {
1961
+ try {
1962
+ const paired = spec.resultSubscription;
1963
+ const resultCommand = paired && exposedSubscriptions.has(`${spec.service}/${paired}`) ? invocation(spec.service, kebab(paired)) : void 0;
1964
+ const command = buildCommand(schema, spec, resultCommand);
1965
+ if ((nameCounts.get(`${spec.service}/${spec.fieldName}`) ?? 0) > 1) {
1966
+ command.name(`${kebab(spec.fieldName)}-${spec.kind}`);
1967
+ }
1968
+ if (spec.scopes) {
1969
+ command.description(`Privileged: requires ${describeScopes(spec.scopes)}.
2520
1970
 
2521
1971
  ${command.description()}`);
2522
- }
2523
- operations.push({ command, fieldName: op.fieldName, kind, service, ...scopes ? { scopes } : {} });
2524
- } catch {
2525
- }
2526
1972
  }
1973
+ operations.push({
1974
+ command,
1975
+ fieldName: spec.fieldName,
1976
+ kind: spec.kind,
1977
+ service: spec.service,
1978
+ ...spec.scopes ? { scopes: spec.scopes } : {}
1979
+ });
1980
+ } catch {
2527
1981
  }
2528
1982
  }
2529
1983
  return operations.sort((a, b) => a.command.name().localeCompare(b.command.name()));
@@ -3324,7 +2778,6 @@ import { createHash } from "crypto";
3324
2778
  import fs8 from "fs";
3325
2779
  import os6 from "os";
3326
2780
  import path8 from "path";
3327
- import { buildClientSchema, getIntrospectionQuery } from "graphql";
3328
2781
  var CACHE_DIR = path8.join(os6.homedir(), ".sortlist");
3329
2782
  var CACHE_PATH = path8.join(CACHE_DIR, "schema.json");
3330
2783
  var CACHE_TTL_MS = 60 * 60 * 1e3;
@@ -3362,66 +2815,6 @@ function writeCache(endpoint, token, introspection, raw) {
3362
2815
  } catch {
3363
2816
  }
3364
2817
  }
3365
- async function fetchIntrospection(endpoint, token) {
3366
- const headers = baseRequestHeaders();
3367
- if (token) headers["Authorization"] = `Bearer ${token}`;
3368
- const res = await fetch(endpoint, {
3369
- method: "POST",
3370
- headers,
3371
- body: JSON.stringify({ query: getIntrospectionQuery() })
3372
- });
3373
- if (!res.ok) {
3374
- throw new Error(`Introspection failed: HTTP ${res.status} ${res.statusText}`);
3375
- }
3376
- const json = await res.json();
3377
- if (json.errors?.length) {
3378
- throw new Error(`Introspection errors: ${json.errors.map((e) => e.message).join(", ")}`);
3379
- }
3380
- if (!json.data) {
3381
- throw new Error("Introspection returned no data");
3382
- }
3383
- return { introspection: json.data, raw: json.data };
3384
- }
3385
- var CLI_TAG = "cli";
3386
- function isTaggedForCli(field) {
3387
- return field.appliedDirectives?.some(
3388
- (d) => d.name === "tag" && d.args.some((a) => a.name === "name" && a.value === CLI_TAG)
3389
- ) ?? false;
3390
- }
3391
- function requiredScopes(field) {
3392
- const value = field.appliedDirectives?.find((directive) => directive.name === "requiresScopes")?.args.find((arg) => arg.name === "scopes")?.value;
3393
- const parsed = typeof value === "string" ? JSON.parse(value) : value;
3394
- if (!Array.isArray(parsed)) return void 0;
3395
- return parsed.filter(Array.isArray).map((alternative) => alternative.map(String));
3396
- }
3397
- function parseIntrospection(raw) {
3398
- const fieldServices = /* @__PURE__ */ new Map();
3399
- const fieldScopes = /* @__PURE__ */ new Map();
3400
- const services = /* @__PURE__ */ new Set();
3401
- for (const type of raw.__schema.types ?? []) {
3402
- if (!type.fields?.length) continue;
3403
- let fieldMap = null;
3404
- let scopeMap = null;
3405
- for (const field of type.fields) {
3406
- const directive = field.appliedDirectives?.find((d) => d.name === "join__field");
3407
- if (!directive) continue;
3408
- const graphArg = directive.args.find((a) => a.name === "graph");
3409
- if (!graphArg || typeof graphArg.value !== "string") continue;
3410
- services.add(graphArg.value);
3411
- if (!isTaggedForCli(field)) continue;
3412
- fieldMap ??= /* @__PURE__ */ new Map();
3413
- fieldMap.set(field.name, graphArg.value);
3414
- const scopes = requiredScopes(field);
3415
- if (scopes?.length) {
3416
- scopeMap ??= /* @__PURE__ */ new Map();
3417
- scopeMap.set(field.name, scopes);
3418
- }
3419
- }
3420
- if (fieldMap) fieldServices.set(type.name, fieldMap);
3421
- if (scopeMap) fieldScopes.set(type.name, scopeMap);
3422
- }
3423
- return { fieldServices, fieldScopes, services };
3424
- }
3425
2818
  async function currentAccessToken() {
3426
2819
  const machine = clientCredentials();
3427
2820
  if (machine) return fetchClientCredentialsToken(machine);
@@ -3433,15 +2826,15 @@ async function getIntrospectedSchema(endpointOverride2) {
3433
2826
  const token = await currentAccessToken();
3434
2827
  const fromCache = readCache(endpoint, token);
3435
2828
  if (fromCache) {
3436
- const usable = build(fromCache.introspection, fromCache.raw);
2829
+ const usable = buildIntrospected(fromCache.introspection, fromCache.raw);
3437
2830
  if (usable) {
3438
2831
  cached2 = usable;
3439
2832
  return cached2;
3440
2833
  }
3441
2834
  discardCache();
3442
2835
  }
3443
- const { introspection, raw } = await fetchIntrospection(endpoint, token);
3444
- const built = build(introspection, raw);
2836
+ const { introspection, raw } = await fetchIntrospection(endpoint, token, void 0, baseRequestHeaders());
2837
+ const built = buildIntrospected(introspection, raw);
3445
2838
  if (!built) {
3446
2839
  throw new Error(
3447
2840
  "The endpoint returned an introspection result this CLI could not build a schema from. Nothing was cached; retry, and check that every subgraph is up."
@@ -3451,14 +2844,6 @@ async function getIntrospectedSchema(endpointOverride2) {
3451
2844
  cached2 = built;
3452
2845
  return cached2;
3453
2846
  }
3454
- function build(introspection, raw) {
3455
- try {
3456
- const { fieldServices, fieldScopes, services } = parseIntrospection(raw);
3457
- return { schema: buildClientSchema(introspection), fieldServices, fieldScopes, services };
3458
- } catch {
3459
- return null;
3460
- }
3461
- }
3462
2847
  function discardCache() {
3463
2848
  try {
3464
2849
  fs8.unlinkSync(CACHE_PATH);
@@ -3470,8 +2855,8 @@ async function refreshSchema(endpointOverride2) {
3470
2855
  discardCache();
3471
2856
  const endpoint = getEndpoint(endpointOverride2);
3472
2857
  const token = await currentAccessToken();
3473
- const { introspection, raw } = await fetchIntrospection(endpoint, token);
3474
- const built = build(introspection, raw);
2858
+ const { introspection, raw } = await fetchIntrospection(endpoint, token, void 0, baseRequestHeaders());
2859
+ const built = buildIntrospected(introspection, raw);
3475
2860
  if (!built) {
3476
2861
  throw new Error(
3477
2862
  "The endpoint returned an introspection result this CLI could not build a schema from. Nothing was cached; retry, and check that every subgraph is up."