-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathserviceWorker.ts
More file actions
214 lines (201 loc) · 6.19 KB
/
serviceWorker.ts
File metadata and controls
214 lines (201 loc) · 6.19 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
import { v4 as uuidv4 } from 'uuid';
import { registerUser } from './auth';
import {
ClientSettings,
GetCompletionsResponseMessage,
LanguageServerServiceWorkerClient,
LanguageServerWorkerRequest,
} from './common';
import { loggedIn, loggedOut, unhealthy } from './shared';
import {
defaultAllowlist,
getGeneralPortalUrl,
getStorageItem,
getStorageItems,
initializeStorageWithDefaults,
setStorageItem,
} from './storage';
import { PUBLIC_API_SERVER, PUBLIC_WEBSITE } from './urls';
import {
AcceptCompletionRequest,
GetCompletionsRequest,
} from '../proto/exa/language_server_pb/language_server_pb';
const authStates: string[] = [];
chrome.runtime.onInstalled.addListener(async () => {
// Here goes everything you want to execute after extension initialization
await initializeStorageWithDefaults({
settings: {},
allowlist: { defaults: defaultAllowlist, current: defaultAllowlist },
});
console.log('Extension successfully installed!');
if ((await getStorageItem('user'))?.apiKey === undefined) {
// TODO(prem): Is this necessary?
await loggedOut();
// Inline the code for openAuthTab() because we can't invoke sendMessage.
const uuid = uuidv4();
authStates.push(uuid);
// TODO(prem): Deduplicate with Options.tsx/storage.ts.
const portalUrl = await (async (): Promise<string | undefined> => {
const url = await getGeneralPortalUrl();
if (url === undefined) {
if (CODEIUM_ENTERPRISE) {
return undefined;
}
return PUBLIC_WEBSITE;
}
return url;
})();
if (portalUrl !== undefined) {
await chrome.tabs.create({
url: `${portalUrl}/profile?redirect_uri=chrome-extension://${chrome.runtime.id}&state=${uuid}`,
});
}
} else {
await loggedIn();
}
});
// The only external messages:
// - website auth
// - request for api key
// - set icon and error message
chrome.runtime.onMessageExternal.addListener((message, sender, sendResponse) => {
if (message.type === 'user') {
(async () => {
const user = await getStorageItem('user');
sendResponse(user);
if (user?.apiKey === undefined) {
await loggedOut();
}
})().catch((e) => {
console.error(e);
});
return true;
}
if (message.type === 'clientSettings') {
(async () => {
const storageItems = await getStorageItems(['user', 'enterpriseDefaultModel']);
const clientSettings: ClientSettings = {
apiKey: storageItems.user?.apiKey,
defaultModel: storageItems.enterpriseDefaultModel,
};
sendResponse(clientSettings);
})().catch((e) => {
console.error(e);
});
return true;
}
if (message.type === 'allowlist') {
(async () => {
const allowlist = await getStorageItem('allowlist');
sendResponse(allowlist);
})().catch((e) => {
console.error(e);
});
return true;
}
if (message.type == 'error') {
unhealthy(message.message).catch((e) => {
console.error(e);
});
// No response needed.
return;
}
if (message.type == 'success') {
loggedIn().catch((e) => {
console.error(e);
});
// No response needed.
return;
}
if (typeof message.token !== 'string' || typeof message.state !== 'string') {
console.log('Unexpected message:', message);
return;
}
(async () => {
const typedMessage = message as { token: string; state: string };
const user = await getStorageItem('user');
if (user?.apiKey === undefined) {
await login(typedMessage.token);
}
})().catch((e) => {
console.error(e);
});
});
chrome.runtime.onStartup.addListener(async () => {
if ((await getStorageItem('user'))?.apiKey === undefined) {
await loggedOut();
} else {
await loggedIn();
}
});
chrome.runtime.onMessage.addListener((message) => {
// TODO(prem): Strongly type this.
if (message.type === 'state') {
const payload = message.payload as { state: string };
authStates.push(payload.state);
} else if (message.type === 'manual') {
login(message.token).catch((e) => {
console.error(e);
});
} else {
console.log('Unrecognized message:', message);
}
});
const clientMap = new Map<string, LanguageServerServiceWorkerClient>();
// TODO(prem): Is it safe to make this listener async to simplify the LanguageServerServiceWorkerClient constructor?
chrome.runtime.onConnectExternal.addListener((port) => {
// TODO(prem): Technically this URL isn't synchronized with the user/API key.
clientMap.set(
port.name,
new LanguageServerServiceWorkerClient(getLanguageServerUrl(), port.name)
);
port.onDisconnect.addListener((port) => {
clientMap.delete(port.name);
});
port.onMessage.addListener(async (message: LanguageServerWorkerRequest, port) => {
const client = clientMap.get(port.name);
if (message.kind === 'getCompletions') {
const response = await client?.getCompletions(
GetCompletionsRequest.fromJsonString(message.request)
);
const reply: GetCompletionsResponseMessage = {
kind: 'getCompletions',
requestId: message.requestId,
response: response?.toJsonString(),
};
port.postMessage(reply);
} else if (message.kind == 'acceptCompletion') {
await client?.acceptedLastCompletion(AcceptCompletionRequest.fromJsonString(message.request));
} else {
console.log('Unrecognized message:', message);
}
});
});
async function login(token: string) {
try {
const portalUrl = await getGeneralPortalUrl();
const user = await registerUser(token);
await setStorageItem('user', {
apiKey: user.api_key,
name: user.name,
userPortalUrl: portalUrl,
});
await loggedIn();
// TODO(prem): Open popup.
// https://github.com/GoogleChrome/developer.chrome.com/issues/2602
// await chrome.action.openPopup();
} catch (error) {
console.log(error);
}
}
async function getLanguageServerUrl(): Promise<string | undefined> {
const user = await getStorageItem('user');
const userPortalUrl = user?.userPortalUrl;
if (userPortalUrl === undefined || userPortalUrl === '') {
if (CODEIUM_ENTERPRISE) {
return undefined;
}
return PUBLIC_API_SERVER;
}
return `${userPortalUrl}/_route/language_server`;
}