Elffuss BraidHub

kikocis/continue public

main · 2.7 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 })
27 : undefined;
28 } catch (e) {
29 return undefined;
30 }
31 }
32
33 override get description(): ContextProviderDescription {
34 return {
35 title: this.options.title || HttpContextProvider.description.title,
36 displayTitle:
37 this.options.displayTitle ||
38 this.options.name ||
39 HttpContextProvider.description.displayTitle,
40 description:
41 this.options.description || HttpContextProvider.description.description,
42 type: HttpContextProvider.description.type,
43 renderInlineAs:
44 this.options.renderInlineAs ||
45 HttpContextProvider.description.renderInlineAs,
46 };
47 }
48
49 async getContextItems(
50 query: string,
51 extras: ContextProviderExtras,
52 ): Promise<ContextItem[]> {
53 const parsedUrl = new URL(this.options.url);
54 const response = await extras.fetch(parsedUrl, {
55 method: "POST",
56 headers: {
57 "Content-Type": "application/json",
58 ...(this.options.headers || {}),
59 },
60 body: JSON.stringify({
61 query: query || "",
62 fullInput: extras.fullInput,
63 options: this.options.options,
64 workspacePath: await this.getWorkspacePath(extras.ide, parsedUrl),
65 }),
66 });
67
68 const json = await response.json();
69
70 try {
71 const createContextItem = (item: any) => ({
72 description: item.description ?? "HTTP Context Item",
73 content: item.content ?? "",
74 name: item.name ?? this.options.title ?? "HTTP",
75 uri: {
76 type: item.uri.type,
77 value: item.uri.value,
78 },
79 });
80
81 return Array.isArray(json)
82 ? json.map(createContextItem)
83 : [createContextItem(json)];
84 } catch (e) {
85 console.warn(
86 `Failed to parse response from custom HTTP context provider.\nError:\n${e}\nResponse from server:\n`,
87 json,
88 );
89 return [];
90 }
91 }
92}
93
94export default HttpContextProvider;