-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathapiclient.ts
More file actions
307 lines (270 loc) · 9.76 KB
/
Copy pathapiclient.ts
File metadata and controls
307 lines (270 loc) · 9.76 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
import axios, { AxiosError, AxiosInstance, AxiosRequestConfig } from "axios";
import { JsonValue } from "@bufbuild/protobuf";
import { fromJson } from "./protobuf-utils";
import { RefreshTokenResponseSchema } from "../pkg/gen/apiclient/auth/v1/auth_pb";
import { GetUserResponseSchema } from "../pkg/gen/apiclient/user/v1/user_pb";
import { EventEmitter } from "events";
import { ErrorCode, ErrorSchema } from "../pkg/gen/apiclient/shared/v1/shared_pb";
import { errorToast } from "./toasts";
import { storage } from "./storage";
import { useAuthStore } from "../stores/auth-store";
// Exhaustive type check helper - will cause compile error if a case is not handled
const assertNever = (x: never): never => {
throw new Error("Unexpected api version: " + x);
};
export type RequestOptions = {
ignoreErrorToast?: boolean;
};
export type ApiVersion = "v1" | "v2";
// Storage key mapping for each API version - add new versions here
const API_VERSION_STORAGE_KEYS: Record<ApiVersion, string> = {
v1: "pd.devtool.endpoint",
v2: "pd.devtool.endpoint.v2",
} as const;
class ApiClient {
private axiosInstance: AxiosInstance;
private refreshToken: string | null;
private onTokenRefreshedEventEmitter: EventEmitter;
private refreshPromise: Promise<void> | null = null;
constructor(baseURL: string, apiVersion: ApiVersion) {
this.axiosInstance = axios.create({
baseURL: `${baseURL}/_pd/api/${apiVersion}`,
headers: {
"Content-Type": "application/json",
},
});
this.refreshToken = null;
this.onTokenRefreshedEventEmitter = new EventEmitter();
}
updateBaseURL(baseURL: string, apiVersion: ApiVersion): void {
this.axiosInstance.defaults.baseURL = `${sanitizeEndpoint(baseURL)}/_pd/api/${apiVersion}`;
switch (apiVersion) {
case "v1":
storage.setItem(API_VERSION_STORAGE_KEYS.v1, this.axiosInstance.defaults.baseURL);
break;
case "v2":
storage.setItem(API_VERSION_STORAGE_KEYS.v2, this.axiosInstance.defaults.baseURL);
break;
default:
assertNever(apiVersion); // Compile error if a new version is added but not handled
}
}
addListener(event: "tokenRefreshed", listener: (args: { token: string; refreshToken: string }) => void): void {
this.onTokenRefreshedEventEmitter.addListener(event, listener);
}
removeListener(event: "tokenRefreshed", listener: (args: { token: string; refreshToken: string }) => void): void {
this.onTokenRefreshedEventEmitter.removeListener(event, listener);
}
setTokens(token: string, refreshToken: string): void {
useAuthStore.getState().setToken(token);
useAuthStore.getState().setRefreshToken(refreshToken);
this.refreshToken = refreshToken;
this.axiosInstance.defaults.headers.common["Authorization"] = `Bearer ${token}`;
}
clearTokens(): void {
this.refreshToken = null;
delete this.axiosInstance.defaults.headers.common["Authorization"];
}
hasToken(): boolean {
const token = this.axiosInstance.defaults.headers.common["Authorization"]?.toString() || "";
return token?.replace("Bearer ", "").trim() !== "";
}
async isAuthed(): Promise<boolean> {
try {
const response = await this.get("/users/@self");
const user = fromJson(GetUserResponseSchema, response);
return user.user?.id !== "";
} catch {
return false;
}
}
async refresh() {
if (this.refreshPromise) {
return this.refreshPromise;
}
this.refreshPromise = (async () => {
try {
const response = await this.axiosInstance.post<JsonValue>("/auth/refresh", {
refreshToken: this.refreshToken,
});
const resp = fromJson(RefreshTokenResponseSchema, response.data);
this.setTokens(resp.token, resp.refreshToken);
this.onTokenRefreshedEventEmitter.emit("tokenRefreshed", {
token: resp.token,
refreshToken: resp.refreshToken,
});
} finally {
this.refreshPromise = null;
}
})();
return this.refreshPromise;
}
private async requestWithRefresh(config: AxiosRequestConfig): Promise<JsonValue> {
try {
const response = await this.axiosInstance(config);
return response.data;
} catch (error) {
if (error instanceof AxiosError && error.response?.status === 401 && this.hasToken()) {
await this.refresh();
const response = await this.axiosInstance(config);
return response.data;
}
throw error;
}
}
private async requestWithErrorToast(config: AxiosRequestConfig, options?: RequestOptions): Promise<JsonValue> {
try {
return await this.requestWithRefresh(config);
} catch (error) {
if (error instanceof AxiosError) {
const errorData = error.response?.data;
const errorPayload = fromJson(ErrorSchema, errorData);
if (!options?.ignoreErrorToast) {
const message = this.cleanErrorMessage(errorPayload.message);
const title = this.getErrorTitle(errorPayload.code);
errorToast(message, title);
}
throw errorPayload;
}
throw error;
}
}
private cleanErrorMessage(msg: string): string {
// Remove technical gRPC prefixes, mirroring backend behavior:
// strip everything up to and including "desc = " when the message
// starts with "rpc error:" and contains "desc = ".
if (msg.startsWith("rpc error:")) {
const marker = "desc = ";
const idx = msg.indexOf(marker);
if (idx !== -1) {
return msg.slice(idx + marker.length);
}
}
return msg;
}
// Error titles aligned with backend errorCodeMessages (error.go) for consistency
private getErrorTitle(code: ErrorCode): string {
const titles: Record<ErrorCode, string> = {
[ErrorCode.UNSPECIFIED]: "An unspecified error occurred",
[ErrorCode.UNKNOWN]: "An unknown error occurred",
[ErrorCode.INVALID_TOKEN]: "Invalid or missing authentication token",
[ErrorCode.INVALID_ACTOR]: "Invalid actor or session",
[ErrorCode.INVALID_USER]: "User not found or invalid",
[ErrorCode.PERMISSION_DENIED]: "Permission denied",
[ErrorCode.RECORD_NOT_FOUND]: "Record not found",
[ErrorCode.BAD_REQUEST]: "Bad request",
[ErrorCode.INTERNAL]: "Internal server error",
[ErrorCode.INVALID_CREDENTIAL]: "Invalid credentials",
[ErrorCode.INVALID_LLM_RESPONSE]: "Invalid LLM response",
[ErrorCode.PROJECT_OUT_OF_DATE]: "Project is out of date",
};
return titles[code] || "Request Failed";
}
async get(url: string, params?: object, options?: RequestOptions): Promise<JsonValue> {
return this.requestWithErrorToast(
{
method: "GET",
url,
params,
},
options,
);
}
async post(url: string, data?: object, options?: RequestOptions): Promise<JsonValue> {
return this.requestWithErrorToast(
{
method: "POST",
url,
data,
},
options,
);
}
async put(url: string, data?: object, options?: RequestOptions): Promise<JsonValue> {
return this.requestWithErrorToast(
{
method: "PUT",
url,
data,
},
options,
);
}
async patch(url: string, data?: object, options?: RequestOptions): Promise<JsonValue> {
return this.requestWithErrorToast(
{
method: "PATCH",
url,
data,
},
options,
);
}
async delete(url: string, options?: RequestOptions): Promise<JsonValue> {
return this.requestWithErrorToast(
{
method: "DELETE",
url,
},
options,
);
}
async postStream(
url: string,
data: any, // eslint-disable-line @typescript-eslint/no-explicit-any
): Promise<ReadableStream<Uint8Array>> {
const response = await fetch(this.axiosInstance.defaults.baseURL + url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${this.axiosInstance.defaults.headers.common["Authorization"]}`,
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Ensure the response body is a readable stream
if (!response.body) {
throw new Error("Readable stream not supported in this environment.");
}
return response.body; // Return the readable stream
}
}
const DEFAULT_ENDPOINT = `${process.env.PD_API_ENDPOINT || "http://localhost:3000"}`;
const LOCAL_STORAGE_KEY_V1 = "pd.devtool.endpoint";
const LOCAL_STORAGE_KEY_V2 = "pd.devtool.endpoint.v2";
const sanitizeEndpoint = (url: string) => url.trim().replace(/\/+$/, "");
// Create apiclient instance with endpoint from storage or default
export const getEndpointFromStorage = () => {
let endpoint = "";
try {
endpoint = storage.getItem(LOCAL_STORAGE_KEY_V1) || DEFAULT_ENDPOINT;
} catch {
// Fallback if storage is not available
endpoint = DEFAULT_ENDPOINT;
}
return sanitizeEndpoint(endpoint.replace("/_pd/api/v1", "").replace("/_pd/api/v2", "")); // compatible with old endpoint
};
/**
* @deprecated Use getEndpointFromStorage instead
*/
export const getEndpointFromLocalStorage = getEndpointFromStorage;
export const resetApiClientEndpoint = () => {
storage.removeItem(LOCAL_STORAGE_KEY_V1);
storage.removeItem(LOCAL_STORAGE_KEY_V2);
apiclient.updateBaseURL(getEndpointFromStorage(), "v1");
apiclientV2.updateBaseURL(getEndpointFromStorage(), "v2");
};
/**
* Reinitialize API client endpoints from storage.
* Call this after the storage adapter has been set.
*/
export const initApiClientFromStorage = () => {
const endpoint = getEndpointFromStorage();
apiclient.updateBaseURL(endpoint, "v1");
apiclientV2.updateBaseURL(endpoint, "v2");
};
const apiclient = new ApiClient(getEndpointFromStorage(), "v1");
export const apiclientV2 = new ApiClient(getEndpointFromStorage(), "v2");
export default apiclient;