-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathpreflight.ts
More file actions
452 lines (412 loc) · 11.5 KB
/
preflight.ts
File metadata and controls
452 lines (412 loc) · 11.5 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
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
import type { SentryTeam } from "../../types/index.js";
import { listOrganizations } from "../api-client.js";
import { getAuthToken } from "../db/auth.js";
import { ApiError, WizardError } from "../errors.js";
import { resolveOrCreateTeam } from "../resolve-team.js";
import { slugify } from "../utils.js";
import { WizardCancelledError } from "./clack-utils.js";
import { tryGetExistingProjectData } from "./existing-project.js";
import { resolveOrgPrefetched } from "./org-prefetch.js";
import type {
ExistingProjectData,
ResolvedInitContext,
WizardOptions,
} from "./types.js";
import { isCancelled, type WizardUI } from "./ui/types.js";
const NUMERIC_ORG_ID_RE = /^\d+$/;
type ExistingProjectChoice = {
project?: string;
existingProject?: ExistingProjectData;
shouldAbort?: boolean;
};
type InitContextSeed = {
org?: string;
project?: string;
existingProject?: ExistingProjectData;
};
type ProjectSelection = Pick<
ResolvedInitContext,
"project" | "existingProject"
>;
/**
* Resolve org, project, team, and auth state before the init workflow starts.
*/
export async function resolveInitContext(
initial: WizardOptions,
ui: WizardUI
): Promise<ResolvedInitContext | null> {
return await withPreflightHandling(ui, async () => {
const seed = await resolveInitContextSeed(initial, ui);
if (!seed) {
return null;
}
const org = await ensureOrg(seed.org, initial, ui);
const projectSelection = await resolveProjectSelection(
org,
initial,
seed,
ui
);
if (!projectSelection) {
return null;
}
const team = await resolveTeam(org, initial, ui);
return buildResolvedInitContext(initial, org, team, projectSelection);
});
}
async function withPreflightHandling(
ui: WizardUI,
action: () => Promise<ResolvedInitContext | null>
): Promise<ResolvedInitContext | null> {
try {
return await action();
} catch (error) {
if (error instanceof WizardCancelledError) {
ui.cancel("Setup cancelled.");
ui.feedback("cancelled");
process.exitCode = 0;
return null;
}
const message = error instanceof Error ? error.message : String(error);
ui.log.error(message);
ui.cancel("Setup failed.");
ui.feedback("failed");
throw error instanceof WizardError ? error : new WizardError(message);
}
}
function buildResolvedInitContext(
initial: WizardOptions,
org: string,
team: string | undefined,
selection: ProjectSelection
): ResolvedInitContext {
return {
directory: initial.directory,
yes: initial.yes,
dryRun: initial.dryRun,
features: initial.features,
org,
team,
project: selection.project,
app: initial.app,
authToken: getAuthToken(),
existingProject: selection.existingProject,
};
}
async function resolveInitContextSeed(
initial: WizardOptions,
ui: WizardUI
): Promise<InitContextSeed | null> {
const detected = await resolveDetectedProject(initial, ui);
if (detected?.shouldAbort) {
return null;
}
return {
org: detected?.org ?? initial.org,
project: detected?.project ?? initial.project,
existingProject: detected?.existingProject,
};
}
async function ensureOrg(
org: string | undefined,
initial: WizardOptions,
ui: WizardUI
): Promise<string> {
if (org) {
return org;
}
const orgResult = await resolveOrgSlug(initial.directory, initial.yes, ui);
if (typeof orgResult === "string") {
return orgResult;
}
throw new WizardError(orgResult.error ?? "Failed to resolve organization.");
}
async function resolveProjectSelection(
org: string,
initial: WizardOptions,
seed: InitContextSeed,
ui: WizardUI
): Promise<ProjectSelection | null> {
if (!seed.project) {
return {
project: seed.project,
existingProject: seed.existingProject,
};
}
const resolved = await resolveExistingProjectChoice({
org,
project: seed.project,
existingProject: seed.existingProject,
yes: initial.yes,
promptOnExisting: Boolean(initial.project && !initial.org),
ui,
});
if (resolved.shouldAbort) {
return null;
}
return mergeProjectSelection(seed, resolved);
}
function mergeProjectSelection(
seed: InitContextSeed,
resolved: ExistingProjectChoice
): ProjectSelection {
const project = "project" in resolved ? resolved.project : seed.project;
const clearedProject =
"project" in resolved && resolved.project === undefined;
return {
project,
existingProject: clearedProject
? undefined
: (resolved.existingProject ?? seed.existingProject),
};
}
async function resolveDetectedProject(
initial: WizardOptions,
ui: WizardUI
): Promise<{
org?: string;
project?: string;
existingProject?: ExistingProjectData;
shouldAbort?: boolean;
} | null> {
if (initial.org || initial.project) {
return null;
}
let detectedProject: { orgSlug: string; projectSlug: string } | null = null;
try {
detectedProject = await detectExistingProject(initial.directory);
} catch {
return null;
}
if (!detectedProject) {
return null;
}
const existingProject = await tryGetExistingProjectData(
detectedProject.orgSlug,
detectedProject.projectSlug
).catch(() => null);
if (initial.yes) {
return {
org: detectedProject.orgSlug,
project: detectedProject.projectSlug,
...(existingProject ? { existingProject } : {}),
};
}
const choice = await ui.select<"existing" | "create">({
message: "Found an existing Sentry project in this codebase.",
options: [
{
value: "existing",
label: `Use existing project (${detectedProject.orgSlug}/${detectedProject.projectSlug})`,
hint: "Sentry is already configured here",
},
{
value: "create",
label: "Create a new Sentry project",
},
],
});
if (isCancelled(choice)) {
throw new WizardCancelledError();
}
if (choice === "existing") {
return {
org: detectedProject.orgSlug,
project: detectedProject.projectSlug,
...(existingProject ? { existingProject } : {}),
};
}
return {};
}
async function resolveExistingProjectChoice(opts: {
org: string;
project: string;
existingProject?: ExistingProjectData;
yes: boolean;
promptOnExisting: boolean;
ui: WizardUI;
}): Promise<ExistingProjectChoice> {
const slug = slugify(opts.project);
if (!slug) {
return { project: opts.project };
}
const existingProject =
opts.existingProject &&
opts.existingProject.orgSlug === opts.org &&
opts.existingProject.projectSlug === slug
? opts.existingProject
: await tryGetExistingProjectData(opts.org, slug).catch(() => null);
if (!existingProject) {
return { project: opts.project };
}
if (!opts.promptOnExisting || opts.yes) {
return {
project: existingProject.projectSlug,
existingProject,
};
}
const choice = await opts.ui.select<"existing" | "create">({
message: `Found existing project '${slug}' in ${opts.org}.`,
options: [
{
value: "existing",
label: `Use existing (${opts.org}/${slug})`,
hint: "Already configured",
},
{
value: "create",
label: "Create a new project",
hint: "Wizard will detect the project name from your codebase",
},
],
});
if (isCancelled(choice)) {
throw new WizardCancelledError();
}
if (choice === "create") {
return { project: undefined };
}
return {
project: existingProject.projectSlug,
existingProject,
};
}
async function resolveTeam(
org: string,
initial: WizardOptions,
ui: WizardUI
): Promise<string | undefined> {
try {
const result = await resolveOrCreateTeam(org, {
team: initial.team,
usageHint: "sentry init",
dryRun: initial.dryRun,
deferAutoCreateOnEmptyOrg: true,
onAmbiguous: initial.yes
? (candidates) => Promise.resolve((candidates[0] as SentryTeam).slug)
: async (candidates) => {
const selected = await ui.select<string>({
message: "Which team should own this project?",
options: candidates.map((team) => ({
value: team.slug,
label: team.slug,
...(team.name !== team.slug ? { hint: team.name } : {}),
})),
});
if (isCancelled(selected)) {
throw new WizardCancelledError();
}
return selected;
},
});
return result.source === "deferred" ? undefined : result.slug;
} catch (error) {
if (error instanceof WizardCancelledError) {
throw error;
}
throw error instanceof WizardError
? error
: new WizardError(error instanceof Error ? error.message : String(error));
}
}
/**
* Format a 403/401 ApiError from listOrganizations() into a { ok: false }
* result, or re-throw if the error is something else.
*
* 403: token lacks org:read scope — user can bypass by supplying the org slug
* directly. 401: token is invalid/expired — supplying an org won't help, only
* re-authenticating will.
*/
function handleOrgListError(error: unknown): { ok: false; error: string } {
if (error instanceof ApiError && error.status === 403) {
const lines: string[] = ["Could not list organizations (403 Forbidden)."];
if (error.detail) {
lines.push(error.detail, "");
}
lines.push(
"Specify the org on the command line: sentry init <org-slug>/",
"Or set an environment variable: SENTRY_ORG=<org-slug> sentry init"
);
return { ok: false, error: lines.join("\n ") };
}
if (error instanceof ApiError && error.status === 401) {
const lines: string[] = [
"Could not list organizations (401 Unauthorized).",
];
if (error.detail) {
lines.push(error.detail);
}
return { ok: false, error: lines.join("\n ") };
}
throw error;
}
async function resolveOrgSlug(
cwd: string,
yes: boolean,
ui: WizardUI
): Promise<string | { ok: false; error: string }> {
const resolved = await resolveOrgPrefetched(cwd);
if (resolved && !NUMERIC_ORG_ID_RE.test(resolved.org)) {
return resolved.org;
}
let orgs: Awaited<ReturnType<typeof listOrganizations>>;
try {
orgs = await listOrganizations();
} catch (error) {
return handleOrgListError(error);
}
if (orgs.length === 0) {
return {
ok: false,
error: "Not authenticated. Run 'sentry auth login' first.",
};
}
if (orgs.length === 1 && orgs[0]) {
return orgs[0].slug;
}
if (yes) {
const slugs = orgs.map((org) => org.slug).join(", ");
return {
ok: false,
error: [
`Multiple organizations found (${slugs}).`,
"Specify one with: sentry init <org-slug>/ [directory]",
" or set SENTRY_ORG=<org-slug>",
].join("\n"),
};
}
const selected = await ui.select<string>({
message: "Which organization should the project be created in?",
options: orgs.map((org) => ({
value: org.slug,
label: org.name,
hint: org.slug,
})),
});
if (isCancelled(selected)) {
throw new WizardCancelledError();
}
return selected;
}
async function detectExistingProject(
cwd: string
): Promise<{ orgSlug: string; projectSlug: string } | null> {
const { detectDsn } = await import("../dsn/index.js");
const dsn = await detectDsn(cwd);
if (!dsn?.publicKey) {
return null;
}
try {
const { resolveDsnByPublicKey } = await import("../resolve-target.js");
const resolved = await resolveDsnByPublicKey(dsn);
if (!resolved) {
return null;
}
return {
orgSlug: resolved.org,
projectSlug: resolved.project,
};
} catch {
return null;
}
}