forked from UsefulSoftwareCo/executor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddOpenApiSource.tsx
More file actions
505 lines (461 loc) · 19.5 KB
/
Copy pathAddOpenApiSource.tsx
File metadata and controls
505 lines (461 loc) · 19.5 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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useAtomSet } from "@effect/atom-react";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
import { IntegrationSlug } from "@executor-js/sdk/shared";
import { integrationWriteKeys } from "@executor-js/react/api/reactivity-keys";
import {
slugifyNamespace,
useIntegrationIdentity,
} from "@executor-js/react/plugins/integration-identity";
import { Button } from "@executor-js/react/components/button";
import {
AuthMethodListEditor,
useAuthMethodList,
type AuthMethodRow,
type AuthMethodSeed,
} from "@executor-js/react/components/auth-method-list-editor";
import { CardStack, CardStackContent } from "@executor-js/react/components/card-stack";
import { FieldLabel } from "@executor-js/react/components/field";
import { FloatActions } from "@executor-js/react/components/float-actions";
import { Textarea } from "@executor-js/react/components/textarea";
import { IOSSpinner, Spinner } from "@executor-js/react/components/spinner";
import {
addIntegrationErrorMessage,
errorMessageFromExit,
FormErrorAlert,
SlugCollisionAlert,
useSlugAlreadyExists,
} from "@executor-js/react/lib/integration-add";
import {
authenticationFromEditorValue,
editorValueFromAuthentication,
openApiWireAuthInput,
} from "./auth-method-config";
import { addOpenApiSpec, previewOpenApiSpec } from "./atoms";
import { OpenApiSourceDetailsFields } from "./OpenApiSourceDetailsFields";
import { GoogleProductPicker } from "./GoogleProductPicker";
import { openApiPresets } from "../sdk/presets";
import {
GOOGLE_BUNDLE_PRESET_ID,
googleOpenApiPresets,
type GoogleOpenApiPreset,
} from "../sdk/google-presets";
import type { SpecPreview } from "../sdk/preview";
import { type Authentication } from "../sdk/types";
import { resolveServerUrl } from "../sdk/openapi-utils";
import { detectedAuthenticationTemplates } from "../sdk/derive-auth";
const GOOGLE_BUNDLE_FAVICON = "https://fonts.gstatic.com/s/i/productlogos/googleg/v6/192px.svg";
// The bundle picker opens with the featured Google APIs pre-checked.
const googleBundleDefaultPresetIds: ReadonlySet<string> = new Set(
googleOpenApiPresets
.filter((preset: GoogleOpenApiPreset) => preset.featured)
.map((preset: GoogleOpenApiPreset) => preset.id),
);
const googleBundleUrls = (
selectedPresetIds: ReadonlySet<string>,
customUrls: readonly string[],
): readonly string[] => {
const fromPresets = googleOpenApiPresets.flatMap((preset: GoogleOpenApiPreset) =>
preset.url && selectedPresetIds.has(preset.id) ? [preset.url] : [],
);
// Preset URLs first (stable order), then any custom Discovery URLs, de-duped.
return [...new Set([...fromPresets, ...customUrls])];
};
const isGoogleDiscoveryUrl = (url: string): boolean => {
const trimmed = url.trim();
if (!URL.canParse(trimmed)) return false;
const parsed = new URL(trimmed);
const host = parsed.hostname.toLowerCase();
if (!host.endsWith("googleapis.com")) return false;
return parsed.pathname.includes("/discovery/") || parsed.pathname.includes("$discovery");
};
const normalizePresetUrl = (url: string): string => {
const trimmed = url.trim();
if (!URL.canParse(trimmed)) return trimmed.replace(/\/$/, "");
const parsed = new URL(trimmed);
parsed.hash = "";
parsed.searchParams.sort();
return parsed.toString().replace(/\/$/, "");
};
const specInputForAdd = (input: string) => {
const value = input.trim();
const parsed = Effect.runSyncExit(
Effect.try({
try: () => new URL(value),
catch: () => null,
}),
);
return Exit.isSuccess(parsed)
? isGoogleDiscoveryUrl(value)
? { kind: "googleDiscovery" as const, url: value }
: { kind: "url" as const, url: value }
: { kind: "blob" as const, value };
};
// ---------------------------------------------------------------------------
// Component — single progressive form. Post-redesign: preview → addSpec
// (register the integration catalog entry with ALL detected auth methods) →
// route to the integration's detail hub, where the user adds accounts. The add
// flow no longer creates a connection.
// ---------------------------------------------------------------------------
export default function AddOpenApiSource(props: {
onComplete: (slug?: string) => void;
onCancel: () => void;
initialUrl?: string;
initialPreset?: string;
initialNamespace?: string;
}) {
const isGoogleBundlePreset = props.initialPreset === GOOGLE_BUNDLE_PRESET_ID;
// Spec input. For the Google BUNDLE preset the input is a product picker (a set
// of selected Discovery URLs), not a single spec URL/blob — the merge happens
// server-side via `{ kind: "googleDiscoveryBundle", urls }`, so the textarea
// preview path is bypassed entirely.
const [specUrl, setSpecUrl] = useState(props.initialUrl ?? "");
const [selectedPresetIds, setSelectedPresetIds] = useState<ReadonlySet<string>>(
googleBundleDefaultPresetIds,
);
const [customDiscoveryUrls, setCustomDiscoveryUrls] = useState<readonly string[]>([]);
const [analyzing, setAnalyzing] = useState(false);
const [analyzeError, setAnalyzeError] = useState<string | null>(null);
// After analysis
const [preview, setPreview] = useState<SpecPreview | null>(null);
const [baseUrl, setBaseUrl] = useState("");
const identityFallbackName = isGoogleBundlePreset
? "Google"
: preview
? Option.getOrElse(preview.title, () => "")
: "";
const identity = useIntegrationIdentity({
fallbackName: identityFallbackName,
fallbackNamespace: props.initialNamespace ?? (isGoogleBundlePreset ? "google" : undefined),
});
const bundleDiscoveryUrls = useMemo(
() => googleBundleUrls(selectedPresetIds, customDiscoveryUrls),
[selectedPresetIds, customDiscoveryUrls],
);
const toggleBundlePreset = useCallback((presetId: string, checked: boolean) => {
setSelectedPresetIds((current: ReadonlySet<string>) => {
const next = new Set(current);
if (checked) next.add(presetId);
else next.delete(presetId);
return next;
});
}, []);
const addCustomDiscoveryUrl = useCallback((url: string) => {
setCustomDiscoveryUrls((current: readonly string[]) =>
current.includes(url) ? current : [...current, url],
);
}, []);
const removeCustomDiscoveryUrl = useCallback((url: string) => {
setCustomDiscoveryUrls((current: readonly string[]) =>
current.filter((entry: string) => entry !== url),
);
}, []);
// Submit
const [adding, setAdding] = useState(false);
const [addError, setAddError] = useState<string | null>(null);
const doPreview = useAtomSet(previewOpenApiSpec, { mode: "promiseExit" });
const doAdd = useAtomSet(addOpenApiSpec, { mode: "promiseExit" });
// Keep the latest handleAnalyze in a ref so the debounced effect doesn't need
// it as a dependency (it closes over fresh state).
const handleAnalyzeRef = useRef<() => void>(() => {});
useEffect(() => {
// The bundle preset never analyzes a single spec — its input is the picker.
if (isGoogleBundlePreset) return;
const trimmed = specUrl.trim();
if (!trimmed) return;
if (preview) return;
const handle = setTimeout(() => {
handleAnalyzeRef.current();
}, 400);
return () => clearTimeout(handle);
}, [specUrl, preview, isGoogleBundlePreset]);
// ---- Derived state ----
const previewHasNoServers = preview !== null && preview.servers.length === 0;
// Offer the spec's servers (resolved with defaults) as base-URL choices when
// there's more than one; a single/no server uses a plain input.
const baseUrlOptions =
preview && preview.servers.length > 1
? preview.servers.map((server) => {
const url = resolveServerUrl(server.url, Option.getOrUndefined(server.variables), {});
return { value: url, label: url };
})
: undefined;
const firstServer = preview?.servers[0];
const firstServerUrl = firstServer
? resolveServerUrl(firstServer.url, Option.getOrUndefined(firstServer.variables), {})
: "";
const previewPresetIcon =
openApiPresets.find(
(preset) => preset.url && normalizePresetUrl(preset.url) === normalizePresetUrl(specUrl),
)?.icon ?? null;
const resolvedBaseUrl = baseUrl.trim();
const resolvedSourceId =
slugifyNamespace(identity.namespace) ||
(preview ? Option.getOrElse(preview.title, () => "openapi") : "openapi");
const resolvedDisplayName =
identity.name.trim() ||
(preview ? Option.getOrElse(preview.title, () => resolvedSourceId) : resolvedSourceId);
// Register EVERY spec-detected auth method, not just a single selected one.
// Keyed off `preview` (stable per analysis) so the memo doesn't re-run on the
// freshly-allocated `?? []` fallback arrays.
const authenticationTemplate: readonly Authentication[] = useMemo(
() =>
detectedAuthenticationTemplates(
preview?.headerPresets ?? [],
preview?.oauth2Presets ?? [],
resolvedBaseUrl,
),
[preview, resolvedBaseUrl],
);
// Editable auth methods, seeded from the spec-detected templates. The add flow
// registers EVERY method (P6) — so this is a LIST, preserving multi-method
// specs (e.g. apiKey + OAuth). Each seed carries the detected template's
// original slug, so an unedited detected method submits with its EXACT
// original slug (preserving behavior); added methods (no seed) get a
// deterministic fresh slug. Re-seeded whenever a fresh detection arrives
// (keyed on the detected templates, stable per analysis + base URL).
const authMethodSeeds: readonly AuthMethodSeed[] = useMemo(() => {
const labels = [
...(preview?.headerPresets ?? []).map((preset) => preset.label),
...(preview?.oauth2Presets ?? []).map((preset) => preset.label),
];
return authenticationTemplate.map(
(template: Authentication, index: number): AuthMethodSeed => ({
value: editorValueFromAuthentication(template),
slug: String(template.slug),
...(labels[index] !== undefined ? { label: labels[index] } : {}),
}),
);
}, [preview, authenticationTemplate]);
const authMethodList = useAuthMethodList(authMethodSeeds);
// The methods to register, mapped back to stored `Authentication[]`. Drops
// `none` rows (nothing to register). An unedited detected method keeps its
// original `seedSlug`; an added method gets a deterministic fresh slug.
const editedAuthenticationTemplate: readonly Authentication[] = useMemo(() => {
const templates: Authentication[] = [];
authMethodList.rows.forEach((row: AuthMethodRow, index: number) => {
const slug =
row.seedSlug ?? (row.value.kind === "oauth" ? `oauth-${index}` : `apikey-${index}`);
const template = authenticationFromEditorValue(row.value, slug);
if (template !== null) templates.push(template);
});
return templates;
}, [authMethodList.rows]);
// Pre-empt the API's `IntegrationAlreadyExistsError`: adding an integration
// whose slug already exists clobbers the existing one's connections/policies,
// so the API blocks it. Surface that here from the tenant-scoped catalog list.
const slugAlreadyExists = useSlugAlreadyExists(resolvedSourceId);
// The bundle path is ready once at least one Google API is selected (no
// network preview gates it); the single/custom-spec path still requires a
// successful preview. Both require a base URL and a free slug.
const hasPreviewOrBundle = isGoogleBundlePreset
? bundleDiscoveryUrls.length > 0
: preview !== null;
// The base URL is optional when the spec declares servers (resolved per call);
// required only when it doesn't.
const canAdd =
hasPreviewOrBundle &&
!slugAlreadyExists &&
(!previewHasNoServers || resolvedBaseUrl.length > 0);
// ---- Handlers ----
const handleAnalyze = async () => {
setAnalyzing(true);
setAnalyzeError(null);
setAddError(null);
const exit = await doPreview({ payload: { spec: specUrl } });
if (Exit.isFailure(exit)) {
setAnalyzeError(errorMessageFromExit(exit, "Failed to parse spec"));
setAnalyzing(false);
return;
}
const result = exit.value;
setPreview(result);
setBaseUrl("");
setAnalyzing(false);
};
handleAnalyzeRef.current = handleAnalyze;
// Persist the integration and return its slug. Registers the catalog entry
// with every detected auth method. Adding a slug that already exists is
// rejected by the API (`IntegrationAlreadyExistsError`) — surfaced inline.
const ensureIntegration = useCallback(async (): Promise<IntegrationSlug | null> => {
// The Google BUNDLE preset emits the multi-service bundle input; the server
// merges the selected Discovery documents into one `google` spec and stores
// the unioned `googleOAuth2` auth template (so no client template is sent).
// Every other preset/custom input keeps the single-spec url/blob/discovery
// branch unchanged.
const specForAdd = isGoogleBundlePreset
? ({ kind: "googleDiscoveryBundle" as const, urls: [...bundleDiscoveryUrls] } satisfies {
readonly kind: "googleDiscoveryBundle";
readonly urls: readonly string[];
})
: specInputForAdd(specUrl);
const exit = await doAdd({
payload: {
spec: specForAdd,
slug: resolvedSourceId,
description: resolvedDisplayName,
baseUrl: resolvedBaseUrl,
// Always send the edited method list (even empty) when the user has
// inspected a preview: an explicit [] means "no auth methods", while
// OMITTING the field tells the server to derive defaults from the
// spec — which would silently resurrect methods the user deleted.
// The Google bundle path stays omitted; its auth is converter-derived
// server-side.
...(!isGoogleBundlePreset
? {
// Serialize to the wire input dialect (apikey → request-shaped).
authenticationTemplate: editedAuthenticationTemplate.map(openApiWireAuthInput),
}
: {}),
},
reactivityKeys: integrationWriteKeys,
});
if (Exit.isFailure(exit)) {
setAddError(addIntegrationErrorMessage(exit, resolvedSourceId, "Failed to add integration"));
return null;
}
return exit.value.slug;
}, [
isGoogleBundlePreset,
bundleDiscoveryUrls,
specUrl,
doAdd,
resolvedSourceId,
resolvedDisplayName,
resolvedBaseUrl,
editedAuthenticationTemplate,
]);
const handleAdd = async () => {
setAdding(true);
setAddError(null);
const integration = await ensureIntegration();
if (!integration) {
setAdding(false);
return;
}
props.onComplete(String(integration));
};
// ---- Render ----
return (
<div className="flex flex-1 flex-col gap-6">
<div>
<h1 className="text-xl font-semibold text-foreground">
{isGoogleBundlePreset ? "Add Google" : "Add OpenAPI Integration"}
</h1>
{isGoogleBundlePreset ? (
<p className="mt-1 text-[13px] text-muted-foreground">
Bundle Google APIs into one integration from their Discovery documents and register
their methods as tools under a single shared OAuth consent.
</p>
) : null}
</div>
{isGoogleBundlePreset ? (
<GoogleProductPicker
selectedPresetIds={selectedPresetIds}
onToggle={toggleBundlePreset}
customUrls={customDiscoveryUrls}
onAddCustomUrl={addCustomDiscoveryUrl}
onRemoveCustomUrl={removeCustomDiscoveryUrl}
/>
) : !preview ? (
<CardStack>
<CardStackContent className="border-t-0">
<div className="space-y-2 p-3">
<FieldLabel>OpenAPI Spec</FieldLabel>
<div className="relative">
<Textarea
value={specUrl}
onChange={(e) => setSpecUrl((e.target as HTMLTextAreaElement).value)}
placeholder="https://api.example.com/openapi.json"
rows={3}
maxRows={10}
className="font-mono text-sm"
/>
{analyzing && (
<div className="pointer-events-none absolute right-2 top-2">
<IOSSpinner className="size-4" />
</div>
)}
</div>
<p className="text-[11px] text-muted-foreground">
Paste a URL or raw JSON/YAML content.
</p>
</div>
</CardStackContent>
</CardStack>
) : null}
{isGoogleBundlePreset ? (
<OpenApiSourceDetailsFields
title="Google"
description={`${bundleDiscoveryUrls.length} Google API${
bundleDiscoveryUrls.length !== 1 ? "s" : ""
} · one shared OAuth consent`}
identity={identity}
baseUrl={resolvedBaseUrl}
onBaseUrlChange={setBaseUrl}
baseUrlLabel="Base URL override (optional)"
faviconIcon={GOOGLE_BUNDLE_FAVICON}
faviconUrl={resolvedBaseUrl}
/>
) : preview ? (
<OpenApiSourceDetailsFields
title={Option.getOrElse(preview.title, () => "API")}
description={`${Option.getOrElse(preview.version, () => "")}${
Option.isSome(preview.version) ? " · " : ""
}${preview.operationCount} operation${preview.operationCount !== 1 ? "s" : ""}${
preview.tags.length > 0
? ` · ${preview.tags.length} tag${preview.tags.length !== 1 ? "s" : ""}`
: ""
}`}
identity={identity}
baseUrl={resolvedBaseUrl}
onBaseUrlChange={setBaseUrl}
baseUrlOptions={baseUrlOptions}
baseUrlLabel={previewHasNoServers ? "Base URL" : "Base URL override (optional)"}
baseUrlPlaceholder={firstServerUrl || "https://api.example.com"}
baseUrlHint={
previewHasNoServers
? undefined
: "Overrides the spec's servers; leave empty to choose the server (and variables) per tool call."
}
baseUrlMissingMessage={
previewHasNoServers ? "This spec declares no servers — enter a base URL." : undefined
}
specUrl={specUrl}
onSpecUrlChange={(value) => {
setSpecUrl(value);
setPreview(null);
setBaseUrl("");
}}
faviconIcon={previewPresetIcon}
faviconUrl={resolvedBaseUrl || firstServerUrl}
/>
) : null}
{analyzeError && <FormErrorAlert message={analyzeError} />}
{preview && !isGoogleBundlePreset && (
<AuthMethodListEditor
list={authMethodList}
emptyHint="No authentication detected. Add a method, or add the integration without auth and connect an account from the integration page later."
footerHint="Every method here is registered with the integration. Connect an account from the integration page after adding."
/>
)}
{hasPreviewOrBundle && slugAlreadyExists && !adding && (
<SlugCollisionAlert slug={resolvedSourceId} />
)}
{addError && <FormErrorAlert message={addError} />}
<FloatActions>
<Button variant="ghost" onClick={() => props.onCancel()} disabled={adding}>
Cancel
</Button>
{(hasPreviewOrBundle || isGoogleBundlePreset) && (
<Button onClick={() => void handleAdd()} disabled={!canAdd || adding}>
{adding && <Spinner className="size-3.5" />}
{adding ? "Adding…" : isGoogleBundlePreset ? "Connect Google" : "Add integration"}
</Button>
)}
</FloatActions>
</div>
);
}