-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathAddGraphqlSource.tsx
More file actions
253 lines (235 loc) · 8.96 KB
/
AddGraphqlSource.tsx
File metadata and controls
253 lines (235 loc) · 8.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import { useCallback, useState } from "react";
import { useAtomSet } from "@effect/atom-react";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { useScope } from "@executor-js/react/api/scope-context";
import { sourceWriteKeys } from "@executor-js/react/api/reactivity-keys";
import {
HttpCredentialEditor,
useHttpCredentialEditorController,
} from "@executor-js/react/plugins/http-credential-state";
import {
sourceDisplayNameFromUrl,
slugifyNamespace,
useSourceIdentity,
} from "@executor-js/react/plugins/source-identity";
import {
oauthCallbackUrl,
oauthConnectionId,
useOAuthPopupFlow,
type OAuthCompletionPayload,
} from "@executor-js/react/plugins/oauth-sign-in";
import {
CredentialControlField,
CredentialUsageRow,
useCredentialTargetScope,
} from "@executor-js/react/plugins/credential-target-scope";
import { useSecretPickerSecrets } from "@executor-js/react/plugins/use-secret-picker-secrets";
import { Button } from "@executor-js/react/components/button";
import { FloatActions } from "@executor-js/react/components/float-actions";
import { Spinner } from "@executor-js/react/components/spinner";
import { addGraphqlSourceOptimistic } from "./atoms";
import { initialGraphqlCredentials } from "./defaults";
import { GraphqlSourceFields } from "./GraphqlSourceFields";
import type { GraphqlCredentialInput } from "../sdk/types";
const ErrorMessage = Schema.Struct({ message: Schema.String });
const decodeErrorMessage = Schema.decodeUnknownOption(ErrorMessage);
const errorMessageFromExit = (exit: Exit.Exit<unknown, unknown>, fallback: string): string =>
Option.match(Option.flatMap(Exit.findErrorOption(exit), decodeErrorMessage), {
onNone: () => fallback,
onSome: ({ message }) => message,
});
type AuthMode = "none" | "oauth2";
export default function AddGraphqlSource(props: {
onComplete: () => void;
onCancel: () => void;
initialUrl?: string;
}) {
const [endpoint, setEndpoint] = useState(props.initialUrl ?? "");
const identity = useSourceIdentity({
fallbackName: sourceDisplayNameFromUrl(endpoint, "GraphQL") ?? "",
});
const [adding, setAdding] = useState(false);
const [addError, setAddError] = useState<string | null>(null);
const [authMode, setAuthMode] = useState<AuthMode>("none");
const [tokens, setTokens] = useState<OAuthCompletionPayload | null>(null);
const scopeId = useScope();
const { credentialTargetScope: requestCredentialTargetScope } = useCredentialTargetScope();
const {
credentialTargetScope: oauthCredentialTargetScope,
setCredentialTargetScope: setOAuthCredentialTargetScope,
credentialScopeOptions,
} = useCredentialTargetScope();
const doAdd = useAtomSet(addGraphqlSourceOptimistic(scopeId), {
mode: "promiseExit",
});
const secretList = useSecretPickerSecrets();
const credentialEditor = useHttpCredentialEditorController({
initialCredentials: initialGraphqlCredentials(),
targetScope: requestCredentialTargetScope,
existingSecrets: secretList,
sourceName: identity.name,
credentialScopeOptions,
bindingScopeOptions: credentialScopeOptions,
});
const oauth = useOAuthPopupFlow({
popupName: "graphql-oauth",
startErrorMessage: "Failed to start OAuth",
});
const canAdd =
endpoint.trim().length > 0 &&
credentialEditor.state.valid &&
(authMode === "none" || tokens !== null) &&
!oauth.busy;
const sourceIdentity = useCallback(() => {
const trimmedEndpoint = endpoint.trim();
const namespace =
slugifyNamespace(identity.namespace) ||
slugifyNamespace(sourceDisplayNameFromUrl(trimmedEndpoint, "GraphQL") ?? "") ||
"graphql";
const displayName =
identity.name.trim() || sourceDisplayNameFromUrl(trimmedEndpoint, "GraphQL") || namespace;
return { trimmedEndpoint, namespace, displayName };
}, [endpoint, identity.name, identity.namespace]);
const handleOAuth = useCallback(async () => {
if (!endpoint.trim() || !credentialEditor.state.valid) return;
setAddError(null);
const { trimmedEndpoint, namespace, displayName } = sourceIdentity();
await oauth.start({
payload: {
endpoint: trimmedEndpoint,
...credentialEditor.serialized.requestFields,
redirectUrl: oauthCallbackUrl(),
connectionId: oauthConnectionId({ pluginId: "graphql", namespace }),
tokenScope: oauthCredentialTargetScope,
strategy: { kind: "dynamic-dcr" },
pluginId: "graphql",
identityLabel: `${displayName} OAuth`,
},
onSuccess: (result) => {
setTokens({
connectionId: result.connectionId,
expiresAt: result.expiresAt,
scope: result.scope,
});
},
onError: setAddError,
});
}, [endpoint, credentialEditor, oauth, sourceIdentity, oauthCredentialTargetScope]);
const handleAdd = async () => {
setAdding(true);
setAddError(null);
const requestCredentials = credentialEditor.serialized.scopedFields<GraphqlCredentialInput>();
const { trimmedEndpoint, namespace, displayName } = sourceIdentity();
const exit = await doAdd({
params: { scopeId },
payload: {
targetScope: scopeId,
endpoint: trimmedEndpoint,
name: displayName,
namespace,
...requestCredentials,
credentialTargetScope:
authMode === "oauth2" && tokens
? oauthCredentialTargetScope
: requestCredentialTargetScope,
...(authMode === "oauth2" && tokens
? {
auth: {
kind: "oauth2" as const,
connectionId: tokens.connectionId,
},
}
: {}),
},
reactivityKeys: sourceWriteKeys,
});
if (Exit.isFailure(exit)) {
setAddError(errorMessageFromExit(exit, "Failed to add source"));
setAdding(false);
return;
}
props.onComplete();
};
return (
<div className="flex flex-1 flex-col gap-6">
<h1 className="text-xl font-semibold text-foreground">Add GraphQL Source</h1>
<GraphqlSourceFields endpoint={endpoint} onEndpointChange={setEndpoint} identity={identity} />
<HttpCredentialEditor.Provider controller={credentialEditor}>
<HttpCredentialEditor.Headers />
<HttpCredentialEditor.QueryParams />
</HttpCredentialEditor.Provider>
{/* Temporarily hidden while we revisit GraphQL OAuth discovery and UX. */}
<section className="hidden space-y-2.5">
<HttpCredentialEditor.Auth.Root
label="Authentication"
value={authMode}
onValueChange={(value) => {
setAuthMode(value === "oauth2" ? "oauth2" : "none");
setTokens(null);
}}
>
<HttpCredentialEditor.Auth.None />
<HttpCredentialEditor.Auth.OAuth value="oauth2" label="OAuth" />
</HttpCredentialEditor.Auth.Root>
{authMode === "oauth2" && (
<CredentialUsageRow
value={oauthCredentialTargetScope}
options={credentialScopeOptions}
onChange={(targetScope) => {
setOAuthCredentialTargetScope(targetScope);
setTokens(null);
}}
label="Connection saved to"
help="Choose who can use the OAuth connection."
>
<CredentialControlField label="Connect via OAuth" help="Start the provider OAuth flow.">
<div className="flex min-h-9 items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2">
{tokens ? (
<span className="text-xs font-medium text-emerald-600 dark:text-emerald-400">
Authenticated
</span>
) : (
<span className="text-xs text-muted-foreground">Not connected</span>
)}
<Button
type="button"
variant="outline"
size="sm"
className="ml-auto h-7 px-2 text-xs"
onClick={() => void handleOAuth()}
disabled={!endpoint.trim() || !credentialEditor.state.valid || oauth.busy}
>
{oauth.busy ? "Signing in..." : tokens ? "Reconnect" : "Sign in"}
</Button>
</div>
</CredentialControlField>
</CredentialUsageRow>
)}
</section>
{/* Error */}
{addError && (
<div className="rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2">
<p className="text-[12px] text-destructive">{addError}</p>
</div>
)}
<FloatActions>
<Button
variant="ghost"
onClick={() => {
oauth.cancel();
props.onCancel();
}}
disabled={adding}
>
Cancel
</Button>
<Button onClick={handleAdd} disabled={!canAdd || adding}>
{adding && <Spinner className="size-3.5" />}
{adding ? "Adding..." : "Add source"}
</Button>
</FloatActions>
</div>
);
}