-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathConfigCreateStepper.tsx
656 lines (598 loc) · 23.3 KB
/
ConfigCreateStepper.tsx
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
'use client'
import { useConfig } from '@/src/app/config-context'
import { useToast } from '@/src/hooks/use-toast'
import { cleanApiDomain, cn } from '@/src/lib/utils'
import { ApiConfig, AuthType, CacheMode, SuperglueClient } from '@superglue/client'
import { Copy, Loader2, Terminal } from 'lucide-react'
import { useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'
import { InteractiveApiPlayground } from '../InteractiveApiPlayground'
import { Button } from '../ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../ui/dialog'
import { Input } from '../ui/input'
import { Label } from '../ui/label'
import { Textarea } from '../ui/textarea'
import { HelpTooltip, inputErrorStyles, parseCredentialsHelper } from './Helpers'
import { StepIndicator, type StepperStep } from './StepIndicator'
interface ConfigCreateStepperProps {
open: boolean
onOpenChange: (open: boolean) => void
configId?: string // not used, but if we later want to edit through this flow
mode?: 'create' | 'edit'
prefillData?: {
fullUrl: string
instruction: string
documentationUrl?: string
}
onComplete?: () => void
}
export function ConfigCreateStepper({ open, onOpenChange, configId: initialConfigId, mode = 'create', prefillData, onComplete }: ConfigCreateStepperProps) {
const [step, setStep] = useState<StepperStep>('basic')
const [isAutofilling, setIsAutofilling] = useState(false)
const { toast } = useToast()
const router = useRouter()
const superglueConfig = useConfig()
const [configId, setConfigId] = useState<string>(initialConfigId || '')
const [initialRawResponse, setInitialRawResponse] = useState<any>(null)
const [hasMappedResponse, setHasMappedResponse] = useState(false)
const [mappedResponseData, setMappedResponseData] = useState<any>(null)
const [responseMapping, setResponseMapping] = useState<any>(null)
const [isRunning, setIsRunning] = useState(false)
const [formData, setFormData] = useState({
fullUrl: prefillData?.fullUrl || '',
instruction: prefillData?.instruction || '',
documentationUrl: prefillData?.documentationUrl || '',
inputPayload: '{}',
auth: {
type: AuthType.HEADER,
value: '',
advancedConfig: '{}'
},
responseSchema: '{}'
})
const [validationErrors, setValidationErrors] = useState<Record<string, boolean>>({})
const handleChange = (field: string) => (
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement> | string
) => {
const value = typeof e === 'string' ? e : e.target.value
setFormData(prev => ({
...prev,
[field]: value
}))
// Reset hasMappedResponse and mappedResponseData when schema or instruction changes
if (field === 'responseSchema' || field === 'instruction') {
setHasMappedResponse(false)
setMappedResponseData(null)
setResponseMapping(null)
}
}
const splitUrl = (url: string) => {
if (!url) {
return {
urlHost: '',
urlPath: ''
}
}
try {
const urlObj = new URL(url.startsWith('http') ? url : `https://${url}`)
const cleanedHost = cleanApiDomain(`${urlObj.protocol}//${urlObj.host}`)
const path = urlObj.pathname === '/' ? '' : urlObj.pathname
return {
urlHost: cleanedHost,
urlPath: path
}
} catch (error) {
// If URL parsing fails, just use existing cleanApiDomain
console.warn('URL parsing failed:', error)
const cleanedUrl = cleanApiDomain(url)
return {
urlHost: cleanedUrl,
urlPath: ''
}
}
}
const handleAuthChange = (value: string) => {
setFormData(prev => ({
...prev,
auth: {
...prev.auth,
value
}
}))
}
const handleNext = async () => {
if (step === 'basic') {
const errors: Record<string, boolean> = {}
if (!formData.fullUrl) {
errors.fullUrl = true
}
if (!formData.instruction) {
errors.instruction = true
}
if (Object.keys(errors).length > 0) {
setValidationErrors(errors)
// Find first error field and scroll to it
const firstErrorField = Object.keys(errors)[0]
const errorElement = document.getElementById(firstErrorField)
if (errorElement) {
errorElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
errorElement.focus()
}
return
}
setValidationErrors({})
// Parse the URL when moving to the next step
const url = splitUrl(formData.fullUrl)
setIsAutofilling(true)
try {
const superglueClient = new SuperglueClient({
endpoint: superglueConfig.superglueEndpoint,
apiKey: superglueConfig.superglueApiKey
})
// Call autofill endpoint
const response = await superglueClient.call({
endpoint: {
urlHost: url.urlHost,
...(url.urlPath ? { urlPath: url.urlPath } : {}),
...(formData.documentationUrl ? { documentationUrl: formData.documentationUrl } : {}),
instruction: formData.instruction,
authentication: formData.auth.value ? AuthType.HEADER : AuthType.NONE
},
payload: JSON.parse(formData.inputPayload),
credentials: parseCredentialsHelper(formData.auth.value, JSON.parse(formData.auth.advancedConfig)),
options: {
cacheMode: CacheMode.DISABLED
}
})
if (response.error) {
throw new Error(response.error)
}
// Store the raw response for the try step
setInitialRawResponse(response.data)
// Generate schema based on the raw response
const generatedSchema = await superglueClient.generateSchema(formData.instruction, JSON.stringify(response.data))
if (generatedSchema) {
setFormData(prev => ({
...prev,
responseSchema: JSON.stringify(generatedSchema, null, 2)
}))
}
// Apply the returned config
const config = response.config as ApiConfig
if (config) {
const id = url.urlHost.replace(/^https?:\/\//, '').replace(/\//g, '') + '-' + Math.floor(1000 + Math.random() * 9000)
setConfigId(id)
// Save the configuration with the generated schema
const savedConfig = await superglueClient.upsertApi(id, {
id,
...config,
responseSchema: generatedSchema,
createdAt: new Date(),
updatedAt: new Date()
} as ApiConfig)
if (!savedConfig) {
throw new Error('Failed to save configuration')
}
}
} catch (error: any) {
console.error('Error during autofill:', error)
toast({
title: 'API Configuration Failed',
description: error?.message || 'An error occurred while configuring the API',
variant: 'destructive',
duration: 10000
})
return
} finally {
setIsAutofilling(false)
}
}
if (step === 'try_and_output') {
// Save the configuration with the updated schema
try {
const superglueClient = new SuperglueClient({
endpoint: superglueConfig.superglueEndpoint,
apiKey: superglueConfig.superglueApiKey
})
const url = splitUrl(formData.fullUrl)
const savedConfig = await superglueClient.upsertApi(configId, {
id: configId,
urlHost: url.urlHost,
instruction: formData.instruction,
documentationUrl: formData.documentationUrl || undefined,
// authentication: formData.auth.value ? AuthType.HEADER : AuthType.NONE,
// headers: {},
// TODO: enable headers
// headers: formData.auth.value ? { 'Authorization': formData.auth.value } : undefined,
responseSchema: JSON.parse(formData.responseSchema),
createdAt: new Date(),
updatedAt: new Date()
} as ApiConfig)
if (!savedConfig) {
throw new Error('Failed to save configuration')
}
// TODO: show some notification to the user that something has been saved
// toast({
// title: 'Configuration Saved',
// description: 'Your API configuration has been saved with the updated schema.',
// })
} catch (error: any) {
console.error('Error saving config:', error)
toast({
title: 'Error Saving Configuration',
description: error?.message || 'An error occurred while saving the configuration',
variant: 'destructive'
})
return
}
}
const steps: StepperStep[] = ['basic', 'try_and_output', 'success']
const currentIndex = steps.indexOf(step)
if (currentIndex < steps.length - 1) {
setStep(steps[currentIndex + 1])
}
}
const handleBack = () => {
const steps: StepperStep[] = ['basic', 'try_and_output', 'success']
const currentIndex = steps.indexOf(step)
if (currentIndex > 0) {
setStep(steps[currentIndex - 1])
}
}
const handleClose = () => {
if (mode === 'create') {
router.push('/configs')
} else {
router.push(`/configs/${configId}/edit`)
}
onOpenChange(false)
}
const getCurlCommand = () => {
let payload = {}
try {
payload = JSON.parse(formData.inputPayload)
} catch (e) {
console.warn('Invalid input payload JSON')
}
const credentials = parseCredentialsHelper(formData.auth.value, JSON.parse(formData.auth.advancedConfig))
const graphqlQuery = {
query: `mutation CallApi($payload: JSON!, $credentials: JSON!) {
call(input: { id: "${configId}" }, payload: $payload, credentials: $credentials) {
data
}
}`,
variables: {
payload,
credentials
}
}
const command = `curl -X POST "${superglueConfig.superglueEndpoint}/graphql" \\
-H "Content-Type: application/json" \\
-H "Authorization: Bearer ${superglueConfig.superglueApiKey}" \\
-d '${JSON.stringify(graphqlQuery)}'`
return command
}
const getSdkCode = () => {
const credentials = parseCredentialsHelper(formData.auth.value, JSON.parse(formData.auth.advancedConfig))
return `npm install @superglue/client
// in your app:
import { SuperglueClient } from "@superglue/client";
const superglue = new SuperglueClient({
apiKey: "${superglueConfig.superglueApiKey}"
});
// Transform any API response with a single call
const result = await superglue.call({
id: "${configId}",
payload: ${formData.inputPayload},
credentials: ${JSON.stringify(credentials)}
})`
}
// Update handleMappedResponse to store the response data
const handleMappedResponse = (response: any) => {
setMappedResponseData(response)
setHasMappedResponse(!!response && typeof response === 'object')
}
const handleRun = async () => {
// TODO: dedupe this InteractiveApiPlayground
setIsRunning(true)
try {
const superglueClient = new SuperglueClient({
endpoint: superglueConfig.superglueEndpoint,
apiKey: superglueConfig.superglueApiKey
})
// 1. First upsert the API config with the new schema and instruction
await superglueClient.upsertApi(configId, {
id: configId,
instruction: formData.instruction,
responseSchema: JSON.parse(formData.responseSchema)
})
// 2. Call the API using the config ID and get mapped response
const mappedResult = await superglueClient.call({
id: configId,
payload: JSON.parse(formData.inputPayload),
credentials: parseCredentialsHelper(formData.auth.value, JSON.parse(formData.auth.advancedConfig))
})
if (mappedResult.error) {
throw new Error(mappedResult.error)
}
// 3. Set the mapped response
const mappedData = mappedResult.data
setMappedResponseData(mappedData)
setHasMappedResponse(true)
setResponseMapping((mappedResult.config as ApiConfig).responseMapping)
} catch (error: any) {
console.error('Error running API:', error)
toast({
title: 'Error Running API',
description: error?.message || 'An error occurred while running the API',
variant: 'destructive'
})
} finally {
setIsRunning(false)
}
}
// Update form data when prefillData changes or when modal is opened
useEffect(() => {
if (prefillData && open) {
setFormData(prevData => ({
...prevData,
fullUrl: prefillData.fullUrl || prevData.fullUrl,
instruction: prefillData.instruction || prevData.instruction,
documentationUrl: prefillData.documentationUrl || prevData.documentationUrl
}));
}
}, [prefillData, open]);
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent
className="h-[100vh] w-[100vw] max-w-[100vw] p-3 sm:p-6 lg:p-12 gap-0 rounded-none border-none flex flex-col"
onPointerDownOutside={e => e.preventDefault()}
>
<div className="flex-none mb-4">
<DialogHeader>
<div className="flex flex-col lg:flex-row items-center justify-between gap-4 mb-4">
<DialogTitle>
{step === 'success' ? 'Configuration Complete!' : 'Create New API Configuration'}
</DialogTitle>
{!step.includes('success') && (
<Button
variant="outline"
className="bg-gradient-to-r from-blue-500/10 to-purple-500/10 border border-blue-200/50 hover:border-blue-300/50 text-blue-600 hover:text-blue-700 text-sm px-4 py-1 h-8 rounded-full animate-pulse shrink-0"
onClick={() => window.open('https://cal.com/teamindex/onboarding', '_blank')}
>
✨ Get help from our team
</Button>
)}
</div>
</DialogHeader>
<StepIndicator currentStep={step} />
</div>
<div className="flex-1 overflow-y-auto px-1 min-h-0">
{step === 'basic' && (
<div className="space-y-3">
<div>
<div className="flex items-center gap-2 mb-1">
<Label htmlFor="fullUrl">API Endpoint URL</Label>
<HelpTooltip text="The API URL (e.g., https://api.example.com/v1). Don't include the endpoint, e.g. /books/list, we figure it out." />
</div>
<Input
id="fullUrl"
value={formData.fullUrl}
onChange={(e) => {
handleChange('fullUrl')(e)
if (e.target.value) {
setValidationErrors(prev => ({ ...prev, fullUrl: false }))
}
}}
placeholder="https://api.example.com/v1"
required
autoFocus
className={cn(
validationErrors.fullUrl && inputErrorStyles,
validationErrors.fullUrl && "focus:!border-destructive"
)}
/>
{validationErrors.fullUrl && (
<p className="text-sm text-destructive mt-1">API endpoint URL is required</p>
)}
</div>
<div>
<div className="flex items-center gap-2 mb-1">
<Label htmlFor="documentationUrl">API Documentation (Optional)</Label>
<HelpTooltip text="Link to the API's documentation if available" />
</div>
<Input
id="documentationUrl"
value={formData.documentationUrl}
onChange={handleChange('documentationUrl')}
placeholder="https://docs.example.com"
/>
</div>
<div>
<div className="flex items-center gap-2 mb-1">
<Label htmlFor="auth">API Key or Token (Optional)</Label>
<HelpTooltip text="Enter API secret here (we don't store it!). Omit prefixes like Bearer. We figure out where to put the secret." />
</div>
<Input
id="auth"
value={formData.auth.value}
onChange={(e) => handleAuthChange(e.target.value)}
placeholder="Enter your API key or token"
/>
</div>
<div className="mt-6">
<div className="flex items-center gap-2 mb-1">
<Label htmlFor="instruction">What do you want to get from this API?</Label>
<HelpTooltip text="Describe what data you want to extract from this API in plain English" />
</div>
<Textarea
id="instruction"
value={formData.instruction}
onChange={(e) => {
handleChange('instruction')(e)
if (e.target.value) {
setValidationErrors(prev => ({ ...prev, instruction: false }))
}
}}
placeholder="E.g. 'Get all products with price and name'"
className={cn(
"h-48",
validationErrors.instruction && inputErrorStyles,
validationErrors.instruction && "focus:!border-destructive"
)}
required
/>
{validationErrors.instruction && (
<p className="text-sm text-destructive mt-1">Instruction is required</p>
)}
</div>
</div>
)}
{step === 'try_and_output' && configId && (
<div className="space-y-2 h-full">
<InteractiveApiPlayground
configId={configId}
instruction={formData.instruction}
onInstructionChange={handleChange('instruction')}
responseSchema={formData.responseSchema}
onResponseSchemaChange={handleChange('responseSchema')}
initialRawResponse={initialRawResponse}
onMappedResponse={handleMappedResponse}
onRun={handleRun}
isRunning={isRunning}
mappedResponseData={mappedResponseData}
responseMapping={responseMapping}
hideRunButton={true}
/>
</div>
)}
{step === 'success' && (
<div className="space-y-4 h-full">
<p className="text-m font-medium">Done!</p>
<p className="text-sm font-medium">You can now call the endpoint from your app. The call is proxied to the targeted endpoint without AI inbewteen. Predictable and millisecond latency.</p>
<div className="rounded-md bg-muted p-4">
<div className="flex items-start space-x-2">
<Terminal className="mt-0.5 h-5 w-5 text-muted-foreground" />
<div className="space-y-1 w-full">
<div className="flex items-center justify-between">
<p className="text-sm font-medium">Try the endpoint locally with curl: </p>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 flex-none"
onClick={() => {
navigator.clipboard.writeText(getCurlCommand());
}}
>
<Copy className="h-4 w-4" />
</Button>
</div>
<div className="relative">
<pre className="rounded-lg bg-secondary p-4 text-sm overflow-x-auto">
<code>{getCurlCommand()}</code>
</pre>
</div>
</div>
</div>
</div>
<div className="rounded-md bg-muted p-4">
<div className="flex items-start space-x-2">
<Terminal className="mt-0.5 h-5 w-5 text-muted-foreground" />
<div className="space-y-1 w-full">
<div className="flex items-center justify-between">
<p className="text-sm font-medium">Or use the TypeScript SDK in your application: </p>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 flex-none"
onClick={() => {
navigator.clipboard.writeText(getSdkCode());
}}
>
<Copy className="h-4 w-4" />
</Button>
</div>
<div className="relative">
<pre className="rounded-lg bg-secondary p-4 text-sm overflow-x-auto">
<code>{getSdkCode()}</code>
</pre>
</div>
</div>
</div>
</div>
</div>
)}
</div>
<div className="flex-none mt-2 sm:mt-4 flex flex-col lg:flex-row gap-2 justify-between">
{step === 'success' ? (
<>
<Button
variant="outline"
onClick={handleBack}
>
Back
</Button>
<div className="flex gap-2">
<Button
variant="outline"
onClick={() => {
router.push(`/configs/${configId}/edit`)
onOpenChange(false)
}}
>
Advanced Edit
</Button>
<Button
onClick={() => {
router.push('/configs')
// Call onComplete before closing if provided
if (onComplete) {
onComplete()
}
onOpenChange(false)
}}
>
Done
</Button>
</div>
</>
) : (
<>
<Button
variant="outline"
onClick={handleBack}
disabled={step === 'basic'}
>
Back
</Button>
<Button
onClick={step === 'try_and_output' && !mappedResponseData ? handleRun : handleNext}
disabled={isAutofilling || (step === 'try_and_output' && !mappedResponseData && isRunning)}
>
{isAutofilling ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{initialRawResponse ? 'Generating schema...' : 'Creating configuration...'}
</>
) : (
step === 'try_and_output' ?
(isRunning ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Running...
</>
) : (!mappedResponseData ? (
<>
✨ Run
</>
) : 'Complete')) :
'Next'
)}
</Button>
</>
)}
</div>
</DialogContent>
</Dialog>
)
}