-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathcodeContext.tsx
330 lines (284 loc) · 8.3 KB
/
codeContext.tsx
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
'use client';
import {createContext, useEffect, useReducer, useState} from 'react';
import Cookies from 'js-cookie';
type ProjectCodeKeywords = {
API_URL: string;
DSN: string;
MINIDUMP_URL: string;
ORG_ID: number;
ORG_INGEST_DOMAIN: string;
ORG_SLUG: string;
PROJECT_ID: number;
PROJECT_SLUG: string;
PUBLIC_DSN: string;
PUBLIC_KEY: string;
SECRET_KEY: string;
UNREAL_URL: string;
title: string;
};
type UserCodeKeywords = {
ID: number;
NAME: string;
};
type CodeKeywords = {
PROJECT: ProjectCodeKeywords[];
USER: UserCodeKeywords | undefined;
};
type Dsn = {
host: string;
pathname: string;
publicKey: string;
scheme: string;
secretKey?: string;
};
type ProjectApiResult = {
dsn: string;
dsnPublic: string;
id: number;
name: string;
organizationId: number;
organizationName: string;
organizationSlug: string;
projectName: string;
projectSlug: string;
publicKey: string;
secretKey: string;
};
type UserApiResult = {
avatarUrl: string;
id: number;
isAuthenticated: boolean;
name: string;
};
type Region = {
name: string;
url: string;
};
// only fetch them once
let cachedCodeKeywords: CodeKeywords | null = null;
export const DEFAULTS: CodeKeywords = {
PROJECT: [
{
DSN: 'https://[email protected]/0',
PUBLIC_DSN: 'https://[email protected]/0',
PUBLIC_KEY: 'examplePublicKey',
SECRET_KEY: 'exampleSecretKey',
API_URL: 'https://sentry.io/api',
PROJECT_ID: 0,
PROJECT_SLUG: 'example-project',
ORG_ID: 0,
ORG_SLUG: 'example-org',
ORG_INGEST_DOMAIN: 'o0.ingest.sentry.io',
MINIDUMP_URL:
'https://o0.ingest.sentry.io/api/0/minidump/?sentry_key=examplePublicKey',
UNREAL_URL: 'https://o0.ingest.sentry.io/api/0/unreal/examplePublicKey/',
title: `example-org / example-project`,
},
],
USER: undefined,
};
type SelectedCodeTabs = Record<string, string | undefined>;
type CodeContextType = {
codeKeywords: CodeKeywords;
isLoading: boolean;
sharedCodeSelection: [SelectedCodeTabs, React.Dispatch<[string, string]>];
sharedKeywordSelection: [
Record<string, number>,
React.Dispatch<Record<string, number>>,
];
};
export const CodeContext = createContext<CodeContextType | null>(null);
function parseDsn(dsn: string): Dsn {
const match = dsn.match(/^(.*?\/\/)(.*?):(.*?)@(.*?)(\/.*?)$/);
if (match === null) {
throw new Error('Failed to parse DSN');
}
return {
scheme: match[1],
publicKey: escape(match[2]),
secretKey: escape(match[3]),
host: escape(match[4]),
pathname: escape(match[5]),
};
}
const formatMinidumpURL = ({scheme, host, pathname, publicKey}: Dsn) => {
return `${scheme}${host}/api${pathname}/minidump/?sentry_key=${publicKey}`;
};
const formatUnrealEngineURL = ({scheme, host, pathname, publicKey}: Dsn) => {
return `${scheme}${host}/api${pathname}/unreal/${publicKey}/`;
};
const formatApiUrl = ({scheme, host}: Dsn) => {
const apiHost = host.indexOf('.ingest.') >= 0 ? host.split('.ingest.')[1] : host;
return `${scheme}${apiHost}/api`;
};
function getHost(): string {
if (process.env.NODE_ENV === 'development') {
return 'http://dev.getsentry.net:8000';
}
return 'https://sentry.io';
}
function makeDefaults() {
// eslint-disable-next-line no-console
console.warn('Unable to fetch codeContext - using defaults.');
return DEFAULTS;
}
/**
* Fetch project details from sentry
*/
export async function fetchCodeKeywords(): Promise<CodeKeywords> {
let json: {projects: ProjectApiResult[]; user: UserApiResult | undefined} = {
projects: [],
user: undefined,
};
// First fetch which regions the user has a presence
const url = `${getHost()}/api/0/users/me/regions/`;
let regions: Region[] = [];
try {
const resp = await fetch(url, {credentials: 'include'});
if (!resp.ok) {
return makeDefaults();
}
const data = await resp.json();
if (data.regions) {
regions = data.regions;
}
} catch (e) {
return makeDefaults();
}
// Then fetch the project configuration for each region, and merge it together.
const results = await Promise.all(
regions.map(async region => {
const regionUrl = `${region.url}/docs/api/user/`;
try {
const resp = await fetch(regionUrl, {credentials: 'include'});
if (!resp.ok) {
return makeDefaults();
}
return resp.json();
} catch (e) {
return makeDefaults();
}
})
);
json = results.reduce((acc, item) => {
if (item.projects) {
acc.projects = acc.projects.concat(item.projects);
}
if (item.user) {
acc.user = item.user;
}
return acc;
}, json);
const {projects, user} = json;
if (projects?.length === 0) {
return makeDefaults();
}
return {
PROJECT: projects.map(project => {
const parsedDsn = parseDsn(project.dsn);
return {
DSN: project.dsn,
PUBLIC_DSN: project.dsnPublic,
PUBLIC_KEY: parsedDsn.publicKey,
SECRET_KEY: parsedDsn.secretKey ?? 'exampleSecretKey',
API_URL: formatApiUrl(parsedDsn),
PROJECT_ID: project.id,
PROJECT_SLUG: project.projectSlug,
ORG_ID: project.organizationId,
ORG_SLUG: project.organizationSlug,
ORG_INGEST_DOMAIN: `o${project.organizationId}.ingest.sentry.io`,
MINIDUMP_URL: formatMinidumpURL(parsedDsn),
UNREAL_URL: formatUnrealEngineURL(parsedDsn),
title: `${project.organizationSlug} / ${project.projectSlug}`,
};
}),
USER: user?.isAuthenticated
? {
ID: user.id,
NAME: user.name,
}
: undefined,
};
}
function getCsrfToken(): string {
// is sentry-sc in production, but may also be sc in other envs
// So we just try both variants
const cookieNames = ['sentry-sc', 'sc'];
const value = cookieNames
.map(cookieName => Cookies.get(cookieName))
.find(token => token !== null);
return value ?? '';
}
export async function createOrgAuthToken({
orgSlug,
name,
}: {
name: string;
orgSlug: string;
}): Promise<string | null> {
const url = `${getHost()}/api/0/organizations/${orgSlug}/org-auth-tokens/`;
const body = {name};
try {
const resp = await fetch(url, {
method: 'POST',
body: JSON.stringify(body),
credentials: 'include',
headers: {
Accept: 'application/json; charset=utf-8',
'Content-Type': 'application/json',
'X-CSRFToken': getCsrfToken(),
},
});
if (!resp.ok) {
return null;
}
const json = await resp.json();
return json.token;
} catch {
return null;
}
}
export function CodeContextProvider({children}: {children: React.ReactNode}) {
const [codeKeywords, setCodeKeywords] = useState(cachedCodeKeywords ?? DEFAULTS);
const [isLoading, setIsLoading] = useState<boolean>(cachedCodeKeywords ? false : true);
useEffect(() => {
if (cachedCodeKeywords === null) {
setIsLoading(true);
fetchCodeKeywords().then((config: CodeKeywords) => {
cachedCodeKeywords = config;
setCodeKeywords(config);
setIsLoading(false);
});
}
}, [setIsLoading, setCodeKeywords]);
// sharedKeywordSelection maintains a global mapping for each "keyword"
// namespace to the index of the selected item.
//
// NOTE: This ONLY does anything for the `PROJECT` keyword namespace, since
// that is the only namespace that actually has a list
const sharedKeywordSelection = useState<Record<string, number>>({});
const storedSelections = Object.fromEntries(
Object.entries(
// default to an empty object if localStorage is not available on the server
typeof localStorage === 'undefined' ? {} : localStorage
).filter(([key]) => key.startsWith('Tabgroup:'))
);
// Maintains the global selection for which code block tab is selected
const sharedCodeSelection = useReducer(
(tabs: SelectedCodeTabs, [groupId, value]: [string, string]) => {
return {...tabs, [groupId]: value};
},
storedSelections
);
const result: CodeContextType = {
codeKeywords,
sharedCodeSelection,
sharedKeywordSelection,
isLoading,
};
return <CodeContext.Provider value={result}>{children}</CodeContext.Provider>;
}
/** For tests only. */
export function _setCachedCodeKeywords(codeKeywords: CodeKeywords) {
cachedCodeKeywords = codeKeywords;
}