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
|
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === "getJwt") {
chrome.storage.local.get(["jwt"], ({ jwt }) => {
sendResponse({ jwt });
});
return true;
}
else if (request.type === "urlChange") {
const content = request.content;
const url = request.url;
(async () => {
chrome.storage.local.get(["jwt"], ({ jwt }) => {
if (!jwt) {
console.error("No JWT found");
return;
}
fetch("https://anycontext.dhr.wtf/api/store", {
method: "POST",
headers: {
"Authorization": `Bearer ${jwt}`,
},
body: JSON.stringify({ pageContent: content, url }),
}).then(ers => console.log(ers.status))
});
})();
}
else if (request.type === "queryApi") {
const input = request.input;
const jwt = request.jwt;
(async () => {
await fetch("https://anycontext.dhr.wtf/api/ask", {
method: "POST",
headers: {
"Authorization": `Bearer ${jwt}`,
},
body: JSON.stringify({
query: input,
}),
}).then(async response => {
if (!response.body) {
throw new Error("No response body");
}
if (!sender.tab?.id) {
throw new Error("No tab ID");
}
const reader = response.body.getReader();
// eslint-disable-next-line no-constant-condition
while (true) {
const { done, value } = await reader.read();
if (done) break;
// For simplicity, we're sending chunks as they come.
// This might need to be adapted based on your data and needs.
const chunkAsString = new TextDecoder('utf-8').decode(value).replace("data: ", "")
chrome.tabs.sendMessage(sender.tab.id, { action: "streamData", data: chunkAsString });
}
// Notify the content script that the stream is complete.
chrome.tabs.sendMessage(sender.tab.id, { action: "streamEnd" });
});
// Indicate that sendResponse will be called asynchronously.
return true;
})();
}
});
|