@executor-js/plugin-graphql 1.5.22 → 2.0.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.
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  addGraphqlIntegrationOptimistic,
3
3
  graphqlAuthMethodInputsFromPlacements
4
- } from "./chunk-VSLIDDNK.js";
5
- import "./chunk-732HGFSH.js";
4
+ } from "./chunk-ZUGWBXOU.js";
5
+ import "./chunk-JTWENVHO.js";
6
6
 
7
7
  // src/react/AddGraphqlSource.tsx
8
8
  import { useCallback, useMemo, useState } from "react";
@@ -20,7 +20,6 @@ import {
20
20
  useAuthMethodList
21
21
  } from "@executor-js/react/components/auth-method-list-editor";
22
22
  import { FloatActions } from "@executor-js/react/components/float-actions";
23
- import { Spinner } from "@executor-js/react/components/spinner";
24
23
  import {
25
24
  addIntegrationErrorMessage,
26
25
  FormErrorAlert,
@@ -167,14 +166,11 @@ function AddGraphqlSource(props) {
167
166
  addError && /* @__PURE__ */ jsx2(FormErrorAlert, { message: addError }),
168
167
  /* @__PURE__ */ jsxs2(FloatActions, { children: [
169
168
  /* @__PURE__ */ jsx2(Button, { variant: "ghost", onClick: () => props.onCancel(), disabled: adding, children: "Cancel" }),
170
- /* @__PURE__ */ jsxs2(Button, { onClick: () => void handleAdd(), disabled: !canAdd, children: [
171
- adding && /* @__PURE__ */ jsx2(Spinner, { className: "size-3.5" }),
172
- adding ? "Adding..." : "Add source"
173
- ] })
169
+ /* @__PURE__ */ jsx2(Button, { onClick: () => void handleAdd(), disabled: !canAdd, loading: adding, children: "Add source" })
174
170
  ] })
175
171
  ] });
176
172
  }
177
173
  export {
178
174
  AddGraphqlSource as default
179
175
  };
180
- //# sourceMappingURL=AddGraphqlSource-B7ZOZ7WM.js.map
176
+ //# sourceMappingURL=AddGraphqlSource-WZIUR2NX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/react/AddGraphqlSource.tsx","../src/react/GraphqlSourceFields.tsx"],"sourcesContent":["import { useCallback, useMemo, useState } from \"react\";\nimport { useAtomSet } from \"@effect/atom-react\";\nimport * as Exit from \"effect/Exit\";\n\nimport { integrationWriteKeys } from \"@executor-js/react/api/reactivity-keys\";\nimport {\n integrationDisplayNameFromUrl,\n slugifyNamespace,\n useIntegrationIdentity,\n} from \"@executor-js/react/plugins/integration-identity\";\nimport { Button } from \"@executor-js/react/components/button\";\nimport {\n AuthMethodListEditor,\n useAuthMethodList,\n type AuthMethodRow,\n type AuthMethodSeed,\n} from \"@executor-js/react/components/auth-method-list-editor\";\nimport { FloatActions } from \"@executor-js/react/components/float-actions\";\nimport {\n addIntegrationErrorMessage,\n FormErrorAlert,\n SlugCollisionAlert,\n useSlugAlreadyExists,\n} from \"@executor-js/react/lib/integration-add\";\n\nimport { addGraphqlIntegrationOptimistic } from \"./atoms\";\nimport { GraphqlSourceFields } from \"./GraphqlSourceFields\";\nimport { graphqlAuthMethodInputsFromPlacements } from \"./auth-method-config\";\nimport type { GraphqlAuthMethodInput } from \"../sdk/types\";\n\n// v2 GraphQL add flow: register the integration with its declared auth-method\n// LIST (the shared `AuthMethodListEditor` — GraphQL stays header/query apiKey;\n// OAuth is hidden), then route to the integration's detail hub. Connection\n// creation is no longer part of the add flow — accounts are added from the hub\n// (P6: add without auth, connect later).\n\n// GraphQL has no add-time detection, so the list starts empty (module constant\n// — a fresh [] every render would re-seed the list each render).\nconst NO_SEEDS: readonly AuthMethodSeed[] = [];\n\nexport default function AddGraphqlSource(props: {\n onComplete: (slug?: string) => void;\n onCancel: () => void;\n initialUrl?: string;\n}) {\n const [endpoint, setEndpoint] = useState(props.initialUrl ?? \"\");\n const [description, setDescription] = useState(\"\");\n const identity = useIntegrationIdentity({\n fallbackName: integrationDisplayNameFromUrl(endpoint, \"GraphQL\") ?? \"\",\n });\n const authMethodList = useAuthMethodList(NO_SEEDS);\n const [adding, setAdding] = useState(false);\n const [addError, setAddError] = useState<string | null>(null);\n\n const doAddIntegration = useAtomSet(addGraphqlIntegrationOptimistic, {\n mode: \"promiseExit\",\n });\n\n // The methods to register: each apikey row declares ONE method carrying\n // every named placement (header + query mix in a single method). Inputs\n // omit slugs — the backend assigns carrier-derived ones. `none` rows\n // register nothing.\n const authenticationTemplate = useMemo<readonly GraphqlAuthMethodInput[]>(\n () =>\n authMethodList.rows.flatMap((row: AuthMethodRow) =>\n row.value.kind === \"apikey\"\n ? graphqlAuthMethodInputsFromPlacements(row.value.placements)\n : [],\n ),\n [authMethodList.rows],\n );\n\n // Every apikey row needs at least one named placement; `none` rows are\n // always valid.\n const apiKeyComplete = authMethodList.rows.every(\n (row: AuthMethodRow) =>\n row.value.kind !== \"apikey\" ||\n row.value.placements.some((placement) => placement.name.trim().length > 0),\n );\n\n const resolvedSlug = useMemo(\n () =>\n slugifyNamespace(identity.namespace) ||\n slugifyNamespace(integrationDisplayNameFromUrl(endpoint.trim(), \"GraphQL\") ?? \"\") ||\n \"graphql\",\n [endpoint, identity.namespace],\n );\n\n // Pre-empt the API's `IntegrationAlreadyExistsError`: adding an integration\n // whose slug already exists clobbers the existing one's connections/policies,\n // so the API blocks it. Surface that here from the tenant-scoped catalog list.\n const slugAlreadyExists = useSlugAlreadyExists(resolvedSlug);\n\n const canAdd = endpoint.trim().length > 0 && apiKeyComplete && !adding && !slugAlreadyExists;\n\n const sourceIdentity = useCallback(() => {\n const trimmedEndpoint = endpoint.trim();\n const slug = resolvedSlug;\n const displayName =\n identity.name.trim() || integrationDisplayNameFromUrl(trimmedEndpoint, \"GraphQL\") || slug;\n return { trimmedEndpoint, slug, displayName };\n }, [endpoint, identity.name, resolvedSlug]);\n\n const handleAdd = async (): Promise<void> => {\n setAdding(true);\n setAddError(null);\n const { trimmedEndpoint, slug, displayName } = sourceIdentity();\n\n const integrationExit = await doAddIntegration({\n payload: {\n endpoint: trimmedEndpoint,\n slug,\n name: displayName,\n ...(description.trim().length > 0 ? { description: description.trim() } : {}),\n ...(authenticationTemplate.length > 0\n ? { authenticationTemplate: [...authenticationTemplate] }\n : {}),\n },\n reactivityKeys: integrationWriteKeys,\n });\n if (Exit.isFailure(integrationExit)) {\n setAddError(addIntegrationErrorMessage(integrationExit, slug, \"Failed to add source\"));\n setAdding(false);\n return;\n }\n const registeredSlug = integrationExit.value.slug;\n\n props.onComplete(String(registeredSlug));\n };\n\n return (\n <div className=\"flex flex-1 flex-col gap-6\">\n <h1 className=\"text-xl font-semibold text-foreground\">Add GraphQL Source</h1>\n\n <GraphqlSourceFields\n endpoint={endpoint}\n onEndpointChange={setEndpoint}\n identity={identity}\n description={description}\n onDescriptionChange={setDescription}\n />\n\n <AuthMethodListEditor\n list={authMethodList}\n allowedKinds={[\"none\", \"apikey\"]}\n emptyHint=\"No authentication declared. Add a method, or add the source without auth and connect an account from the integration page later.\"\n footerHint=\"Every method here is registered with the source. Connect an account from the integration page after adding.\"\n />\n\n {slugAlreadyExists && !adding && <SlugCollisionAlert slug={resolvedSlug} />}\n\n {addError && <FormErrorAlert message={addError} />}\n\n <FloatActions>\n <Button variant=\"ghost\" onClick={() => props.onCancel()} disabled={adding}>\n Cancel\n </Button>\n <Button onClick={() => void handleAdd()} disabled={!canAdd} loading={adding}>\n Add source\n </Button>\n </FloatActions>\n </div>\n );\n}\n","import {\n CardStack,\n CardStackContent,\n CardStackEntryField,\n} from \"@executor-js/react/components/card-stack\";\nimport { Input } from \"@executor-js/react/components/input\";\nimport { Textarea } from \"@executor-js/react/components/textarea\";\nimport {\n IntegrationIdentityFieldRows,\n type IntegrationIdentity,\n} from \"@executor-js/react/plugins/integration-identity\";\n\nexport function GraphqlSourceFields(props: {\n readonly endpoint: string;\n readonly onEndpointChange: (endpoint: string) => void;\n readonly identity: IntegrationIdentity;\n /** The integration's agent-visible description. Blank = the backend falls\n * back to the introspected schema's own description, then the name. */\n readonly description?: string;\n readonly onDescriptionChange?: (value: string) => void;\n readonly endpointDisabled?: boolean;\n readonly namespaceReadOnly?: boolean;\n}) {\n return (\n <CardStack>\n <CardStackContent className=\"border-t-0\">\n <CardStackEntryField\n label=\"Endpoint\"\n hint=\"The endpoint will be introspected to discover available queries and mutations.\"\n >\n <Input\n value={props.endpoint}\n onChange={(e) => props.onEndpointChange((e.target as HTMLInputElement).value)}\n placeholder=\"https://api.example.com/graphql\"\n className=\"font-mono text-sm\"\n disabled={props.endpointDisabled}\n />\n </CardStackEntryField>\n <IntegrationIdentityFieldRows\n identity={props.identity}\n namePlaceholder=\"e.g. Shopify API\"\n namespaceReadOnly={props.namespaceReadOnly}\n />\n {props.onDescriptionChange && (\n <CardStackEntryField label=\"Description\">\n <Textarea\n value={props.description ?? \"\"}\n onChange={(e) => props.onDescriptionChange?.((e.target as HTMLTextAreaElement).value)}\n placeholder=\"What this API is and when to reach for it\"\n rows={2}\n maxRows={6}\n className=\"text-sm\"\n />\n <p className=\"text-[11px] text-muted-foreground\">\n Agent-visible. Leave blank to use the schema's own description when it has one.\n </p>\n </CardStackEntryField>\n )}\n </CardStackContent>\n </CardStack>\n );\n}\n"],"mappings":";;;;;;;AAAA,SAAS,aAAa,SAAS,gBAAgB;AAC/C,SAAS,kBAAkB;AAC3B,YAAY,UAAU;AAEtB,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACvBP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa;AACtB,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,OAEK;AAoBG,cAcA,YAdA;AAlBH,SAAS,oBAAoB,OAUjC;AACD,SACE,oBAAC,aACC,+BAAC,oBAAiB,WAAU,cAC1B;AAAA;AAAA,MAAC;AAAA;AAAA,QACC,OAAM;AAAA,QACN,MAAK;AAAA,QAEL;AAAA,UAAC;AAAA;AAAA,YACC,O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,eAAe,GAAG;AACnC,kBAAY,2BAA2B,iBAAiB,MAAM,sBAAsB,CAAC;AACrF,gBAAU,KAAK;AACf;AAAA,IACF;AACA,UAAM,iBAAiB,gBAAgB,MAAM;AAE7C,UAAM,WAAW,OAAO,cAAc,CAAC;AAAA,EACzC;AAEA,SACE,gBAAAA,MAAC,SAAI,WAAU,8BACb;AAAA,oBAAAD,KAAC,QAAG,WAAU,yCAAwC,gCAAkB;AAAA,IAExE,gBAAAA;AAAA,MAAC;AAAA;AAAA,QACC;AAAA,QACA,kBAAkB;AAAA,QAClB;AAAA,QACA;AAAA,QACA,qBAAqB;AAAA;AAAA,IACvB;AAAA,IAEA,gBAAAA;AAAA,MAAC;AAAA;AAAA,QACC,MAAM;AAAA,QACN,cAAc,CAAC,QAAQ,QAAQ;AAAA,QAC/B,WAAU;AAAA,QACV,YAAW;AAAA;AAAA,IACb;AAAA,IAEC,qBAAqB,CAAC,UAAU,gBAAAA,KAAC,sBAAmB,MAAM,cAAc;AAAA,IAExE,YAAY,gBAAAA,KAAC,kBAAe,SAAS,UAAU;AAAA,IAEhD,gBAAAC,MAAC,gBACC;AAAA,sBAAAD,KAAC,UAAO,SAAQ,SAAQ,SAAS,MAAM,MAAM,SAAS,GAAG,UAAU,QAAQ,oBAE3E;AAAA,MACA,gBAAAA,KAAC,UAAO,SAAS,MAAM,KAAK,UAAU,GAAG,UAAU,CAAC,QAAQ,SAAS,QAAQ,wBAE7E;AAAA,OACF;AAAA,KACF;AAEJ;","names":["jsx","jsxs"]}
@@ -4,8 +4,8 @@ import {
4
4
  graphqlConfigAtom,
5
5
  graphqlConfigure,
6
6
  graphqlWireAuthInput
7
- } from "./chunk-VSLIDDNK.js";
8
- import "./chunk-732HGFSH.js";
7
+ } from "./chunk-ZUGWBXOU.js";
8
+ import "./chunk-JTWENVHO.js";
9
9
 
10
10
  // src/react/GraphqlAccountsPanel.tsx
11
11
  import { useCallback, useMemo } from "react";
@@ -75,4 +75,4 @@ function GraphqlAccountsPanel(props) {
75
75
  export {
76
76
  GraphqlAccountsPanel as default
77
77
  };
78
- //# sourceMappingURL=GraphqlAccountsPanel-QGBVXP2A.js.map
78
+ //# sourceMappingURL=GraphqlAccountsPanel-LUSTMA3K.js.map
@@ -17,7 +17,7 @@ import {
17
17
  decodeGraphqlIntegrationConfigOption,
18
18
  expandGraphqlAuthMethodInputs,
19
19
  normalizeGraphqlAuthMethods
20
- } from "./chunk-732HGFSH.js";
20
+ } from "./chunk-JTWENVHO.js";
21
21
 
22
22
  // src/sdk/introspect.ts
23
23
  import { Effect, Option, Schema } from "effect";
@@ -455,6 +455,10 @@ var endpointForTelemetry = (endpoint) => {
455
455
  url.hash = "";
456
456
  return url.toString();
457
457
  };
458
+ var effectiveOperationString = (operation, args) => {
459
+ const customSelect = typeof args.select === "string" ? args.select.trim() : "";
460
+ return customSelect.length > 0 && operation.operationPrefix != null && operation.operationSuffix != null ? `${operation.operationPrefix} { ${customSelect} }${operation.operationSuffix}` : operation.operationString;
461
+ };
458
462
  var isJsonContentType = (ct) => {
459
463
  if (!ct) return false;
460
464
  const normalized = ct.split(";")[0]?.trim().toLowerCase() ?? "";
@@ -482,10 +486,11 @@ var invoke = Effect3.fn("GraphQL.invoke")(function* (operation, args, endpoint,
482
486
  if (typeof args.variables === "object" && args.variables !== null) {
483
487
  Object.assign(variables, args.variables);
484
488
  }
489
+ const operationString = effectiveOperationString(operation, args);
485
490
  let request = HttpClientRequest2.post(requestEndpoint).pipe(
486
491
  HttpClientRequest2.setHeader("Content-Type", "application/json"),
487
492
  HttpClientRequest2.bodyJsonUnsafe({
488
- query: operation.operationString,
493
+ query: operationString,
489
494
  variables: Object.keys(variables).length > 0 ? variables : void 0
490
495
  })
491
496
  );
@@ -630,6 +635,19 @@ import {
630
635
  renderAuthPlacements,
631
636
  requiredPlacementVariables
632
637
  } from "@executor-js/sdk/http-auth";
638
+
639
+ // src/sdk/validate-selection.ts
640
+ import { parse } from "graphql";
641
+ var validateOperationString = (operationString) => {
642
+ try {
643
+ parse(operationString);
644
+ return [];
645
+ } catch {
646
+ return ["`select` is not a valid GraphQL selection set"];
647
+ }
648
+ };
649
+
650
+ // src/sdk/plugin.ts
633
651
  var GraphqlErrorBody = Schema3.Struct({ message: Schema3.String });
634
652
  var GraphqlErrorsBody = Schema3.Array(Schema3.Unknown);
635
653
  var decodeGraphqlErrorBody = Schema3.decodeUnknownOption(GraphqlErrorBody);
@@ -727,21 +745,21 @@ var unwrapTypeName2 = (ref) => {
727
745
  if (ref.ofType) return unwrapTypeName2(ref.ofType);
728
746
  return "Unknown";
729
747
  };
730
- var buildSelectionSet = (ref, types, depth, seen) => {
731
- if (depth > 2) return "";
732
- const leafName = unwrapTypeName2(ref);
733
- if (seen.has(leafName)) return "";
734
- const objectType = types.get(leafName);
748
+ var isCompositeType = (ref, types) => {
749
+ const kind = types.get(unwrapTypeName2(ref))?.kind;
750
+ return kind === "OBJECT" || kind === "INTERFACE" || kind === "UNION";
751
+ };
752
+ var hasRequiredArgWithoutDefault = (field) => field.args.some(
753
+ (arg) => arg.type.kind === "NON_NULL" && arg.defaultValue == null
754
+ );
755
+ var buildDefaultSelectionSet = (ref, types) => {
756
+ const objectType = types.get(unwrapTypeName2(ref));
735
757
  if (!objectType?.fields) return "";
736
- const kind = objectType.kind;
737
- if (kind === "SCALAR" || kind === "ENUM") return "";
738
- seen.add(leafName);
739
- const subFields = objectType.fields.filter((f) => !f.name.startsWith("__")).slice(0, 12).map((f) => {
740
- const sub = buildSelectionSet(f.type, types, depth + 1, seen);
741
- return sub ? `${f.name} ${sub}` : f.name;
742
- });
743
- seen.delete(leafName);
744
- return subFields.length > 0 ? `{ ${subFields.join(" ")} }` : "";
758
+ if (objectType.kind === "SCALAR" || objectType.kind === "ENUM") return "";
759
+ const leaves = objectType.fields.filter(
760
+ (f) => !f.name.startsWith("__") && !hasRequiredArgWithoutDefault(f) && !isCompositeType(f.type, types)
761
+ ).map((f) => f.name);
762
+ return leaves.length > 0 ? `{ ${leaves.join(" ")} }` : "{ __typename }";
745
763
  };
746
764
  var operationNameForField = (fieldName) => fieldName.charAt(0).toUpperCase() + fieldName.slice(1);
747
765
  var buildOperationStringForField = (kind, field, types) => {
@@ -752,10 +770,26 @@ var buildOperationStringForField = (kind, field, types) => {
752
770
  return `$${arg.name}: ${typeName}`;
753
771
  });
754
772
  const argPasses = field.args.map((arg) => `${arg.name}: $${arg.name}`);
755
- const selectionSet = buildSelectionSet(field.type, types, 0, /* @__PURE__ */ new Set());
773
+ const defaultSelection = buildDefaultSelectionSet(field.type, types);
756
774
  const varDefsStr = varDefs.length > 0 ? `(${varDefs.join(", ")})` : "";
757
775
  const argPassStr = argPasses.length > 0 ? `(${argPasses.join(", ")})` : "";
758
- return `${opType} ${opName}${varDefsStr} { ${field.name}${argPassStr}${selectionSet ? ` ${selectionSet}` : ""} }`;
776
+ const operationPrefix = `${opType} ${opName}${varDefsStr} { ${field.name}${argPassStr}`;
777
+ const operationSuffix = ` }`;
778
+ const operationString = `${operationPrefix}${defaultSelection ? ` ${defaultSelection}` : ""}${operationSuffix}`;
779
+ return { operationString, operationPrefix, operationSuffix };
780
+ };
781
+ var withSelectInput = (inputSchema, returnTypeName) => {
782
+ const base = inputSchema && typeof inputSchema === "object" ? inputSchema : { type: "object", properties: {} };
783
+ const properties = {
784
+ ...base.properties ?? {}
785
+ };
786
+ if (!("select" in properties)) {
787
+ properties.select = {
788
+ type: "string",
789
+ description: `Optional GraphQL selection set for the \`${returnTypeName}\` return type. Overrides the default, which selects only scalar fields. Provide the fields to return, with sub-selections for nested objects and arguments where required, e.g. "id name items { id title }". Omit for the default.`
790
+ };
791
+ }
792
+ return { ...base, type: "object", properties };
759
793
  };
760
794
  var prepareOperations = (fields, introspection) => {
761
795
  const typeMap = /* @__PURE__ */ new Map();
@@ -784,17 +818,25 @@ var prepareOperations = (fields, introspection) => {
784
818
  );
785
819
  const key = `${extracted.kind}.${extracted.fieldName}`;
786
820
  const entry = fieldMap.get(key);
787
- const operationString = entry ? buildOperationStringForField(entry.kind, entry.field, typeMap) : `${extracted.kind} ${operationNameForField(extracted.fieldName)} { ${extracted.fieldName} }`;
821
+ const built = entry ? buildOperationStringForField(entry.kind, entry.field, typeMap) : {
822
+ operationString: `${extracted.kind} ${operationNameForField(extracted.fieldName)} { ${extracted.fieldName} }`,
823
+ operationPrefix: void 0,
824
+ operationSuffix: void 0
825
+ };
788
826
  const binding = OperationBinding.make({
789
827
  kind: extracted.kind,
790
828
  fieldName: extracted.fieldName,
791
- operationString,
792
- variableNames: extracted.arguments.map((a) => a.name)
829
+ operationString: built.operationString,
830
+ variableNames: extracted.arguments.map((a) => a.name),
831
+ ...built.operationPrefix !== void 0 && built.operationSuffix !== void 0 ? { operationPrefix: built.operationPrefix, operationSuffix: built.operationSuffix } : {}
793
832
  });
794
833
  return {
795
834
  toolName,
796
835
  description,
797
- inputSchema: Option5.getOrUndefined(extracted.inputSchema),
836
+ inputSchema: withSelectInput(
837
+ Option5.getOrUndefined(extracted.inputSchema),
838
+ extracted.returnTypeName
839
+ ),
798
840
  binding
799
841
  };
800
842
  });
@@ -1177,6 +1219,21 @@ var graphqlPlugin = definePlugin((options) => {
1177
1219
  statusCode: Option5.none()
1178
1220
  });
1179
1221
  }
1222
+ const selectArg = args?.select;
1223
+ if (typeof selectArg === "string" && selectArg.trim().length > 0) {
1224
+ const operationString = effectiveOperationString(
1225
+ op.binding,
1226
+ args ?? {}
1227
+ );
1228
+ const selectionErrors = validateOperationString(operationString);
1229
+ if (selectionErrors.length > 0) {
1230
+ return ToolResult.fail({
1231
+ code: "graphql_invalid_selection",
1232
+ message: selectionErrors[0],
1233
+ details: { errors: selectionErrors }
1234
+ });
1235
+ }
1236
+ }
1180
1237
  const headers = { ...config.headers ?? {} };
1181
1238
  const queryParams = {
1182
1239
  ...config.queryParams ?? {}
@@ -1306,4 +1363,4 @@ export {
1306
1363
  describeGraphqlAuthMethods,
1307
1364
  graphqlPlugin
1308
1365
  };
1309
- //# sourceMappingURL=chunk-IUCH3RWQ.js.map
1366
+ //# sourceMappingURL=chunk-DQ3XWZ6J.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/introspect.ts","../src/sdk/extract.ts","../src/sdk/invoke.ts","../src/sdk/store.ts","../src/sdk/plugin.ts","../src/sdk/validate-selection.ts"],"sourcesContent":["import { Effect, Option, Schema } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\n\nimport { GraphqlIntrospectionError } from \"./errors\";\n\n// ---------------------------------------------------------------------------\n// Introspection query — standard GraphQL introspection\n// ---------------------------------------------------------------------------\n\nconst INTROSPECTION_QUERY = `\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n types {\n kind\n name\n description\n fields(includeDeprecated: false) {\n name\n description\n args {\n name\n description\n type {\n ...TypeRef\n }\n defaultValue\n }\n type {\n ...TypeRef\n }\n }\n inputFields {\n name\n description\n type {\n ...TypeRef\n }\n defaultValue\n }\n enumValues(includeDeprecated: false) {\n name\n description\n }\n }\n }\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n`;\n\n// ---------------------------------------------------------------------------\n// Introspection result types\n// ---------------------------------------------------------------------------\n\nconst IntrospectionTypeRefLeaf = Schema.Struct({\n kind: Schema.String,\n name: Schema.NullOr(Schema.String),\n ofType: Schema.optional(Schema.Null),\n});\n\nconst IntrospectionTypeRef5 = Schema.Struct({\n kind: Schema.String,\n name: Schema.NullOr(Schema.String),\n ofType: Schema.optional(Schema.NullOr(IntrospectionTypeRefLeaf)),\n});\n\nconst IntrospectionTypeRef4 = Schema.Struct({\n kind: Schema.String,\n name: Schema.NullOr(Schema.String),\n ofType: Schema.optional(Schema.NullOr(IntrospectionTypeRef5)),\n});\n\nconst IntrospectionTypeRef3 = Schema.Struct({\n kind: Schema.String,\n name: Schema.NullOr(Schema.String),\n ofType: Schema.optional(Schema.NullOr(IntrospectionTypeRef4)),\n});\n\nconst IntrospectionTypeRef2 = Schema.Struct({\n kind: Schema.String,\n name: Schema.NullOr(Schema.String),\n ofType: Schema.optional(Schema.NullOr(IntrospectionTypeRef3)),\n});\n\nconst IntrospectionTypeRefSchema = Schema.Struct({\n kind: Schema.String,\n name: Schema.NullOr(Schema.String),\n ofType: Schema.optional(Schema.NullOr(IntrospectionTypeRef2)),\n});\n\nconst IntrospectionInputValueSchema = Schema.Struct({\n name: Schema.String,\n description: Schema.NullOr(Schema.String),\n type: IntrospectionTypeRefSchema,\n defaultValue: Schema.NullOr(Schema.String),\n});\n\nconst IntrospectionFieldSchema = Schema.Struct({\n name: Schema.String,\n description: Schema.NullOr(Schema.String),\n args: Schema.Array(IntrospectionInputValueSchema),\n type: IntrospectionTypeRefSchema,\n});\n\nconst IntrospectionTypeSchema = Schema.Struct({\n kind: Schema.String,\n name: Schema.String,\n description: Schema.NullOr(Schema.String),\n fields: Schema.NullOr(Schema.Array(IntrospectionFieldSchema)),\n inputFields: Schema.NullOr(Schema.Array(IntrospectionInputValueSchema)),\n enumValues: Schema.NullOr(\n Schema.Array(\n Schema.Struct({\n name: Schema.String,\n description: Schema.NullOr(Schema.String),\n }),\n ),\n ),\n});\n\nconst IntrospectionResultSchema = Schema.Struct({\n __schema: Schema.Struct({\n queryType: Schema.NullOr(Schema.Struct({ name: Schema.String })),\n mutationType: Schema.NullOr(Schema.Struct({ name: Schema.String })),\n types: Schema.Array(IntrospectionTypeSchema),\n }),\n});\n\nconst IntrospectionResponseSchema = Schema.Struct({\n data: Schema.optional(IntrospectionResultSchema),\n errors: Schema.optional(Schema.Array(Schema.Unknown)),\n});\n\nconst UpstreamErrorResponseSchema = Schema.Struct({\n message: Schema.optional(Schema.String),\n errors: Schema.optional(\n Schema.Array(\n Schema.Struct({\n message: Schema.optional(Schema.String),\n }),\n ),\n ),\n});\n\nconst IntrospectionJsonSchema = Schema.Union([\n Schema.Struct({ data: IntrospectionResultSchema }),\n IntrospectionResultSchema,\n]);\nconst JsonTextSchema = Schema.fromJsonString(Schema.Unknown);\n\nconst decodeUpstreamErrorResponse = Schema.decodeUnknownOption(UpstreamErrorResponseSchema);\n\nexport type IntrospectionTypeRef = typeof IntrospectionTypeRefSchema.Type;\nexport type IntrospectionInputValue = typeof IntrospectionInputValueSchema.Type;\nexport type IntrospectionField = typeof IntrospectionFieldSchema.Type;\nexport type IntrospectionEnumValue = NonNullable<\n (typeof IntrospectionTypeSchema.Type)[\"enumValues\"]\n>[number];\nexport type IntrospectionType = typeof IntrospectionTypeSchema.Type;\nexport type IntrospectionSchema = (typeof IntrospectionResultSchema.Type)[\"__schema\"];\nexport type IntrospectionResult = typeof IntrospectionResultSchema.Type;\n\nconst firstUpstreamErrorMessage = (value: unknown): string | null => {\n const decoded = decodeUpstreamErrorResponse(value);\n return Option.match(decoded, {\n onNone: () => null,\n onSome: (response) => {\n if (response.message) return response.message;\n for (const entry of response.errors ?? []) {\n const message = entry.message;\n if (message) return message;\n }\n return null;\n },\n });\n};\n\nconst redactUpstreamBody = (body: string): string =>\n body\n .replaceAll(\n /(\"(?:access_token|refresh_token|id_token|client_secret|token|authorization)\"\\s*:\\s*\")[^\"]*(\")/gi,\n \"$1[redacted]$2\",\n )\n .replaceAll(\n /((?:access_token|refresh_token|id_token|client_secret|token|authorization)=)[^&\\s]*/gi,\n \"$1[redacted]\",\n )\n .replaceAll(\n /((?:authorization|access-token|refresh-token|id-token|client-secret|token)\\s*:\\s*)(?:bearer\\s+)?[^\\s,;]+/gi,\n \"$1[redacted]\",\n );\n\nconst upstreamTextMessage = (body: string): string | null => {\n const text = redactUpstreamBody(body.replaceAll(/\\s+/g, \" \").trim());\n if (text.length === 0) return null;\n return text.length > 500 ? `${text.slice(0, 500)}...` : text;\n};\n\n// ---------------------------------------------------------------------------\n// Introspect a GraphQL endpoint\n// ---------------------------------------------------------------------------\n\nexport const introspect = Effect.fn(\"GraphQL.introspect\")(function* (\n endpoint: string,\n headers?: Record<string, string>,\n queryParams?: Record<string, string>,\n) {\n const client = yield* HttpClient.HttpClient;\n const requestEndpoint =\n queryParams && Object.keys(queryParams).length > 0\n ? (() => {\n const url = new URL(endpoint);\n for (const [name, value] of Object.entries(queryParams)) {\n url.searchParams.set(name, value);\n }\n return url.toString();\n })()\n : endpoint;\n\n let request = HttpClientRequest.post(requestEndpoint).pipe(\n HttpClientRequest.setHeader(\"Content-Type\", \"application/json\"),\n HttpClientRequest.setHeader(\"Accept\", \"application/json\"),\n HttpClientRequest.setHeader(\"User-Agent\", \"executor-graphql\"),\n HttpClientRequest.bodyJsonUnsafe({\n query: INTROSPECTION_QUERY,\n }),\n );\n\n if (headers) {\n for (const [k, v] of Object.entries(headers)) {\n request = HttpClientRequest.setHeader(request, k, v);\n }\n }\n\n const response = yield* client.execute(request).pipe(\n Effect.tapCause((cause) => Effect.logError(\"graphql introspection request failed\", cause)),\n Effect.mapError(\n () =>\n new GraphqlIntrospectionError({\n message: \"Failed to reach GraphQL endpoint\",\n }),\n ),\n );\n\n if (response.status !== 200) {\n const responseText = yield* response.text.pipe(Effect.catch(() => Effect.succeed(\"\")));\n const raw = responseText\n ? yield* Schema.decodeUnknownEffect(JsonTextSchema)(responseText).pipe(\n Effect.catch(() => Effect.succeed(null)),\n )\n : null;\n const upstreamMessage = upstreamTextMessage(\n (raw === null ? null : firstUpstreamErrorMessage(raw)) ?? responseText,\n );\n return yield* new GraphqlIntrospectionError({\n message: upstreamMessage\n ? `Introspection failed with status ${response.status}: ${upstreamMessage}`\n : `Introspection failed with status ${response.status}`,\n });\n }\n\n const raw = yield* response.json.pipe(\n Effect.tapCause((cause) => Effect.logError(\"graphql introspection JSON parse failed\", cause)),\n Effect.mapError(\n () =>\n new GraphqlIntrospectionError({\n message: `Failed to parse introspection response as JSON`,\n }),\n ),\n );\n\n const json = yield* Schema.decodeUnknownEffect(IntrospectionResponseSchema)(raw).pipe(\n Effect.mapError(\n () =>\n new GraphqlIntrospectionError({\n message: \"Introspection response has an invalid shape\",\n }),\n ),\n );\n\n if (json.errors && Array.isArray(json.errors) && json.errors.length > 0) {\n const upstreamMessage = firstUpstreamErrorMessage(json);\n return yield* new GraphqlIntrospectionError({\n message: upstreamMessage\n ? `Introspection returned ${json.errors.length} error(s): ${upstreamMessage}`\n : `Introspection returned ${json.errors.length} error(s)`,\n });\n }\n\n if (!json.data?.__schema) {\n return yield* new GraphqlIntrospectionError({\n message: \"Introspection response missing __schema\",\n });\n }\n\n return json.data;\n});\n\n// ---------------------------------------------------------------------------\n// Parse an introspection result from a JSON string (for offline/text input)\n// ---------------------------------------------------------------------------\n\nexport const parseIntrospectionJson = (\n text: string,\n): Effect.Effect<IntrospectionResult, GraphqlIntrospectionError> =>\n Schema.decodeUnknownEffect(Schema.fromJsonString(IntrospectionJsonSchema))(text).pipe(\n Effect.map((parsed) => (\"data\" in parsed ? parsed.data : parsed)),\n Effect.mapError(\n () =>\n new GraphqlIntrospectionError({\n message: \"Failed to parse introspection JSON\",\n }),\n ),\n );\n","import { Effect, Match, Option } from \"effect\";\n\nimport { GraphqlExtractionError } from \"./errors\";\nimport type {\n IntrospectionResult,\n IntrospectionSchema,\n IntrospectionType,\n IntrospectionTypeRef,\n IntrospectionInputValue,\n} from \"./introspect\";\nimport {\n ExtractedField,\n ExtractionResult,\n GraphqlArgument,\n type GraphqlOperationKind,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Type ref helpers\n// ---------------------------------------------------------------------------\n\n/** Unwrap NON_NULL / LIST wrappers to get the leaf type name */\nconst unwrapTypeName = (ref: IntrospectionTypeRef): string => {\n if (ref.name) return ref.name;\n if (ref.ofType) return unwrapTypeName(ref.ofType);\n return \"Unknown\";\n};\n\n/** Check if a type ref is non-null (required) */\nconst isNonNull = (ref: IntrospectionTypeRef): boolean => ref.kind === \"NON_NULL\";\n\n// ---------------------------------------------------------------------------\n// Build shared definitions from all INPUT_OBJECT and ENUM types\n// ---------------------------------------------------------------------------\n\nconst buildDefinitions = (\n types: ReadonlyMap<string, IntrospectionType>,\n): Record<string, unknown> => {\n const defs: Record<string, unknown> = {};\n\n for (const [name, type] of types) {\n // Skip internal types\n if (name.startsWith(\"__\")) continue;\n\n if (type.kind === \"INPUT_OBJECT\" && type.inputFields) {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const field of type.inputFields) {\n const schema = typeRefToJsonSchema(field.type, types);\n if (field.description) {\n (schema as Record<string, unknown>).description = field.description;\n }\n properties[field.name] = schema;\n if (isNonNull(field.type)) {\n required.push(field.name);\n }\n }\n\n const def: Record<string, unknown> = { type: \"object\", properties };\n if (required.length > 0) def.required = required;\n if (type.description) def.description = type.description;\n defs[name] = def;\n }\n\n if (type.kind === \"ENUM\" && type.enumValues) {\n defs[name] = {\n type: \"string\",\n enum: type.enumValues.map((v) => v.name),\n ...(type.description ? { description: type.description } : {}),\n };\n }\n }\n\n return defs;\n};\n\n// ---------------------------------------------------------------------------\n// Convert a type ref to JSON Schema using $ref for complex types\n// ---------------------------------------------------------------------------\n\nconst typeRefToJsonSchema = (\n ref: IntrospectionTypeRef,\n // oxlint-disable-next-line only-used-in-recursion\n types: ReadonlyMap<string, IntrospectionType>,\n): Record<string, unknown> =>\n Match.value(ref.kind).pipe(\n Match.when(\n \"NON_NULL\",\n (): Record<string, unknown> => (ref.ofType ? typeRefToJsonSchema(ref.ofType, types) : {}),\n ),\n Match.when(\n \"LIST\",\n (): Record<string, unknown> => ({\n type: \"array\",\n items: ref.ofType ? typeRefToJsonSchema(ref.ofType, types) : {},\n }),\n ),\n Match.when(\"SCALAR\", (): Record<string, unknown> => scalarToJsonSchema(ref.name ?? \"String\")),\n Match.when(\n \"ENUM\",\n (): Record<string, unknown> =>\n ref.name ? { $ref: `#/$defs/${ref.name}` } : { type: \"string\" },\n ),\n Match.when(\n \"INPUT_OBJECT\",\n (): Record<string, unknown> =>\n ref.name ? { $ref: `#/$defs/${ref.name}` } : { type: \"object\" },\n ),\n Match.whenOr(\n \"OBJECT\",\n \"INTERFACE\",\n \"UNION\",\n (): Record<string, unknown> => ({ type: \"object\" }),\n ),\n Match.option,\n Option.getOrElse((): Record<string, unknown> => ({})),\n );\n\nconst scalarToJsonSchema = (name: string): Record<string, unknown> =>\n Match.value(name).pipe(\n Match.whenOr(\"String\", \"ID\", (): Record<string, unknown> => ({ type: \"string\" })),\n Match.when(\"Int\", (): Record<string, unknown> => ({ type: \"integer\" })),\n Match.when(\"Float\", (): Record<string, unknown> => ({ type: \"number\" })),\n Match.when(\"Boolean\", (): Record<string, unknown> => ({ type: \"boolean\" })),\n Match.option,\n Option.getOrElse(\n (): Record<string, unknown> => ({ type: \"string\", description: `Custom scalar: ${name}` }),\n ),\n );\n\n// ---------------------------------------------------------------------------\n// Build input JSON Schema from field arguments\n// ---------------------------------------------------------------------------\n\nconst buildInputSchema = (\n args: readonly IntrospectionInputValue[],\n types: ReadonlyMap<string, IntrospectionType>,\n): Record<string, unknown> | undefined => {\n if (args.length === 0) return undefined;\n\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const arg of args) {\n const schema = typeRefToJsonSchema(arg.type, types);\n if (arg.description) {\n (schema as Record<string, unknown>).description = arg.description;\n }\n properties[arg.name] = schema;\n if (isNonNull(arg.type)) {\n required.push(arg.name);\n }\n }\n\n const inputSchema: Record<string, unknown> = {\n type: \"object\",\n properties,\n };\n if (required.length > 0) inputSchema.required = required;\n return inputSchema;\n};\n\n/** Format a type ref back to GraphQL type notation (e.g. \"[String!]!\") */\nconst formatTypeRef = (ref: IntrospectionTypeRef): string =>\n Match.value(ref.kind).pipe(\n Match.when(\"NON_NULL\", () => (ref.ofType ? `${formatTypeRef(ref.ofType)}!` : \"Unknown!\")),\n Match.when(\"LIST\", () => (ref.ofType ? `[${formatTypeRef(ref.ofType)}]` : \"[Unknown]\")),\n Match.option,\n Option.getOrElse(() => ref.name ?? \"Unknown\"),\n );\n\n// ---------------------------------------------------------------------------\n// Extract fields from schema\n// ---------------------------------------------------------------------------\n\nconst extractFields = (\n _schema: IntrospectionSchema,\n kind: GraphqlOperationKind,\n typeName: string | null | undefined,\n types: ReadonlyMap<string, IntrospectionType>,\n): ExtractedField[] => {\n if (!typeName) return [];\n\n const type = types.get(typeName);\n if (!type?.fields) return [];\n\n return type.fields\n .filter((f) => !f.name.startsWith(\"__\"))\n .map((field) => {\n const args = field.args.map((arg) =>\n GraphqlArgument.make({\n name: arg.name,\n typeName: formatTypeRef(arg.type),\n required: isNonNull(arg.type),\n description: arg.description ? Option.some(arg.description) : Option.none(),\n }),\n );\n\n const inputSchema = buildInputSchema(field.args, types);\n\n return ExtractedField.make({\n fieldName: field.name,\n kind,\n description: field.description ? Option.some(field.description) : Option.none(),\n arguments: args,\n inputSchema: inputSchema ? Option.some(inputSchema) : Option.none(),\n returnTypeName: unwrapTypeName(field.type),\n });\n });\n};\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport interface ExtractionOutput {\n readonly result: ExtractionResult;\n /** Shared JSON Schema definitions for INPUT_OBJECT and ENUM types.\n * Tool input schemas use `$ref` pointers into these. */\n readonly definitions: Record<string, unknown>;\n}\n\nexport const extract = (\n introspection: IntrospectionResult,\n): Effect.Effect<ExtractionOutput, GraphqlExtractionError> =>\n Effect.try({\n try: () => {\n const schema = introspection.__schema;\n const typeMap = new Map<string, IntrospectionType>();\n for (const t of schema.types) {\n typeMap.set(t.name, t);\n }\n\n const definitions = buildDefinitions(typeMap);\n\n const queryFields = extractFields(schema, \"query\", schema.queryType?.name, typeMap);\n const mutationFields = extractFields(schema, \"mutation\", schema.mutationType?.name, typeMap);\n\n return {\n result: ExtractionResult.make({\n schemaName: Option.none(),\n fields: [...queryFields, ...mutationFields],\n }),\n definitions,\n };\n },\n catch: () =>\n new GraphqlExtractionError({\n message: \"Failed to extract GraphQL schema\",\n }),\n });\n","import { Effect, Layer, Option } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\n\nimport { GraphqlInvocationError } from \"./errors\";\nimport { type OperationBinding, InvocationResult } from \"./types\";\n\nconst endpointWithQueryParams = (endpoint: string, queryParams: Record<string, string>): string => {\n if (Object.keys(queryParams).length === 0) return endpoint;\n const url = new URL(endpoint);\n for (const [name, value] of Object.entries(queryParams)) {\n url.searchParams.set(name, value);\n }\n return url.toString();\n};\n\nexport const endpointForTelemetry = (endpoint: string): string => {\n if (!URL.canParse(endpoint)) return endpoint;\n const url = new URL(endpoint);\n url.search = \"\";\n url.hash = \"\";\n return url.toString();\n};\n\n/** The operation string to send for a call. A caller-supplied `select` overrides\n * the default scalar-leaf selection: it is spliced into the field's selection\n * set (`field { <select> }`) so nested/list data can be requested per call. Falls\n * back to the stored default operation when `select` is absent or the binding\n * predates the prefix/suffix split. `select` is a control input, never a GraphQL\n * variable. Shared with plugin.invokeTool so the validated string matches the\n * sent string exactly. */\nexport const effectiveOperationString = (\n operation: OperationBinding,\n args: Record<string, unknown>,\n): string => {\n const customSelect = typeof args.select === \"string\" ? args.select.trim() : \"\";\n return customSelect.length > 0 &&\n operation.operationPrefix != null &&\n operation.operationSuffix != null\n ? `${operation.operationPrefix} { ${customSelect} }${operation.operationSuffix}`\n : operation.operationString;\n};\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nconst isJsonContentType = (ct: string | null | undefined): boolean => {\n if (!ct) return false;\n const normalized = ct.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n return (\n normalized === \"application/json\" || normalized.includes(\"+json\") || normalized.includes(\"json\")\n );\n};\n\n// ---------------------------------------------------------------------------\n// Public API — execute a GraphQL operation\n// ---------------------------------------------------------------------------\n\nexport const invoke = Effect.fn(\"GraphQL.invoke\")(function* (\n operation: OperationBinding,\n args: Record<string, unknown>,\n endpoint: string,\n resolvedHeaders: Record<string, string>,\n resolvedQueryParams: Record<string, string> = {},\n) {\n const client = yield* HttpClient.HttpClient;\n const requestEndpoint = endpointWithQueryParams(endpoint, resolvedQueryParams);\n const telemetryEndpoint = endpointForTelemetry(endpoint);\n\n yield* Effect.annotateCurrentSpan({\n \"http.method\": \"POST\",\n \"http.url\": telemetryEndpoint,\n \"plugin.graphql.endpoint\": telemetryEndpoint,\n \"plugin.graphql.operation_kind\": operation.kind,\n \"plugin.graphql.field_name\": operation.fieldName,\n \"plugin.graphql.headers.resolved_count\": Object.keys(resolvedHeaders).length,\n \"plugin.graphql.query_params.resolved_count\": Object.keys(resolvedQueryParams).length,\n });\n\n // Build the GraphQL request body\n const variables: Record<string, unknown> = {};\n for (const varName of operation.variableNames) {\n if (args[varName] !== undefined) {\n variables[varName] = args[varName];\n }\n }\n\n // Also pick up any variables from a \"variables\" container\n if (typeof args.variables === \"object\" && args.variables !== null) {\n Object.assign(variables, args.variables);\n }\n\n // `select` (a control input, not a GraphQL variable) is applied here and never\n // enters `variables`. plugin.invokeTool validates this same string before we\n // reach the network.\n const operationString = effectiveOperationString(operation, args);\n\n let request = HttpClientRequest.post(requestEndpoint).pipe(\n HttpClientRequest.setHeader(\"Content-Type\", \"application/json\"),\n HttpClientRequest.bodyJsonUnsafe({\n query: operationString,\n variables: Object.keys(variables).length > 0 ? variables : undefined,\n }),\n );\n\n for (const [name, value] of Object.entries(resolvedHeaders)) {\n request = HttpClientRequest.setHeader(request, name, value);\n }\n\n const response = yield* client.execute(request).pipe(\n Effect.mapError(\n (err) =>\n new GraphqlInvocationError({\n message: \"GraphQL request failed\",\n statusCode: Option.none(),\n cause: err,\n }),\n ),\n );\n\n const status = response.status;\n const contentType = response.headers[\"content-type\"] ?? null;\n\n const body: unknown = isJsonContentType(contentType)\n ? yield* response.json.pipe(Effect.catch(() => response.text))\n : yield* response.text;\n\n // GraphQL responses are always 200 with { data, errors }\n const gqlBody = body as { data?: unknown; errors?: unknown[] } | null;\n const hasErrors = Array.isArray(gqlBody?.errors) && gqlBody.errors.length > 0;\n\n yield* Effect.annotateCurrentSpan({\n \"http.status_code\": status,\n \"plugin.graphql.has_errors\": hasErrors,\n \"plugin.graphql.error_count\": hasErrors ? gqlBody!.errors!.length : 0,\n });\n\n return InvocationResult.make({\n status,\n data: gqlBody?.data ?? null,\n errors: hasErrors ? gqlBody!.errors : null,\n });\n});\n\n// ---------------------------------------------------------------------------\n// Invoke a GraphQL operation with a provided HttpClient layer\n// ---------------------------------------------------------------------------\n\nexport const invokeWithLayer = (\n operation: OperationBinding,\n args: Record<string, unknown>,\n endpoint: string,\n resolvedHeaders: Record<string, string>,\n resolvedQueryParams: Record<string, string>,\n httpClientLayer: Layer.Layer<HttpClient.HttpClient>,\n) =>\n invoke(operation, args, endpoint, resolvedHeaders, resolvedQueryParams).pipe(\n Effect.provide(httpClientLayer),\n Effect.withSpan(\"plugin.graphql.invoke\", {\n attributes: {\n \"plugin.graphql.endpoint\": endpointForTelemetry(endpoint),\n \"plugin.graphql.operation_kind\": operation.kind,\n \"plugin.graphql.field_name\": operation.fieldName,\n },\n }),\n );\n","import { Effect, Option, Predicate, Schema } from \"effect\";\n\nimport {\n type Owner,\n type PluginStorageEntry,\n type StorageDeps,\n type StorageFailure,\n} from \"@executor-js/sdk/core\";\n\nimport { OperationBinding } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Per-integration operation bindings.\n//\n// In v2 the integration's GraphQL operations are derived from introspection and\n// are identical for every connection, so the plugin store keeps one set of\n// operation bindings per integration slug — `invokeTool` reads them back to\n// rebuild the request. Operations are catalog-level metadata, so they live under\n// the shared `owner: \"org\"` partition.\n// ---------------------------------------------------------------------------\n\nconst CATALOG_OWNER: Owner = \"org\";\nconst OPERATION_COLLECTION = \"operation\";\n\nexport interface StoredOperation {\n /** The tool's leaf name, e.g. `query.hello`. */\n readonly toolName: string;\n /** The owning integration slug. */\n readonly integration: string;\n readonly binding: OperationBinding;\n}\n\nconst OperationBindingFromJsonString = Schema.fromJsonString(OperationBinding);\nconst decodeOperationBindingFromJsonString = Schema.decodeUnknownSync(\n OperationBindingFromJsonString,\n);\nconst decodeOperationBinding = Schema.decodeUnknownSync(OperationBinding);\nconst encodeBinding = Schema.encodeSync(OperationBinding);\n\nconst decodeBinding = (value: unknown): OperationBinding => {\n if (typeof value === \"string\") return decodeOperationBindingFromJsonString(value);\n return decodeOperationBinding(value);\n};\n\nconst toJsonRecord = (value: unknown): Record<string, unknown> => value as Record<string, unknown>;\n\nconst OperationStorage = Schema.Struct({\n toolName: Schema.String,\n integration: Schema.String,\n binding: Schema.Unknown,\n});\nconst decodeOperationStorage = Schema.decodeUnknownOption(OperationStorage);\n\nconst operationKey = (integration: string, toolName: string): string =>\n `${integration}.${toolName}`;\n\nconst operationData = (operation: StoredOperation) => ({\n toolName: operation.toolName,\n integration: operation.integration,\n binding: toJsonRecord(encodeBinding(operation.binding)),\n});\n\nconst rowToOperation = (row: PluginStorageEntry): StoredOperation | null => {\n const decoded = decodeOperationStorage(row.data);\n if (Option.isNone(decoded)) return null;\n const operation = decoded.value;\n return {\n toolName: operation.toolName,\n integration: operation.integration,\n binding: decodeBinding(operation.binding),\n };\n};\n\n/** Blob key for an introspection snapshot's content hash. Content-addressed\n * so re-puts are idempotent and identical schemas share one blob per\n * partition. */\nexport const introspectionBlobKey = (introspectionHash: string): string =>\n `introspection/${introspectionHash}`;\n\nexport interface GraphqlStore {\n /** Replace the stored operation bindings for an integration. */\n readonly replaceOperations: (\n integration: string,\n operations: readonly StoredOperation[],\n ) => Effect.Effect<void, StorageFailure>;\n readonly getOperation: (\n integration: string,\n toolName: string,\n ) => Effect.Effect<StoredOperation | null, StorageFailure>;\n readonly listOperations: (\n integration: string,\n ) => Effect.Effect<readonly StoredOperation[], StorageFailure>;\n readonly removeOperations: (integration: string) => Effect.Effect<void, StorageFailure>;\n /** Persist an introspection JSON snapshot under its content hash. Org-owned\n * and content-addressed; never removed on integration removal because\n * another integration in the tenant may share the hash. */\n readonly putIntrospection: (\n introspectionHash: string,\n introspectionJson: string,\n ) => Effect.Effect<void, StorageFailure>;\n /** Load an introspection snapshot by content hash; null when absent. */\n readonly getIntrospection: (\n introspectionHash: string,\n ) => Effect.Effect<string | null, StorageFailure>;\n}\n\nexport const makeDefaultGraphqlStore = ({ pluginStorage, blobs }: StorageDeps): GraphqlStore => {\n const listOperationRows = (integration: string) =>\n pluginStorage\n .list({\n collection: OPERATION_COLLECTION,\n keyPrefix: `${integration}.`,\n })\n .pipe(\n Effect.map((rows) =>\n rows.filter((row) => rowToOperation(row)?.integration === integration),\n ),\n );\n\n const removeOperations = (integration: string) =>\n Effect.gen(function* () {\n const rows = yield* listOperationRows(integration);\n for (const row of rows) {\n yield* pluginStorage.remove({\n owner: CATALOG_OWNER,\n collection: OPERATION_COLLECTION,\n key: row.key,\n });\n }\n });\n\n return {\n replaceOperations: (integration, operations) =>\n Effect.gen(function* () {\n yield* removeOperations(integration);\n for (const operation of operations) {\n yield* pluginStorage.put({\n owner: CATALOG_OWNER,\n collection: OPERATION_COLLECTION,\n key: operationKey(integration, operation.toolName),\n data: operationData(operation),\n });\n }\n }),\n\n getOperation: (integration, toolName) =>\n pluginStorage\n .get({ collection: OPERATION_COLLECTION, key: operationKey(integration, toolName) })\n .pipe(Effect.map((row) => (row ? rowToOperation(row) : null))),\n\n listOperations: (integration) =>\n listOperationRows(integration).pipe(\n Effect.map((rows) => rows.map(rowToOperation).filter(Predicate.isNotNull)),\n ),\n\n removeOperations,\n\n putIntrospection: (introspectionHash, introspectionJson) =>\n blobs.put(introspectionBlobKey(introspectionHash), introspectionJson, {\n owner: CATALOG_OWNER,\n }),\n\n getIntrospection: (introspectionHash) => blobs.get(introspectionBlobKey(introspectionHash)),\n };\n};\n","import { Effect, Match, Option, Schema } from \"effect\";\nimport type { Layer } from \"effect\";\nimport { HttpClient } from \"effect/unstable/http\";\n\nimport {\n authToolFailure,\n AuthTemplateSlug,\n definePlugin,\n IntegrationAlreadyExistsError,\n IntegrationDetectionResult,\n IntegrationSlug,\n mergeAuthTemplates,\n sha256Hex,\n ToolName,\n ToolResult,\n type AuthMethodDescriptor,\n type IntegrationConfig,\n type IntegrationRecord,\n type PluginCtx,\n type StorageFailure,\n type ToolAnnotations,\n type ToolDef,\n} from \"@executor-js/sdk/core\";\n\nimport {\n TOKEN_VARIABLE,\n describeApiKeyAuthMethod,\n describeNoneAuthMethod,\n oauthBearerPlacement,\n renderAuthPlacements,\n requiredPlacementVariables,\n type RenderedAuthPlacements,\n} from \"@executor-js/sdk/http-auth\";\n\nimport {\n introspect,\n parseIntrospectionJson,\n type IntrospectionResult,\n type IntrospectionType,\n type IntrospectionField,\n type IntrospectionInputValue,\n type IntrospectionTypeRef,\n} from \"./introspect\";\nimport { extract } from \"./extract\";\nimport {\n GraphqlAuthRequiredError,\n GraphqlIntrospectionError,\n GraphqlInvocationError,\n} from \"./errors\";\nimport { effectiveOperationString, invokeWithLayer } from \"./invoke\";\nimport { validateOperationString } from \"./validate-selection\";\nimport { graphqlPresets } from \"./presets\";\nimport { makeDefaultGraphqlStore, type GraphqlStore, type StoredOperation } from \"./store\";\nimport {\n GraphqlAuthMethodInput,\n decodeGraphqlIntegrationConfig,\n decodeGraphqlIntegrationConfigOption,\n ExtractedField,\n GraphqlIntegrationConfig,\n expandGraphqlAuthMethodInputs,\n normalizeGraphqlAuthMethods,\n OperationBinding,\n type GraphqlAuthMethod,\n type GraphqlOperationKind,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// GraphQL error-body decoding (for invocation responses)\n// ---------------------------------------------------------------------------\n\nconst GraphqlErrorBody = Schema.Struct({ message: Schema.String });\nconst GraphqlErrorsBody = Schema.Array(Schema.Unknown);\nconst decodeGraphqlErrorBody = Schema.decodeUnknownOption(GraphqlErrorBody);\nconst decodeGraphqlErrorsBody = Schema.decodeUnknownOption(GraphqlErrorsBody);\n\nconst decodeGraphqlErrors = (errors: unknown): readonly unknown[] | undefined =>\n Option.getOrUndefined(decodeGraphqlErrorsBody(errors));\n\nconst extractGraphqlErrorMessage = (errors: readonly unknown[]): string | undefined =>\n errors\n .map((error) => Option.getOrUndefined(decodeGraphqlErrorBody(error))?.message)\n .find((message) => message !== undefined && message.length > 0);\n\nconst GRAPHQL_PLUGIN_ID = \"graphql\";\n\n// ---------------------------------------------------------------------------\n// Extension input shapes\n// ---------------------------------------------------------------------------\n\n/** Register a GraphQL integration in the catalog. `endpoint` is the GraphQL URL;\n * `slug` (defaulted from the endpoint) is the catalog id; `introspectionJson`\n * supplies the schema when the endpoint disables live introspection; `headers`\n * / `queryParams` are static and also applied to add-time introspection;\n * `authenticationTemplate` declares the auth methods a connection can apply\n * through. */\nconst GraphqlAddIntegrationInputSchema = Schema.Struct({\n endpoint: Schema.String,\n slug: Schema.optional(Schema.String),\n name: Schema.optional(Schema.String),\n /** Agent-visible catalog description. Falls back to the introspected\n * schema's own description, then the display name. */\n description: Schema.optional(Schema.String),\n introspectionJson: Schema.optional(Schema.String),\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n authenticationTemplate: Schema.optional(Schema.Array(GraphqlAuthMethodInput)),\n});\nexport type GraphqlAddIntegrationInput = typeof GraphqlAddIntegrationInputSchema.Type;\n\nconst GraphqlConfigureInputSchema = Schema.Struct({\n name: Schema.optional(Schema.String),\n endpoint: Schema.optional(Schema.String),\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n authenticationTemplate: Schema.optional(Schema.Array(GraphqlAuthMethodInput)),\n});\nexport type GraphqlConfigureInput = typeof GraphqlConfigureInputSchema.Type;\n\n/** Input for the custom-method-create flow (HTTP `POST /graphql/integrations/\n * :slug/config`). Unlike `configure` (which REPLACES the whole config for the\n * generic repair path), `configureAuth` MERGE-APPENDS these methods onto the\n * integration's existing `authenticationTemplate`, mirroring OpenAPI's\n * `configure`. */\nconst GraphqlConfigureAuthInputSchema = Schema.Struct({\n authenticationTemplate: Schema.Array(GraphqlAuthMethodInput),\n mode: Schema.optional(Schema.Literals([\"merge\", \"replace\"])),\n});\nexport type GraphqlConfigureAuthInput = typeof GraphqlConfigureAuthInputSchema.Type;\n\n// ---------------------------------------------------------------------------\n// Static control-tool schemas\n// ---------------------------------------------------------------------------\n\nconst StaticAddIntegrationOutputSchema = Schema.Struct({\n slug: Schema.String,\n name: Schema.String,\n});\nconst StaticGetIntegrationInputSchema = Schema.Struct({\n slug: Schema.String,\n});\nconst StaticGetIntegrationOutputSchema = Schema.Struct({\n integration: Schema.NullOr(Schema.Unknown),\n});\n\nconst StaticAddIntegrationInputStandardSchema = Schema.toStandardSchemaV1(\n Schema.toStandardJSONSchemaV1(GraphqlAddIntegrationInputSchema),\n);\nconst StaticAddIntegrationOutputStandardSchema = Schema.toStandardSchemaV1(\n Schema.toStandardJSONSchemaV1(StaticAddIntegrationOutputSchema),\n);\nconst StaticGetIntegrationInputStandardSchema = Schema.toStandardSchemaV1(\n Schema.toStandardJSONSchemaV1(StaticGetIntegrationInputSchema),\n);\nconst StaticGetIntegrationOutputStandardSchema = Schema.toStandardSchemaV1(\n Schema.toStandardJSONSchemaV1(StaticGetIntegrationOutputSchema),\n);\n\nconst graphqlToolFailure = (code: string, message: string, details?: unknown) =>\n ToolResult.fail({\n code,\n message,\n ...(details === undefined ? {} : { details }),\n });\n\nconst graphqlAuthToolFailure = (failure: GraphqlAuthRequiredError) =>\n authToolFailure({\n code: failure.code,\n message: failure.message,\n source: { id: failure.integration, scope: failure.owner },\n credential: {\n kind: failure.credentialKind,\n ...(failure.credentialLabel ? { label: failure.credentialLabel } : {}),\n connectionId: failure.connection,\n },\n ...(failure.status !== undefined ? { status: failure.status } : {}),\n ...(failure.details !== undefined\n ? {\n upstream: {\n ...(failure.status !== undefined ? { status: failure.status } : {}),\n details: failure.details,\n },\n }\n : {}),\n });\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Match `token` as a separator-bounded run inside a URL hostname or path,\n * used as a low-confidence detection hint when introspection fails. */\nconst urlMatchesToken = (url: URL, token: string): boolean => {\n const re = new RegExp(`(?:^|[^a-z0-9])${token}(?:$|[^a-z0-9])`, \"i\");\n return re.test(url.hostname) || re.test(url.pathname);\n};\n\n/** Derive an integration slug from an endpoint URL. */\nconst slugFromEndpoint = (endpoint: string): string => {\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: URL construction throws; this helper intentionally falls back to the stable default slug\n try {\n const url = new URL(endpoint);\n return url.hostname.replace(/[^a-z0-9]+/gi, \"_\").toLowerCase();\n } catch {\n return \"graphql\";\n }\n};\n\nconst formatTypeRef = (ref: IntrospectionTypeRef): string =>\n Match.value(ref.kind).pipe(\n Match.when(\"NON_NULL\", () => (ref.ofType ? `${formatTypeRef(ref.ofType)}!` : \"Unknown!\")),\n Match.when(\"LIST\", () => (ref.ofType ? `[${formatTypeRef(ref.ofType)}]` : \"[Unknown]\")),\n Match.option,\n Option.getOrElse(() => ref.name ?? \"Unknown\"),\n );\n\nconst unwrapTypeName = (ref: IntrospectionTypeRef): string => {\n if (ref.name) return ref.name;\n if (ref.ofType) return unwrapTypeName(ref.ofType);\n return \"Unknown\";\n};\n\n// Composite (output) types require a sub-selection; leaves (scalars/enums) must\n// not have one. Anything we cannot resolve in the type map is treated as a leaf\n// (custom scalars live in the map as SCALAR; truly-unknown types are rare).\nconst isCompositeType = (\n ref: IntrospectionTypeRef,\n types: ReadonlyMap<string, IntrospectionType>,\n): boolean => {\n const kind = types.get(unwrapTypeName(ref))?.kind;\n return kind === \"OBJECT\" || kind === \"INTERFACE\" || kind === \"UNION\";\n};\n\n// A field whose argument is non-null without a default cannot be selected by the\n// generator: it has no value to pass and emitting the field without the argument\n// is invalid (e.g. GitLab's `metadata.featureFlags(names:)`). Root-field required\n// arguments are different: those are threaded as operation variables (and\n// surfaced on the tool's input schema) in `buildOperationStringForField`.\nconst hasRequiredArgWithoutDefault = (field: IntrospectionField): boolean =>\n field.args.some(\n (arg: IntrospectionInputValue) => arg.type.kind === \"NON_NULL\" && arg.defaultValue == null,\n );\n\n// Build the DEFAULT selection set for a field's return type: every scalar/enum\n// leaf the generator can select without arguments. It deliberately does NOT\n// recurse into composite fields or guess at nested selections, for two reasons:\n// - A real schema (GitLab has 4000+ types) makes any recursive auto-expansion\n// either arbitrary (which N fields? how deep?) or so large the server\n// rejects it for exceeding its query-complexity budget.\n// - A bounded-but-arbitrary selection silently freezes a partial view at sync\n// time. Instead, callers that want nested or list data pass an explicit\n// `select` (see buildOperationStringForField / invoke), so the choice of\n// deeper fields is the caller's, not a guess baked into the tool.\n// The result is always valid: selecting only leaves never needs a sub-selection,\n// and a composite type with no selectable leaves falls back to `__typename`.\nconst buildDefaultSelectionSet = (\n ref: IntrospectionTypeRef,\n types: ReadonlyMap<string, IntrospectionType>,\n): string => {\n const objectType = types.get(unwrapTypeName(ref));\n if (!objectType?.fields) return \"\"; // scalar / enum / unknown: no selection\n if (objectType.kind === \"SCALAR\" || objectType.kind === \"ENUM\") return \"\";\n\n const leaves = objectType.fields\n .filter(\n (f: IntrospectionField) =>\n !f.name.startsWith(\"__\") &&\n !hasRequiredArgWithoutDefault(f) &&\n !isCompositeType(f.type, types),\n )\n .map((f: IntrospectionField) => f.name);\n\n // A composite type MUST have a non-empty selection; `__typename` is a leaf\n // that exists on every composite, so it is a safe minimal fallback.\n return leaves.length > 0 ? `{ ${leaves.join(\" \")} }` : \"{ __typename }\";\n};\n\n// Name every generated operation: some servers reject anonymous operations, and\n// APM tooling keys traces off the operation name. Field names are already valid\n// GraphQL name tokens, so the upper-cased field name is a safe operation name.\nconst operationNameForField = (fieldName: string): string =>\n fieldName.charAt(0).toUpperCase() + fieldName.slice(1);\n\ninterface BuiltOperation {\n /** The operation with the default (scalar-leaf) selection. */\n readonly operationString: string;\n /** Everything up to (not including) the field's selection set:\n * `query Op($a: T) { field(a: $a)`. A caller-supplied `select` is wrapped as\n * `{ <select> }` and spliced between this prefix and the suffix at invoke\n * time, so the selection can be chosen per call without re-introspecting. */\n readonly operationPrefix: string;\n /** Closes the operation: ` }`. */\n readonly operationSuffix: string;\n}\n\nconst buildOperationStringForField = (\n kind: GraphqlOperationKind,\n field: IntrospectionField,\n types: ReadonlyMap<string, IntrospectionType>,\n): BuiltOperation => {\n const opType = kind === \"query\" ? \"query\" : \"mutation\";\n const opName = operationNameForField(field.name);\n\n const varDefs = field.args.map((arg) => {\n const typeName = formatTypeRef(arg.type);\n return `$${arg.name}: ${typeName}`;\n });\n\n const argPasses = field.args.map((arg) => `${arg.name}: $${arg.name}`);\n const defaultSelection = buildDefaultSelectionSet(field.type, types);\n\n const varDefsStr = varDefs.length > 0 ? `(${varDefs.join(\", \")})` : \"\";\n const argPassStr = argPasses.length > 0 ? `(${argPasses.join(\", \")})` : \"\";\n\n const operationPrefix = `${opType} ${opName}${varDefsStr} { ${field.name}${argPassStr}`;\n const operationSuffix = ` }`;\n const operationString = `${operationPrefix}${defaultSelection ? ` ${defaultSelection}` : \"\"}${operationSuffix}`;\n\n return { operationString, operationPrefix, operationSuffix };\n};\n\ninterface PreparedOperation {\n readonly toolName: string;\n readonly description: string;\n readonly inputSchema: unknown;\n readonly binding: OperationBinding;\n}\n\n// Surface an optional `select` input on every tool so a caller can choose the\n// return fields per call. The default operation selects only scalar leaves; to\n// fetch nested or list data the caller passes a GraphQL selection set here, which\n// is spliced into the operation at invoke time. A real field argument named\n// `select` (rare) is left untouched.\nconst withSelectInput = (inputSchema: unknown, returnTypeName: string): unknown => {\n const base =\n inputSchema && typeof inputSchema === \"object\"\n ? (inputSchema as Record<string, unknown>)\n : { type: \"object\", properties: {} };\n const properties = {\n ...((base.properties as Record<string, unknown> | undefined) ?? {}),\n };\n if (!(\"select\" in properties)) {\n properties.select = {\n type: \"string\",\n description: `Optional GraphQL selection set for the \\`${returnTypeName}\\` return type. Overrides the default, which selects only scalar fields. Provide the fields to return, with sub-selections for nested objects and arguments where required, e.g. \"id name items { id title }\". Omit for the default.`,\n };\n }\n return { ...base, type: \"object\", properties };\n};\n\nconst prepareOperations = (\n fields: readonly ExtractedField[],\n introspection: IntrospectionResult,\n): readonly PreparedOperation[] => {\n const typeMap = new Map<string, IntrospectionType>();\n for (const t of introspection.__schema.types) {\n typeMap.set(t.name, t);\n }\n\n const fieldMap = new Map<string, { kind: GraphqlOperationKind; field: IntrospectionField }>();\n const schema = introspection.__schema;\n for (const rootKind of [\"query\", \"mutation\"] as const) {\n const typeName = rootKind === \"query\" ? schema.queryType?.name : schema.mutationType?.name;\n if (!typeName) continue;\n const rootType = typeMap.get(typeName);\n if (!rootType?.fields) continue;\n for (const f of rootType.fields) {\n if (!f.name.startsWith(\"__\")) {\n fieldMap.set(`${rootKind}.${f.name}`, { kind: rootKind, field: f });\n }\n }\n }\n\n return fields.map((extracted) => {\n const prefix = extracted.kind === \"mutation\" ? \"mutation\" : \"query\";\n // A tool's name keeps its `<kind>.<field>` path (e.g. `query.hello`,\n // `mutation.setGreeting`). The address grammar treats `<tool>` as the\n // trailing remainder (see parseToolAddress), so the dot nests naturally.\n const toolName = `${prefix}.${extracted.fieldName}`;\n const description = Option.getOrElse(\n extracted.description,\n () => `GraphQL ${extracted.kind}: ${extracted.fieldName} -> ${extracted.returnTypeName}`,\n );\n\n const key = `${extracted.kind}.${extracted.fieldName}`;\n const entry = fieldMap.get(key);\n const built = entry\n ? buildOperationStringForField(entry.kind, entry.field, typeMap)\n : {\n operationString: `${extracted.kind} ${operationNameForField(extracted.fieldName)} { ${extracted.fieldName} }`,\n operationPrefix: undefined,\n operationSuffix: undefined,\n };\n\n const binding = OperationBinding.make({\n kind: extracted.kind,\n fieldName: extracted.fieldName,\n operationString: built.operationString,\n variableNames: extracted.arguments.map((a) => a.name),\n ...(built.operationPrefix !== undefined && built.operationSuffix !== undefined\n ? { operationPrefix: built.operationPrefix, operationSuffix: built.operationSuffix }\n : {}),\n });\n\n return {\n toolName,\n description,\n inputSchema: withSelectInput(\n Option.getOrUndefined(extracted.inputSchema),\n extracted.returnTypeName,\n ),\n binding,\n };\n });\n};\n\nconst annotationsFor = (binding: OperationBinding): ToolAnnotations => {\n if (binding.kind === \"mutation\") {\n return {\n requiresApproval: true,\n approvalDescription: `mutation ${binding.fieldName}`,\n };\n }\n return {};\n};\n\n// ---------------------------------------------------------------------------\n// Auth method rendering (D11) — apply the connection's resolved values through\n// the method the connection references. An oauth2 method is the conventional\n// bearer placement (with the method's optional header/prefix override) over\n// the resolved access token; an apikey method renders its declared placements.\n// ---------------------------------------------------------------------------\n\nconst renderGraphqlAuthMethod = (\n method: GraphqlAuthMethod,\n values: Record<string, string | null>,\n): RenderedAuthPlacements => {\n if (method.kind === \"apikey\") return renderAuthPlacements(method.placements, values);\n if (method.kind === \"oauth2\") {\n return renderAuthPlacements([oauthBearerPlacement(method.header, method.prefix)], values);\n }\n return { headers: {}, queryParams: {} };\n};\n\n// ---------------------------------------------------------------------------\n// Introspection — produce operations from a config (live or stored JSON).\n// ---------------------------------------------------------------------------\n\nconst buildToolDefs = (prepared: readonly PreparedOperation[]): readonly ToolDef[] =>\n prepared.map((p) => ({\n name: ToolName.make(p.toolName),\n description: p.description,\n inputSchema: p.inputSchema,\n annotations: annotationsFor(p.binding),\n }));\n\nconst toStoredOperations = (\n slug: IntegrationSlug,\n prepared: readonly PreparedOperation[],\n): StoredOperation[] =>\n prepared.map((p) => ({\n toolName: p.toolName,\n integration: String(slug),\n binding: p.binding,\n }));\n\n/** Render an integration's static + resolved-credential auth onto introspection\n * headers/query params. Connection-create / tool-generation introspection runs\n * with the connection's credential (exactly how its tools are invoked), so an\n * auth-required endpoint introspects successfully here rather than at add-time. */\nconst introspectHeadersForConnection = (\n config: GraphqlIntegrationConfig,\n values: Record<string, string | null>,\n templateSlug: AuthTemplateSlug | null,\n): RenderedAuthPlacements => {\n const headers: Record<string, string> = { ...(config.headers ?? {}) };\n const queryParams: Record<string, string> = { ...(config.queryParams ?? {}) };\n // Render the exact method the connection references; with no slug\n // (connection row not yet persisted) fall back to the first declared.\n const method =\n (templateSlug !== null\n ? config.authenticationTemplate.find(\n (m: GraphqlAuthMethod) => m.slug === String(templateSlug),\n )\n : undefined) ?? config.authenticationTemplate[0];\n if (method) {\n const rendered = renderGraphqlAuthMethod(method, values);\n Object.assign(headers, rendered.headers);\n Object.assign(queryParams, rendered.queryParams);\n }\n return { headers, queryParams };\n};\n\n/** Resolve a config's introspection snapshot text from the plugin blob store\n * (`introspectionHash`). Null when the integration has no snapshot (live\n * introspection territory). Pre-blob rows that inlined the JSON are\n * rewritten by the introspection-to-blob migrations before this code reads\n * them. */\nconst loadIntrospectionJson = (\n storage: GraphqlStore,\n config: GraphqlIntegrationConfig,\n): Effect.Effect<string | null, StorageFailure> =>\n config.introspectionHash != null\n ? storage.getIntrospection(config.introspectionHash)\n : Effect.succeed(null);\n\n/** Introspect a config live or from its stored snapshot, applying connection\n * auth. A non-null `introspectionJson` (loaded via `loadIntrospectionJson`)\n * short-circuits the network; otherwise this introspects the endpoint with\n * the rendered credential. */\nconst introspectForConnection = (\n config: GraphqlIntegrationConfig,\n introspectionJson: string | null,\n values: Record<string, string | null>,\n templateSlug: AuthTemplateSlug | null,\n httpClientLayer: Layer.Layer<HttpClient.HttpClient>,\n): Effect.Effect<IntrospectionResult, GraphqlIntrospectionError> => {\n if (introspectionJson != null) {\n return parseIntrospectionJson(introspectionJson);\n }\n const auth = introspectHeadersForConnection(config, values, templateSlug);\n return introspect(\n config.endpoint,\n Object.keys(auth.headers).length > 0 ? auth.headers : undefined,\n Object.keys(auth.queryParams).length > 0 ? auth.queryParams : undefined,\n ).pipe(Effect.provide(httpClientLayer));\n};\n\n/** Introspect an integration's endpoint (with this connection's credential),\n * prepare its operations, persist the bindings, and return them. Invoked from\n * `invokeTool` on a cache miss — i.e. when an integration was registered\n * without an add-time schema and its bindings haven't been produced yet. */\nconst materializeOperations = (\n ctx: PluginCtx<GraphqlStore>,\n integration: string,\n config: GraphqlIntegrationConfig,\n credential: {\n readonly template: AuthTemplateSlug;\n readonly values: Record<string, string | null>;\n },\n httpClientLayer: Layer.Layer<HttpClient.HttpClient>,\n): Effect.Effect<readonly StoredOperation[], GraphqlIntrospectionError | StorageFailure> =>\n Effect.gen(function* () {\n // Render the exact method this connection references (we have its slug\n // here, unlike `resolveTools`) so an auth-required endpoint introspects.\n const method = config.authenticationTemplate.find(\n (m: GraphqlAuthMethod) => m.slug === String(credential.template),\n );\n const headers: Record<string, string> = { ...(config.headers ?? {}) };\n const queryParams: Record<string, string> = {\n ...(config.queryParams ?? {}),\n };\n if (method) {\n const rendered = renderGraphqlAuthMethod(method, credential.values);\n Object.assign(headers, rendered.headers);\n Object.assign(queryParams, rendered.queryParams);\n }\n\n const introspectionJson = yield* loadIntrospectionJson(ctx.storage, config);\n const introspection =\n introspectionJson != null\n ? yield* parseIntrospectionJson(introspectionJson)\n : yield* introspect(\n config.endpoint,\n Object.keys(headers).length > 0 ? headers : undefined,\n Object.keys(queryParams).length > 0 ? queryParams : undefined,\n ).pipe(Effect.provide(httpClientLayer));\n\n const { result } = yield* extract(introspection).pipe(\n Effect.catch(() =>\n Effect.succeed({\n result: { fields: [] as readonly ExtractedField[] },\n } as {\n readonly result: { readonly fields: readonly ExtractedField[] };\n }),\n ),\n );\n const prepared = prepareOperations(result.fields, introspection);\n const stored = toStoredOperations(IntegrationSlug.make(integration), prepared);\n yield* ctx.storage.replaceOperations(integration, stored);\n return stored;\n });\n\n// ---------------------------------------------------------------------------\n// Declared auth methods — project the stored `authenticationTemplate` into the\n// catalog's plugin-agnostic `AuthMethodDescriptor[]`. Pure/sync and tolerant of\n// a malformed or foreign config blob (returns `[]`). GraphQL has no accounts\n// slot of its own, so this projection is what surfaces declared + custom methods\n// through the catalog's `authMethods` to the hub / Add-account flows. Exported\n// for tests.\n//\n// none → a no-auth method carrying no credential inputs\n// apikey → carried placements (headers / query params) verbatim\n// oauth2 → one oauth method (no resolved endpoints; graphql renders the\n// connection value as a bearer at invoke time).\n// ---------------------------------------------------------------------------\n\nexport const describeGraphqlAuthMethods = (\n record: IntegrationRecord,\n): readonly AuthMethodDescriptor[] => {\n const config = Option.getOrUndefined(decodeGraphqlIntegrationConfigOption(record.config));\n if (!config) return [];\n return config.authenticationTemplate.map((method: GraphqlAuthMethod): AuthMethodDescriptor => {\n if (method.kind === \"apikey\") return describeApiKeyAuthMethod(method);\n if (method.kind === \"oauth2\") {\n return {\n id: method.slug,\n label: \"OAuth\",\n kind: \"oauth\",\n template: method.slug,\n oauth: {},\n };\n }\n return describeNoneAuthMethod(method.slug);\n });\n};\n\nexport const describeGraphqlIntegrationDisplay = (\n record: IntegrationRecord,\n): { readonly url?: string } => {\n const config = Option.getOrUndefined(decodeGraphqlIntegrationConfigOption(record.config));\n return { url: config?.endpoint };\n};\n\n// ---------------------------------------------------------------------------\n// Plugin extension\n// ---------------------------------------------------------------------------\n\n// The extension only registers integrations (and parses any pre-supplied\n// introspection JSON offline). Live introspection — the only thing that needed\n// an HTTP layer — is deferred to `resolveTools` / `invokeTool`, so the extension\n// no longer takes one.\nconst makeGraphqlExtension = (ctx: PluginCtx<GraphqlStore>) => {\n const buildConfig = (input: GraphqlAddIntegrationInput): GraphqlIntegrationConfig =>\n GraphqlIntegrationConfig.make({\n endpoint: input.endpoint,\n name: input.name?.trim() || slugFromEndpoint(input.endpoint),\n ...(input.headers !== undefined ? { headers: input.headers } : {}),\n ...(input.queryParams !== undefined ? { queryParams: input.queryParams } : {}),\n authenticationTemplate: input.authenticationTemplate\n ? normalizeGraphqlAuthMethods(input.authenticationTemplate)\n : [],\n });\n\n /** Register the integration in the catalog. Registering a source is a\n * catalog statement (\"we use this GraphQL endpoint now\") and MUST NOT make a\n * network call or require auth — exactly like MCP defers discovery. Live\n * introspection (and the operation bindings it yields) is deferred to\n * connection-create / tool-generation (`resolveTools`) and tool invocation\n * (`invokeTool`), where a connection's credential is available.\n *\n * When the caller pre-supplies `introspectionJson`, the schema is already in\n * hand, so we parse it offline (no network) and persist the operation\n * bindings up front. */\n const addIntegrationInternal = (input: GraphqlAddIntegrationInput) =>\n Effect.gen(function* () {\n const slug = IntegrationSlug.make(input.slug ?? slugFromEndpoint(input.endpoint));\n\n // Block re-adding an existing slug. The core `integrations.register`\n // primitive upserts (so boot re-registration is idempotent), but an\n // explicit add must NOT silently clobber an existing integration's tools,\n // connections, and policies. To add more auth, update the existing one.\n const existing = yield* ctx.core.integrations.get(slug);\n if (existing) {\n return yield* new IntegrationAlreadyExistsError({ slug });\n }\n\n return yield* addIntegrationTransaction(input, slug);\n });\n\n const addIntegrationTransaction = (input: GraphqlAddIntegrationInput, slug: IntegrationSlug) =>\n Effect.gen(function* () {\n const baseConfig = buildConfig(input);\n\n // No pre-supplied schema → register WITHOUT introspecting. Tools (and\n // their operation bindings) are produced lazily when a connection is\n // created (`resolveTools`) / a tool is first invoked (`invokeTool`),\n // using that connection's credential.\n if (input.introspectionJson === undefined) {\n yield* ctx.transaction(\n ctx.core.integrations.register({\n slug,\n name: baseConfig.name,\n description: input.description?.trim() || baseConfig.name,\n config: baseConfig,\n canRemove: true,\n canRefresh: true,\n }),\n );\n return { slug: String(slug), name: baseConfig.name, toolCount: 0 };\n }\n\n // Pre-supplied introspection JSON: parse it offline (no network) and\n // persist the operation bindings + snapshot so production stays offline.\n const introspection = yield* parseIntrospectionJson(input.introspectionJson);\n const { result } = yield* extract(introspection);\n const prepared = prepareOperations(result.fields, introspection);\n\n // Snapshot the resolved schema so tool production never needs a live\n // HTTP layer (D6: tools are spec-derived and identical per connection).\n // The snapshot text goes to the plugin blob store (content-addressed,\n // written OUTSIDE the transaction — re-puts are idempotent and an\n // aborted register leaves only an unreferenced blob), and the config\n // carries only its hash.\n const snapshotJson = JSON.stringify({ data: introspection });\n const introspectionHash = yield* sha256Hex(snapshotJson);\n const config = GraphqlIntegrationConfig.make({\n ...baseConfig,\n introspectionHash,\n });\n\n yield* ctx.storage.putIntrospection(introspectionHash, snapshotJson);\n\n yield* ctx.transaction(\n Effect.gen(function* () {\n yield* ctx.storage.replaceOperations(String(slug), toStoredOperations(slug, prepared));\n\n // Prefill order: caller's description, then the schema's own\n // description (present when introspection ran with schema\n // descriptions), then the display name.\n const schemaDescription =\n typeof (introspection as { description?: unknown }).description === \"string\"\n ? ((introspection as { description?: string }).description ?? \"\").trim()\n : \"\";\n yield* ctx.core.integrations.register({\n slug,\n name: config.name,\n description: input.description?.trim() || schemaDescription || config.name,\n config,\n canRemove: true,\n canRefresh: true,\n });\n }),\n );\n\n return {\n slug: String(slug),\n name: config.name,\n toolCount: prepared.length,\n };\n });\n\n const configureIntegration = (slug: string, input: GraphqlConfigureInput) =>\n Effect.gen(function* () {\n const record = yield* ctx.core.integrations.get(IntegrationSlug.make(slug));\n if (!record) return;\n const current = Option.getOrElse(\n // best-effort: re-decode the stored config, falling back to an\n // endpoint-only config if it was never set.\n yield* decodeGraphqlIntegrationConfig(record.config).pipe(Effect.option),\n () =>\n GraphqlIntegrationConfig.make({\n endpoint: \"\",\n name: record.description,\n authenticationTemplate: [],\n }),\n );\n\n const next = GraphqlIntegrationConfig.make({\n endpoint: input.endpoint ?? current.endpoint,\n name: input.name?.trim() || current.name,\n ...(current.introspectionHash !== undefined\n ? { introspectionHash: current.introspectionHash }\n : {}),\n ...((input.headers ?? current.headers) !== undefined\n ? { headers: input.headers ?? current.headers }\n : {}),\n ...((input.queryParams ?? current.queryParams) !== undefined\n ? { queryParams: input.queryParams ?? current.queryParams }\n : {}),\n authenticationTemplate: input.authenticationTemplate\n ? normalizeGraphqlAuthMethods(input.authenticationTemplate)\n : current.authenticationTemplate,\n });\n\n yield* ctx.core.integrations.update(IntegrationSlug.make(slug), {\n description: next.name,\n config: next,\n });\n });\n\n /** Read the integration's decoded config (or `null` when absent / malformed).\n * Surfaces `authenticationTemplate` for the configure / custom-method UX. */\n const getConfig = (\n slug: string,\n ): Effect.Effect<GraphqlIntegrationConfig | null, StorageFailure> =>\n ctx.core.integrations\n .get(IntegrationSlug.make(slug))\n .pipe(\n Effect.map((record) =>\n record ? Option.getOrNull(decodeGraphqlIntegrationConfigOption(record.config)) : null,\n ),\n );\n\n /** Merge-append custom auth methods onto the integration's existing\n * `authenticationTemplate`. Returns the merged array. A no-op (returns `[]`)\n * for an unknown slug or undecodable config. */\n const configureAuthMethods = (\n slug: string,\n input: GraphqlConfigureAuthInput,\n ): Effect.Effect<readonly GraphqlAuthMethod[], StorageFailure> =>\n ctx.transaction(\n Effect.gen(function* () {\n const record = yield* ctx.core.integrations.get(IntegrationSlug.make(slug));\n if (!record) return [] as readonly GraphqlAuthMethod[];\n const current = Option.getOrNull(decodeGraphqlIntegrationConfigOption(record.config));\n if (!current) return [] as readonly GraphqlAuthMethod[];\n\n // Replace mode declares the full set — backfill kind-based slugs.\n // Merge mode appends: `mergeAuthTemplates` replaces on slug match and\n // assigns fresh `custom_<id>` slugs to slug-less entries, so a custom\n // method never silently displaces a declared one.\n const merged =\n input.mode === \"replace\"\n ? normalizeGraphqlAuthMethods(input.authenticationTemplate)\n : mergeAuthTemplates(\n current.authenticationTemplate,\n expandGraphqlAuthMethodInputs(\n input.authenticationTemplate,\n ) as readonly GraphqlAuthMethod[],\n );\n\n const next = GraphqlIntegrationConfig.make({\n ...current,\n authenticationTemplate: merged,\n });\n\n yield* ctx.core.integrations.update(IntegrationSlug.make(slug), {\n config: next,\n });\n\n return merged;\n }),\n );\n\n return {\n /** Register a GraphQL integration (introspects + persists operations). */\n addIntegration: (input: GraphqlAddIntegrationInput) => addIntegrationInternal(input),\n\n /** Read the integration's stored config. */\n getIntegration: (slug: string) =>\n ctx.core.integrations\n .get(IntegrationSlug.make(slug))\n .pipe(Effect.map((record) => (record ? record.config : null))),\n\n /** Read the integration's decoded config (auth templates surfaced). */\n getConfig,\n\n /** Merge-append custom auth methods (custom-method-create flow). */\n configureAuth: configureAuthMethods,\n\n removeIntegration: (slug: string) =>\n ctx.transaction(\n Effect.gen(function* () {\n yield* ctx.storage.removeOperations(slug);\n yield* ctx.core.integrations\n .remove(IntegrationSlug.make(slug))\n .pipe(Effect.catchTag(\"IntegrationRemovalNotAllowedError\", () => Effect.void));\n }),\n ),\n\n configure: configureIntegration,\n };\n};\n\nexport type GraphqlPluginExtension = ReturnType<typeof makeGraphqlExtension>;\n\n// ---------------------------------------------------------------------------\n// Plugin factory\n// ---------------------------------------------------------------------------\n\nexport interface GraphqlPluginOptions {\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;\n}\n\nexport const graphqlPlugin = definePlugin((options?: GraphqlPluginOptions) => {\n return {\n id: GRAPHQL_PLUGIN_ID as \"graphql\",\n packageName: \"@executor-js/plugin-graphql\",\n integrationPresets: graphqlPresets.map((preset) => ({\n id: preset.id,\n name: preset.name,\n summary: preset.summary,\n url: preset.url,\n endpoint: preset.endpoint,\n ...(preset.icon ? { icon: preset.icon } : {}),\n ...(preset.featured ? { featured: preset.featured } : {}),\n })),\n storage: (deps): GraphqlStore => makeDefaultGraphqlStore(deps),\n\n extension: (ctx: PluginCtx<GraphqlStore>) => makeGraphqlExtension(ctx),\n\n integrationConfigure: {\n type: \"graphql\",\n schema: GraphqlConfigureInputSchema,\n configure: ({ ctx, integration, config }) =>\n makeGraphqlExtension(ctx).configure(String(integration), config as GraphqlConfigureInput),\n },\n\n describeAuthMethods: describeGraphqlAuthMethods,\n describeIntegrationDisplay: describeGraphqlIntegrationDisplay,\n\n staticSources: (self: GraphqlPluginExtension) => [\n {\n id: \"graphql\",\n kind: \"executor\",\n name: \"GraphQL\",\n tools: [\n {\n name: \"getIntegration\",\n description:\n \"Inspect an existing GraphQL integration, including endpoint, static headers/query params, and auth templates. Use this before repairing an integration with `graphql.configure` or creating a connection.\",\n inputSchema: StaticGetIntegrationInputStandardSchema,\n outputSchema: StaticGetIntegrationOutputStandardSchema,\n handler: ({ args }) => {\n const input = args as typeof StaticGetIntegrationInputSchema.Type;\n return Effect.map(self.getIntegration(input.slug), (integration) =>\n ToolResult.ok({ integration }),\n );\n },\n },\n {\n name: \"addIntegration\",\n description:\n \"Add a GraphQL endpoint to the catalog and register its operations. Introspects the endpoint (or uses provided introspection JSON). After adding, create an owner-scoped connection against the integration to materialize its per-connection tools. For API keys / bearer tokens, declare an `authenticationTemplate` and create a connection whose value is the token.\",\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Add a GraphQL integration\",\n },\n inputSchema: StaticAddIntegrationInputStandardSchema,\n outputSchema: StaticAddIntegrationOutputStandardSchema,\n handler: ({ args }) => {\n const input = args as GraphqlAddIntegrationInput;\n return self.addIntegration(input).pipe(\n Effect.map((result) => ToolResult.ok({ slug: result.slug, name: result.name })),\n Effect.catchTags({\n GraphqlIntrospectionError: ({ message }) =>\n Effect.succeed(graphqlToolFailure(\"graphql_introspection_failed\", message)),\n GraphqlExtractionError: ({ message }) =>\n Effect.succeed(graphqlToolFailure(\"graphql_extraction_failed\", message)),\n IntegrationAlreadyExistsError: ({ slug }: IntegrationAlreadyExistsError) =>\n Effect.succeed(\n graphqlToolFailure(\n \"integration_already_exists\",\n `Integration ${slug} already exists; update it instead of re-adding.`,\n ),\n ),\n }),\n );\n },\n },\n ],\n },\n ],\n\n // -----------------------------------------------------------------------\n // Per-connection tool production. THIS is where a GraphQL integration is\n // introspected — when a connection is created (or refreshed), with that\n // connection's credential — yielding one ToolDef per operation. Registering\n // the integration in the catalog makes no network call; discovery is\n // deferred to here, exactly how MCP defers tool discovery to connect time.\n // The introspected schema is identical across connections, so `invokeTool`\n // re-derives the same operation bindings; only the credential differs.\n // -----------------------------------------------------------------------\n resolveTools: ({\n config,\n template,\n storage,\n getValues,\n httpClientLayer,\n }: {\n readonly config: IntegrationConfig;\n readonly template: AuthTemplateSlug | null;\n readonly storage: GraphqlStore;\n readonly getValues: () => Effect.Effect<Record<string, string | null>, unknown>;\n readonly httpClientLayer: Layer.Layer<HttpClient.HttpClient>;\n }) =>\n Effect.gen(function* () {\n const decoded = yield* decodeGraphqlIntegrationConfig(config).pipe(Effect.option);\n if (Option.isNone(decoded)) return { tools: [] };\n const graphqlConfig = decoded.value;\n const introspectionJson = yield* loadIntrospectionJson(storage, graphqlConfig);\n // Live introspection (no stored snapshot) needs the connection's\n // credential inputs for auth-required endpoints; resolve them lazily.\n const values =\n introspectionJson == null\n ? yield* getValues().pipe(\n Effect.catch(() => Effect.succeed({} as Record<string, string | null>)),\n )\n : ({} as Record<string, string | null>);\n const introspection = yield* introspectForConnection(\n graphqlConfig,\n introspectionJson,\n values,\n template,\n options?.httpClientLayer ?? httpClientLayer,\n ).pipe(Effect.option);\n if (Option.isNone(introspection)) return { tools: [] };\n const extracted = yield* extract(introspection.value).pipe(Effect.option);\n if (Option.isNone(extracted)) return { tools: [] };\n const prepared = prepareOperations(extracted.value.result.fields, introspection.value);\n return {\n tools: buildToolDefs(prepared),\n definitions: extracted.value.definitions,\n };\n }).pipe(Effect.catch(() => Effect.succeed({ tools: [] as readonly ToolDef[] }))),\n\n // -----------------------------------------------------------------------\n // Invoke one of a connection's tools. Look up the operation by integration\n // + tool name, render the credential through the connection's auth\n // template, and execute the GraphQL request.\n // -----------------------------------------------------------------------\n invokeTool: ({ ctx, toolRow, credential, args }) =>\n Effect.gen(function* () {\n const httpClientLayer = options?.httpClientLayer ?? ctx.httpClientLayer;\n const integration = toolRow.integration;\n const toolName = toolRow.name;\n\n const config = yield* decodeGraphqlIntegrationConfig(credential.config).pipe(\n Effect.mapError(\n () =>\n new GraphqlInvocationError({\n message: `Invalid GraphQL integration config for \"${integration}\"`,\n statusCode: Option.none(),\n }),\n ),\n );\n\n // Operation bindings are produced lazily for integrations registered\n // without an add-time schema (no network at catalog registration). On a\n // cache miss, introspect with this connection's credential, persist the\n // bindings, then resolve the requested tool — discovery/persistence are\n // deferred to first use, mirroring MCP.\n let op = yield* ctx.storage.getOperation(integration, toolName);\n if (!op) {\n op = yield* materializeOperations(\n ctx,\n integration,\n config,\n credential,\n httpClientLayer,\n ).pipe(Effect.map((ops) => ops.find((o) => o.toolName === toolName) ?? null));\n }\n if (!op) {\n return yield* new GraphqlInvocationError({\n message: `No GraphQL operation found for tool \"${integration}.${toolName}\"`,\n statusCode: Option.none(),\n });\n }\n\n // Parse-check a caller-supplied `select` locally, before any network\n // call: reject a malformed selection (and any attempt to break out of the\n // field's selection set) with a precise error instead of a confusing\n // server response. Field- and argument-level validity is left to the\n // server, which returns verbatim errors.\n const selectArg = (args as Record<string, unknown> | undefined)?.select;\n if (typeof selectArg === \"string\" && selectArg.trim().length > 0) {\n const operationString = effectiveOperationString(\n op.binding,\n (args ?? {}) as Record<string, unknown>,\n );\n const selectionErrors = validateOperationString(operationString);\n if (selectionErrors.length > 0) {\n return ToolResult.fail({\n code: \"graphql_invalid_selection\",\n message: selectionErrors[0]!,\n details: { errors: selectionErrors },\n });\n }\n }\n\n const headers: Record<string, string> = { ...(config.headers ?? {}) };\n const queryParams: Record<string, string> = {\n ...(config.queryParams ?? {}),\n };\n\n const method = config.authenticationTemplate.find(\n (m: GraphqlAuthMethod) => m.slug === String(credential.template),\n );\n if (method && method.kind !== \"none\") {\n // A method with unresolved inputs fails the invocation explicitly\n // instead of dialing unauthenticated. oauth2 requires the resolved\n // access token (`token`); apikey requires every placement variable.\n const missing = (\n method.kind === \"oauth2\"\n ? [TOKEN_VARIABLE]\n : requiredPlacementVariables(method.placements)\n ).filter((variable) => credential.values[variable] == null);\n if (missing.length > 0) {\n return yield* new GraphqlAuthRequiredError({\n code:\n method.kind === \"oauth2\" ? \"oauth_connection_missing\" : \"connection_value_missing\",\n message:\n method.kind === \"oauth2\"\n ? `Missing OAuth connection value for GraphQL integration \"${integration}\" (connection \"${credential.connection}\")`\n : `Missing credential value for GraphQL integration \"${integration}\" (connection \"${credential.connection}\") for input(s): ${missing.join(\", \")}`,\n owner: credential.owner,\n integration,\n connection: String(credential.connection),\n credentialKind: method.kind === \"oauth2\" ? \"oauth\" : \"secret\",\n credentialLabel: method.kind === \"oauth2\" ? \"OAuth sign-in\" : \"API key\",\n template: String(credential.template),\n });\n }\n const rendered = renderGraphqlAuthMethod(method, credential.values);\n Object.assign(headers, rendered.headers);\n Object.assign(queryParams, rendered.queryParams);\n }\n\n const result = yield* invokeWithLayer(\n op.binding,\n (args ?? {}) as Record<string, unknown>,\n config.endpoint,\n headers,\n queryParams,\n httpClientLayer,\n );\n\n const errors = decodeGraphqlErrors(result.errors);\n if (errors !== undefined && errors.length > 0) {\n const firstMessage = extractGraphqlErrorMessage(errors);\n return ToolResult.fail({\n code: \"graphql_errors\",\n message: firstMessage !== undefined ? firstMessage : \"GraphQL request returned errors\",\n details: { errors },\n });\n }\n if (result.status < 200 || result.status >= 300) {\n if (result.status === 401 || result.status === 403) {\n return authToolFailure({\n code: \"connection_rejected\",\n status: result.status,\n message: `Upstream rejected credentials for GraphQL integration \"${integration}\" with HTTP ${result.status}. Re-authenticate or update the connection before retrying this tool.`,\n source: { id: integration, scope: credential.owner },\n credential: { kind: \"upstream\", label: \"Upstream authorization\" },\n upstream: {\n status: result.status,\n details: {\n data: result.data,\n errors: result.errors,\n },\n },\n });\n }\n return ToolResult.fail({\n code: \"graphql_http_error\",\n status: result.status,\n message: `GraphQL request failed with HTTP ${result.status}`,\n details: {\n status: result.status,\n data: result.data,\n errors: result.errors,\n },\n });\n }\n return ToolResult.ok(result.data);\n }).pipe(\n Effect.catchTag(\"GraphqlAuthRequiredError\", (error) =>\n Effect.succeed(graphqlAuthToolFailure(error)),\n ),\n ),\n\n // Per-connection cleanup. Operation bindings are catalog-level (shared\n // across an integration's connections), so removing a single connection\n // leaves them in place; the executor drops the connection's tool rows.\n removeConnection: () => Effect.void,\n\n detect: ({ ctx, url }: { readonly ctx: PluginCtx<GraphqlStore>; readonly url: string }) =>\n Effect.gen(function* () {\n const httpClientLayer = options?.httpClientLayer ?? ctx.httpClientLayer;\n const trimmed = url.trim();\n if (!trimmed) return null;\n const parsed = yield* Effect.try({\n try: () => new URL(trimmed),\n catch: (cause) => cause,\n }).pipe(Effect.option);\n if (Option.isNone(parsed)) return null;\n\n const ok = yield* introspect(trimmed).pipe(\n Effect.provide(httpClientLayer),\n Effect.map(() => true),\n Effect.catch(() => Effect.succeed(false)),\n );\n\n const slug = slugFromEndpoint(trimmed);\n\n if (ok) {\n return IntegrationDetectionResult.make({\n kind: \"graphql\",\n confidence: \"high\",\n endpoint: trimmed,\n name: slug,\n slug,\n });\n }\n\n // Low-confidence URL-token fallback. Introspection can fail for many\n // reasons (auth, CORS, the endpoint disabled introspection, transport\n // errors). When the URL itself strongly implies GraphQL, surface a\n // candidate so the user can still pick it.\n if (urlMatchesToken(parsed.value, \"graphql\")) {\n return IntegrationDetectionResult.make({\n kind: \"graphql\",\n confidence: \"low\",\n endpoint: trimmed,\n name: slug,\n slug,\n });\n }\n\n return null;\n }),\n };\n // HTTP transport (routes/handlers/extensionService) is layered on by the\n // api-aware factory in `@executor-js/plugin-graphql/api`.\n});\n","import { parse } from \"graphql\";\n\n// Local validation for a caller-supplied `select` (see invoke / plugin.invokeTool).\n// graphql-js is already a runtime dependency of this plugin, so we reuse its\n// parser to reject a malformed selection before any network round trip, and to\n// catch any attempt to break out of the field's selection set (the spliced text\n// must parse as part of a single operation). Field- and argument-level validity\n// is left to the upstream server, which returns verbatim errors: building a local\n// GraphQLSchema would need a full introspection snapshot, but the stored snapshot\n// is a reduced shape (see introspect.ts) that buildClientSchema cannot consume.\n\n/** Parse-check an assembled operation string. Returns a one-element error array\n * when the selection is not valid GraphQL, or an empty array when it parses. */\nexport const validateOperationString = (operationString: string): readonly string[] => {\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: graphql `parse` throws on a syntax error; the thrown value is reported generically (its message is not extracted, per the typed-error lint rules)\n try {\n parse(operationString);\n return [];\n } catch {\n return [\"`select` is not a valid GraphQL selection set\"];\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,QAAQ,QAAQ,cAAc;AACvC,SAAS,YAAY,yBAAyB;AAQ9C,IAAM,sBAAsB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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,UAAU;AAAA,UACV,MAAM;AAAA,UACN;AAAA,QACF,CAAC;AAAA,MACH;AAEA,aAAO;AAAA,IACT,CAAC;AAAA,EACL;AAGF,CAAC;","names":["raw","Effect","Option","Option","Effect","Effect","Option","HttpClient","HttpClientRequest","Effect","HttpClient","HttpClientRequest","Option","Effect","Option","Schema","Schema","Option","Effect","Effect","Match","Option","Schema","Schema","Option","formatTypeRef","Match","unwrapTypeName","Effect"]}
@@ -56,8 +56,16 @@ var ExtractionResult = Schema2.Struct({
56
56
  var OperationBinding = Schema2.Struct({
57
57
  kind: GraphqlOperationKind,
58
58
  fieldName: Schema2.String,
59
- /** The full GraphQL query/mutation string */
59
+ /** The full GraphQL query/mutation string, with the default scalar-leaf
60
+ * selection. Sent when the caller does not supply a custom `select`. */
60
61
  operationString: Schema2.String,
62
+ /** Operation text up to (not including) the field's selection set, e.g.
63
+ * `query Op($a: T) { field(a: $a)`. With `operationSuffix`, lets `invoke`
64
+ * splice a caller-supplied `select` as `{ <select> }` without re-introspecting.
65
+ * Optional so bindings persisted before this field still decode. */
66
+ operationPrefix: Schema2.optional(Schema2.String),
67
+ /** Closes the operation (` }`); pairs with `operationPrefix`. */
68
+ operationSuffix: Schema2.optional(Schema2.String),
61
69
  /** Ordered variable names for mapping */
62
70
  variableNames: Schema2.Array(Schema2.String)
63
71
  });
@@ -149,4 +157,4 @@ export {
149
157
  decodeGraphqlIntegrationConfigOption,
150
158
  InvocationResult
151
159
  };
152
- //# sourceMappingURL=chunk-732HGFSH.js.map
160
+ //# sourceMappingURL=chunk-JTWENVHO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/errors.ts","../src/sdk/types.ts"],"sourcesContent":["import { Data, Schema } from \"effect\";\nimport type { Option } from \"effect\";\nimport type { AuthToolFailureCode } from \"@executor-js/sdk/core\";\n\nexport class GraphqlIntrospectionError extends Schema.TaggedErrorClass<GraphqlIntrospectionError>()(\n \"GraphqlIntrospectionError\",\n {\n message: Schema.String,\n },\n) {}\n\nexport class GraphqlExtractionError extends Schema.TaggedErrorClass<GraphqlExtractionError>()(\n \"GraphqlExtractionError\",\n {\n message: Schema.String,\n },\n) {}\n\nexport class GraphqlInvocationError extends Data.TaggedError(\"GraphqlInvocationError\")<{\n readonly message: string;\n readonly statusCode: Option.Option<number>;\n readonly cause?: unknown;\n}> {}\n\n/** A tool invocation could not produce a usable credential. Re-keyed for v2:\n * references the connection by (owner, integration, name) instead of a v1\n * source id + scope. */\nexport class GraphqlAuthRequiredError extends Data.TaggedError(\"GraphqlAuthRequiredError\")<{\n readonly code: AuthToolFailureCode;\n readonly message: string;\n readonly owner: string;\n readonly integration: string;\n readonly connection: string;\n readonly credentialKind: \"secret\" | \"oauth\" | \"upstream\";\n readonly credentialLabel?: string;\n readonly template?: string;\n readonly status?: number;\n readonly details?: unknown;\n readonly cause?: unknown;\n}> {}\n","import { Schema } from \"effect\";\nimport {\n ApiKeyAuthTemplate,\n apiKeyMethodFromAuthTemplate,\n isApiKeyAuthTemplate,\n ApiKeyAuthMethod,\n NoneAuthMethod,\n normalizeAuthMethodSlugs,\n} from \"@executor-js/sdk/http-auth\";\n\n// ---------------------------------------------------------------------------\n// GraphQL operation kind\n// ---------------------------------------------------------------------------\n\nexport const GraphqlOperationKind = Schema.Literals([\"query\", \"mutation\"]);\nexport type GraphqlOperationKind = typeof GraphqlOperationKind.Type;\n\n// ---------------------------------------------------------------------------\n// Extracted field (becomes a tool)\n// ---------------------------------------------------------------------------\n\nexport const GraphqlArgument = Schema.Struct({\n name: Schema.String,\n typeName: Schema.String,\n required: Schema.Boolean,\n description: Schema.OptionFromOptional(Schema.String),\n});\nexport type GraphqlArgument = typeof GraphqlArgument.Type;\n\nexport const ExtractedField = Schema.Struct({\n /** e.g. \"user\", \"createUser\" */\n fieldName: Schema.String,\n /** \"query\" or \"mutation\" */\n kind: GraphqlOperationKind,\n description: Schema.OptionFromOptional(Schema.String),\n arguments: Schema.Array(GraphqlArgument),\n /** JSON Schema for the input (built from arguments) */\n inputSchema: Schema.OptionFromOptional(Schema.Unknown),\n /** The return type name for documentation */\n returnTypeName: Schema.String,\n});\nexport type ExtractedField = typeof ExtractedField.Type;\n\nexport const ExtractionResult = Schema.Struct({\n /** Schema name from introspection */\n schemaName: Schema.OptionFromOptional(Schema.String),\n fields: Schema.Array(ExtractedField),\n});\nexport type ExtractionResult = typeof ExtractionResult.Type;\n\n// ---------------------------------------------------------------------------\n// Operation binding — minimal data needed to invoke\n// ---------------------------------------------------------------------------\n\nexport const OperationBinding = Schema.Struct({\n kind: GraphqlOperationKind,\n fieldName: Schema.String,\n /** The full GraphQL query/mutation string, with the default scalar-leaf\n * selection. Sent when the caller does not supply a custom `select`. */\n operationString: Schema.String,\n /** Operation text up to (not including) the field's selection set, e.g.\n * `query Op($a: T) { field(a: $a)`. With `operationSuffix`, lets `invoke`\n * splice a caller-supplied `select` as `{ <select> }` without re-introspecting.\n * Optional so bindings persisted before this field still decode. */\n operationPrefix: Schema.optional(Schema.String),\n /** Closes the operation (` }`); pairs with `operationPrefix`. */\n operationSuffix: Schema.optional(Schema.String),\n /** Ordered variable names for mapping */\n variableNames: Schema.Array(Schema.String),\n});\nexport type OperationBinding = typeof OperationBinding.Type;\n\n// ---------------------------------------------------------------------------\n// Auth methods — the shared placements vocabulary (`@executor-js/sdk/http-auth`)\n// plus GraphQL's own oauth variant. The integration's\n// `config.authenticationTemplate` declares zero or more methods, each with a\n// stable `slug` a connection binds against (`connection.template`). There are\n// no secret slots and no credential bindings — a connection IS the credential,\n// and the plugin renders its resolved values onto the request through the\n// bound method (D11).\n//\n// none — no credential (open endpoint)\n// apikey — render the connection's values through the method's header/query\n// placements (one credential input per distinct placement\n// `variable`; a method may mix carriers — e.g. a bearer header\n// plus a team-id query param)\n// oauth2 — the value is an OAuth access token, applied as a bearer header\n// (optionally overriding the header name / prefix). GraphQL oauth\n// stores no endpoints — only how the token is rendered.\n// ---------------------------------------------------------------------------\n\n/** An OAuth bearer method: write `<header>: <prefix><access-token>`. The\n * resolved (and refreshed) access token is the connection's `token` value. */\nexport const GraphqlOAuthMethod = Schema.Struct({\n kind: Schema.Literal(\"oauth2\"),\n slug: Schema.String,\n /** The header to write the bearer token to. Defaults to `Authorization`. */\n header: Schema.optional(Schema.String),\n /** The token prefix. Defaults to `Bearer `. */\n prefix: Schema.optional(Schema.String),\n});\nexport type GraphqlOAuthMethod = typeof GraphqlOAuthMethod.Type;\n\nexport const GraphqlAuthMethod = Schema.Union([\n NoneAuthMethod,\n ApiKeyAuthMethod,\n GraphqlOAuthMethod,\n]);\nexport type GraphqlAuthMethod = typeof GraphqlAuthMethod.Type;\n\n/** Input variant of `GraphqlAuthMethod` — callers (UI, agents) may omit the\n * slug; `normalizeGraphqlAuthMethods` backfills it. */\nexport const GraphqlAuthMethodInput = Schema.Union([\n Schema.Struct({ slug: Schema.optional(Schema.String), kind: Schema.Literal(\"none\") }),\n Schema.Struct({\n slug: Schema.optional(Schema.String),\n kind: Schema.Literal(\"oauth2\"),\n header: Schema.optional(Schema.String),\n prefix: Schema.optional(Schema.String),\n }),\n // Credential methods are authored request-shaped — the ONE apikey input\n // dialect: `{ type: \"apiKey\", headers: { Authorization: [\"Bearer \",\n // variable(\"token\")] }, queryParams: { … } }`. Stored configs and the\n // catalog read as canonical placements; `apiKeyAuthTemplateFromMethod`\n // serializes them back for read-modify-write flows.\n ApiKeyAuthTemplate,\n]);\nexport type GraphqlAuthMethodInput = typeof GraphqlAuthMethodInput.Type;\n\n/** The expansion target: input arms with the dialect resolved to canonical\n * placements (slug still optional — backfill is a separate pass). */\nexport type GraphqlCanonicalAuthMethodInput =\n | Exclude<GraphqlAuthMethodInput, ApiKeyAuthTemplate>\n | (Omit<ApiKeyAuthMethod, \"slug\"> & { readonly slug?: string });\n\n/** The default slug for a slug-less input method. Carrier-derived for the\n * single-placement apikey cases (`header` / `query`) so the UI, agent, and\n * migration paths all converge on the same names. */\nconst defaultGraphqlAuthSlug = (method: GraphqlCanonicalAuthMethodInput): string => {\n if (method.kind !== \"apikey\") return method.kind;\n if (method.placements.length === 1) {\n return method.placements[0]!.carrier === \"header\" ? \"header\" : \"query\";\n }\n return \"apikey\";\n};\n\n/** Expand request-shaped dialect entries into canonical placements; canonical\n * entries pass through. Slug backfill is the caller's concern\n * (`normalizeGraphqlAuthMethods` for declare flows, `mergeAuthTemplates` for\n * the custom-method merge). */\nexport const expandGraphqlAuthMethodInputs = (\n methods: readonly GraphqlAuthMethodInput[],\n): readonly GraphqlCanonicalAuthMethodInput[] =>\n methods.map(\n (method): GraphqlCanonicalAuthMethodInput =>\n isApiKeyAuthTemplate(method)\n ? (apiKeyMethodFromAuthTemplate(method) as GraphqlCanonicalAuthMethodInput)\n : (method as GraphqlCanonicalAuthMethodInput),\n );\n\n/** Assign each method a stable slug: a caller-provided one wins, otherwise a\n * kind/carrier-derived default, suffixed `_2`, `_3`, … on collision. The\n * request-shaped dialect is expanded to canonical placements first. */\nexport const normalizeGraphqlAuthMethods = (\n methods: readonly GraphqlAuthMethodInput[],\n): readonly GraphqlAuthMethod[] =>\n normalizeAuthMethodSlugs(\n expandGraphqlAuthMethodInputs(methods),\n defaultGraphqlAuthSlug,\n ) as readonly GraphqlAuthMethod[];\n\n// ---------------------------------------------------------------------------\n// Integration config — the opaque-to-core blob the graphql plugin stores on the\n// integration row. Holds everything `resolveTools` (introspection) and\n// `invokeTool` (request building + auth rendering) need.\n// ---------------------------------------------------------------------------\n\nexport const GraphqlIntegrationConfig = Schema.Struct({\n /** The GraphQL endpoint URL. */\n endpoint: Schema.String,\n /** Display name for the integration. */\n name: Schema.String,\n /** Hex SHA-256 of the introspection JSON snapshot — the content address of\n * the blob (`introspection/<hash>` in the plugin blob store). Rows that\n * predate the blob store (inline `introspectionJson` text) are rewritten\n * by the introspection-to-blob migrations before this schema sees them. */\n introspectionHash: Schema.optional(Schema.String),\n /** Static headers applied to every request (and to add-time introspection). */\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n /** Static query parameters applied to every request. */\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n /** Declared auth methods — how a connection's values are rendered onto\n * requests. A connection's `template` picks one by slug. */\n authenticationTemplate: Schema.Array(GraphqlAuthMethod),\n});\nexport type GraphqlIntegrationConfig = typeof GraphqlIntegrationConfig.Type;\n\n// Decodes ONLY the canonical shape. Pre-canonical stored shapes are rewritten\n// by the one-off config migration (`migrate-config.ts`), not decoded here —\n// runtime code knows only the canonical model.\nexport const decodeGraphqlIntegrationConfig = Schema.decodeUnknownEffect(GraphqlIntegrationConfig);\nexport const decodeGraphqlIntegrationConfigOption =\n Schema.decodeUnknownOption(GraphqlIntegrationConfig);\n\n// ---------------------------------------------------------------------------\n// Invocation\n// ---------------------------------------------------------------------------\n\nexport const InvocationResult = Schema.Struct({\n status: Schema.Number,\n data: Schema.NullOr(Schema.Unknown),\n errors: Schema.NullOr(Schema.Unknown),\n});\nexport type InvocationResult = typeof InvocationResult.Type;\n"],"mappings":";AAAA,SAAS,MAAM,cAAc;AAItB,IAAM,4BAAN,cAAwC,OAAO,iBAA4C;AAAA,EAChG;AAAA,EACA;AAAA,IACE,SAAS,OAAO;AAAA,EAClB;AACF,EAAE;AAAC;AAEI,IAAM,yBAAN,cAAqC,OAAO,iBAAyC;AAAA,EAC1F;AAAA,EACA;AAAA,IACE,SAAS,OAAO;AAAA,EAClB;AACF,EAAE;AAAC;AAEI,IAAM,yBAAN,cAAqC,KAAK,YAAY,wBAAwB,EAIlF;AAAC;AAKG,IAAM,2BAAN,cAAuC,KAAK,YAAY,0BAA0B,EAYtF;AAAC;;;ACvCJ,SAAS,UAAAA,eAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMA,IAAM,uBAAuBA,QAAO,SAAS,CAAC,SAAS,UAAU,CAAC;AAOlE,IAAM,kBAAkBA,QAAO,OAAO;AAAA,EAC3C,MAAMA,QAAO;AAAA,EACb,UAAUA,QAA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