-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathindex.tsx
257 lines (213 loc) · 5.86 KB
/
index.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
import { IThread } from 'src/types';
import { removeToken } from 'src/utils/token';
import { IFeedback } from 'src/types/feedback';
export * from './hooks/auth';
export * from './hooks/api';
export interface IThreadFilters {
search?: string;
feedback?: number;
}
export interface IPageInfo {
hasNextPage: boolean;
endCursor?: string;
}
export interface IPagination {
first: number;
cursor?: string | number;
}
export class ClientError extends Error {
detail?: string;
constructor(message: string, detail?: string) {
super(message);
this.detail = detail;
}
toString() {
if (this.detail) {
return `${this.message}: ${this.detail}`;
} else {
return this.message;
}
}
}
type Payload = FormData | any;
export class APIBase {
constructor(
public httpEndpoint: string,
public type: 'webapp' | 'copilot' | 'teams' | 'slack' | 'discord',
public on401?: () => void,
public onError?: (error: ClientError) => void
) {}
buildEndpoint(path: string) {
if (this.httpEndpoint.endsWith('/')) {
// remove trailing slash on httpEndpoint
return `${this.httpEndpoint.slice(0, -1)}${path}`;
} else {
return `${this.httpEndpoint}${path}`;
}
}
checkToken(token: string) {
const prefix = 'Bearer ';
if (token.startsWith(prefix)) {
return token;
} else {
return prefix + token;
}
}
async fetch(
method: string,
path: string,
token?: string,
data?: Payload,
signal?: AbortSignal
): Promise<Response> {
try {
const headers: { Authorization?: string; 'Content-Type'?: string } = {};
if (token) headers['Authorization'] = this.checkToken(token); // Assuming token is a bearer token
let body;
if (data instanceof FormData) {
body = data;
} else {
headers['Content-Type'] = 'application/json';
body = data ? JSON.stringify(data) : null;
}
const res = await fetch(this.buildEndpoint(path), {
method,
headers,
signal,
body
});
if (!res.ok) {
const body = await res.json();
if (res.status === 401 && this.on401) {
removeToken();
this.on401();
}
throw new ClientError(res.statusText, body.detail);
}
return res;
} catch (error: any) {
if (error instanceof ClientError && this.onError) {
this.onError(error);
}
console.error(error);
throw error;
}
}
async get(endpoint: string, token?: string) {
return await this.fetch('GET', endpoint, token);
}
async post(
endpoint: string,
data: Payload,
token?: string,
signal?: AbortSignal
) {
return await this.fetch('POST', endpoint, token, data, signal);
}
async put(endpoint: string, data: Payload, token?: string) {
return await this.fetch('PUT', endpoint, token, data);
}
async patch(endpoint: string, data: Payload, token?: string) {
return await this.fetch('PATCH', endpoint, token, data);
}
async delete(endpoint: string, data: Payload, token?: string) {
return await this.fetch('DELETE', endpoint, token, data);
}
}
export class ChainlitAPI extends APIBase {
async headerAuth() {
const res = await this.post(`/auth/header`, {});
return res.json();
}
async passwordAuth(data: FormData) {
const res = await this.post(`/login`, data);
return res.json();
}
async logout() {
const res = await this.post(`/logout`, {});
return res.json();
}
async setFeedback(
feedback: IFeedback,
accessToken?: string
): Promise<{ success: boolean; feedbackId: string }> {
const res = await this.put(`/feedback`, { feedback }, accessToken);
return res.json();
}
async deleteFeedback(
feedbackId: string,
accessToken?: string
): Promise<{ success: boolean }> {
const res = await this.delete(`/feedback`, { feedbackId }, accessToken);
return res.json();
}
async listThreads(
pagination: IPagination,
filter: IThreadFilters,
accessToken?: string
): Promise<{
pageInfo: IPageInfo;
data: IThread[];
}> {
const res = await this.post(
`/project/threads`,
{ pagination, filter },
accessToken
);
return res.json();
}
async deleteThread(threadId: string, accessToken?: string) {
const res = await this.delete(`/project/thread`, { threadId }, accessToken);
return res.json();
}
uploadFile(
file: File,
onProgress: (progress: number) => void,
sessionId: string,
token?: string
) {
const xhr = new XMLHttpRequest();
const promise = new Promise<{ id: string }>((resolve, reject) => {
const formData = new FormData();
formData.append('file', file);
xhr.open(
'POST',
this.buildEndpoint(`/project/file?session_id=${sessionId}`),
true
);
if (token) {
xhr.setRequestHeader('Authorization', this.checkToken(token));
}
// Track the progress of the upload
xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
const percentage = (event.loaded / event.total) * 100;
onProgress(percentage);
}
};
xhr.onload = function () {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
resolve(response);
} else {
reject('Upload failed');
}
};
xhr.onerror = function () {
reject('Upload error');
};
xhr.send(formData);
});
return { xhr, promise };
}
getElementUrl(id: string, sessionId: string) {
const queryParams = `?session_id=${sessionId}`;
return this.buildEndpoint(`/project/file/${id}${queryParams}`);
}
getLogoEndpoint(theme: string) {
return this.buildEndpoint(`/logo?theme=${theme}`);
}
getOAuthEndpoint(provider: string) {
return this.buildEndpoint(`/auth/oauth/${provider}`);
}
}