Elffuss BraidHub

kikocis/continue public

54ea0739010d · 2.6 KiBRawPermalink
1import isLocalhost from "is-localhost-ip";
2import {
3 ContextItem,
4 ContextProviderDescription,
5 ContextProviderExtras,
6 IDE,
7} from "../../index.js";
8import { BaseContextProvider } from "../index.js";
9
10class HttpContextProvider extends BaseContextProvider {
11 static description: ContextProviderDescription = {
12 title: "http",
13 displayTitle: "HTTP",
14 description: "Retrieve a context item from a custom server",
15 type: "normal",
16 renderInlineAs: "",
17 };
18
19 private async getWorkspacePath(ide: IDE, url: URL) {
20 try {
21 const currentFile = await ide.getCurrentFile();
22 // `isLocalhost` actually also returns true for other local addresses, not just localhost
23 return await isLocalhost(url.hostname) ?
24 (await ide.getWorkspaceDirs()).find(workspaceDirectory => {
25 return currentFile?.path.startsWith(workspaceDirectory)
26 }) : undefined
27 } catch (e) {
28 return undefined;
29 }
30 }
31
32 override get description(): ContextProviderDescription {
33 return {
34 title: this.options.title || HttpContextProvider.description.title,
35 displayTitle:
36 this.options.displayTitle ||
37 this.options.name ||
38 HttpContextProvider.description.displayTitle,
39 description:
40 this.options.description || HttpContextProvider.description.description,
41 type: HttpContextProvider.description.type,
42 renderInlineAs:
43 this.options.renderInlineAs ||
44 HttpContextProvider.description.renderInlineAs,
45 };
46 }
47
48 async getContextItems(
49 query: string,
50 extras: ContextProviderExtras,
51 ): Promise<ContextItem[]> {
52 const parsedUrl = new URL(this.options.url)
53 const response = await extras.fetch(parsedUrl, {
54 method: "POST",
55 headers: {
56 "Content-Type": "application/json",
57 ...(this.options.headers || {}),
58 },
59 body: JSON.stringify({
60 query: query || "",
61 fullInput: extras.fullInput,
62 options: this.options.options,
63 workspacePath: await this.getWorkspacePath(extras.ide, parsedUrl),
64 }),
65 });
66
67 const json = await response.json();
68
69 try {
70 const createContextItem = (item: any) => ({
71 description: item.description ?? "HTTP Context Item",
72 content: item.content ?? "",
73 name: item.name ?? this.options.title ?? "HTTP",
74 });
75
76 return Array.isArray(json)
77 ? json.map(createContextItem)
78 : [createContextItem(json)];
79 } catch (e) {
80 console.warn(
81 `Failed to parse response from custom HTTP context provider.\nError:\n${e}\nResponse from server:\n`,
82 json,
83 );
84 return [];
85 }
86 }
87}
88
89export default HttpContextProvider;