-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
clack-utils.ts
1219 lines (1082 loc) · 34.8 KB
/
clack-utils.ts
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-ignore - clack is ESM and TS complains about that. It works though
import * as clack from '@clack/prompts';
import axios from 'axios';
import chalk from 'chalk';
import * as childProcess from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { setInterval } from 'timers';
import { URL } from 'url';
import * as Sentry from '@sentry/node';
import { hasPackageInstalled, PackageDotJson } from './package-json';
import { SentryProjectData, WizardOptions } from './types';
import { traceStep } from '../telemetry';
import {
detectPackageManger,
PackageManager,
installPackageWithPackageManager,
packageManagers,
} from './package-manager';
import { debug } from './debug';
import { fulfillsVersionRange } from './semver';
const opn = require('opn') as (
url: string,
) => Promise<childProcess.ChildProcess>;
export const SENTRY_DOT_ENV_FILE = '.env.sentry-build-plugin';
export const SENTRY_CLI_RC_FILE = '.sentryclirc';
export const SENTRY_PROPERTIES_FILE = 'sentry.properties';
const SAAS_URL = 'https://sentry.io/';
interface WizardProjectData {
apiKeys: {
token: string;
};
projects: SentryProjectData[];
}
export interface CliSetupConfig {
filename: string;
name: string;
gitignore: boolean;
likelyAlreadyHasAuthToken(contents: string): boolean;
tokenContent(authToken: string): string;
likelyAlreadyHasOrgAndProject(contents: string): boolean;
orgAndProjContent(org: string, project: string): string;
likelyAlreadyHasUrl?(contents: string): boolean;
urlContent?(url: string): string;
}
export interface CliSetupConfigContent {
authToken: string;
org?: string;
project?: string;
url?: string;
}
export const rcCliSetupConfig: CliSetupConfig = {
filename: SENTRY_CLI_RC_FILE,
name: 'source maps',
gitignore: true,
likelyAlreadyHasAuthToken: function (contents: string): boolean {
return !!(contents.includes('[auth]') && contents.match(/token=./g));
},
tokenContent: function (authToken: string): string {
return `[auth]\ntoken=${authToken}`;
},
likelyAlreadyHasOrgAndProject: function (contents: string): boolean {
return !!(
contents.includes('[defaults]') &&
contents.match(/org=./g) &&
contents.match(/project=./g)
);
},
orgAndProjContent: function (org: string, project: string): string {
return `[defaults]\norg=${org}\nproject=${project}`;
},
};
export const propertiesCliSetupConfig: Required<CliSetupConfig> = {
filename: SENTRY_PROPERTIES_FILE,
gitignore: true,
name: 'debug files',
likelyAlreadyHasAuthToken(contents: string): boolean {
return !!contents.match(/auth\.token=./g);
},
tokenContent(authToken: string): string {
return `auth.token=${authToken}`;
},
likelyAlreadyHasOrgAndProject(contents: string): boolean {
return !!(
contents.match(/defaults\.org=./g) &&
contents.match(/defaults\.project=./g)
);
},
orgAndProjContent(org: string, project: string): string {
return `defaults.org=${org}\ndefaults.project=${project}`;
},
likelyAlreadyHasUrl(contents: string): boolean {
return !!contents.match(/defaults\.url=./g);
},
urlContent(url: string): string {
return `defaults.url=${url}`;
},
};
export async function abort(message?: string, status?: number): Promise<never> {
clack.outro(message ?? 'Wizard setup cancelled.');
const sentryHub = Sentry.getCurrentHub();
const sentryTransaction = sentryHub.getScope().getTransaction();
sentryTransaction?.setStatus('aborted');
sentryTransaction?.finish();
const sentrySession = sentryHub.getScope().getSession();
if (sentrySession) {
sentrySession.status = status === 0 ? 'abnormal' : 'crashed';
sentryHub.captureSession(true);
}
await Sentry.flush(3000);
return process.exit(status ?? 1);
}
export async function abortIfCancelled<T>(
input: T | Promise<T>,
): Promise<Exclude<T, symbol>> {
if (clack.isCancel(await input)) {
clack.cancel('Wizard setup cancelled.');
const sentryHub = Sentry.getCurrentHub();
const sentryTransaction = sentryHub.getScope().getTransaction();
sentryTransaction?.setStatus('cancelled');
sentryTransaction?.finish();
sentryHub.captureSession(true);
await Sentry.flush(3000);
process.exit(0);
} else {
return input as Exclude<T, symbol>;
}
}
export function printWelcome(options: {
wizardName: string;
promoCode?: string;
message?: string;
telemetryEnabled?: boolean;
}): void {
let wizardPackage: { version?: string } = {};
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
wizardPackage = require(path.join(
path.dirname(require.resolve('@sentry/wizard')),
'..',
'package.json',
));
} catch {
// We don't need to have this
}
// eslint-disable-next-line no-console
console.log('');
clack.intro(chalk.inverse(` ${options.wizardName} `));
let welcomeText =
options.message ||
`The ${options.wizardName} will help you set up Sentry for your application.\nThank you for using Sentry :)`;
if (options.promoCode) {
welcomeText = `${welcomeText}\n\nUsing promo-code: ${options.promoCode}`;
}
if (wizardPackage.version) {
welcomeText = `${welcomeText}\n\nVersion: ${wizardPackage.version}`;
}
if (options.telemetryEnabled) {
welcomeText = `${welcomeText}
This wizard sends telemetry data and crash reports to Sentry. This helps us improve the Wizard.
You can turn this off at any time by running ${chalk.cyanBright(
'sentry-wizard --disable-telemetry',
)}.`;
}
clack.note(welcomeText);
}
export async function confirmContinueIfNoOrDirtyGitRepo(): Promise<void> {
return traceStep('check-git-status', async () => {
if (!isInGitRepo()) {
const continueWithoutGit = await abortIfCancelled(
clack.confirm({
message:
'You are not inside a git repository. The wizard will create and update files. Do you want to continue anyway?',
}),
);
Sentry.setTag('continue-without-git', continueWithoutGit);
if (!continueWithoutGit) {
await abort(undefined, 0);
}
}
const uncommittedOrUntrackedFiles = getUncommittedOrUntrackedFiles();
if (uncommittedOrUntrackedFiles.length) {
clack.log.warn(
`You have uncommitted or untracked files in your repo:
${uncommittedOrUntrackedFiles.join('\n')}
The wizard will create and update files.`,
);
const continueWithDirtyRepo = await abortIfCancelled(
clack.confirm({
message: 'Do you want to continue anyway?',
}),
);
Sentry.setTag('continue-with-dirty-repo', continueWithDirtyRepo);
if (!continueWithDirtyRepo) {
await abort(undefined, 0);
}
}
});
}
function isInGitRepo() {
try {
childProcess.execSync('git rev-parse --is-inside-work-tree', {
stdio: 'ignore',
});
return true;
} catch {
return false;
}
}
function getUncommittedOrUntrackedFiles(): string[] {
try {
const gitStatus = childProcess
.execSync('git status --porcelain=v1')
.toString();
const files = gitStatus
.split(os.EOL)
.map((line) => line.trim())
.filter(Boolean)
.map((f) => `- ${f.split(/\s+/)[1]}`);
return files;
} catch {
return [];
}
}
export async function askToInstallSentryCLI(): Promise<boolean> {
return await abortIfCancelled(
clack.confirm({
message:
"You don't have Sentry CLI installed. Do you want to install it?",
}),
);
}
export async function askForItemSelection(
items: string[],
message: string,
): Promise<{ value: string; index: number }> {
const selection: { value: string; index: number } | symbol =
await abortIfCancelled(
clack.select({
maxItems: 12,
message: message,
options: items.map((item, index) => {
return {
value: { value: item, index: index },
label: item,
};
}),
}),
);
return selection;
}
export async function confirmContinueIfPackageVersionNotSupported({
packageId,
packageName,
packageVersion,
acceptableVersions,
}: {
packageId: string;
packageName: string;
packageVersion: string;
acceptableVersions: string;
}): Promise<void> {
return traceStep(`check-package-version`, async () => {
Sentry.setTag(`${packageName.toLowerCase()}-version`, packageVersion);
const isSupportedVersion = fulfillsVersionRange({
acceptableVersions,
version: packageVersion,
canBeLatest: true,
});
if (isSupportedVersion) {
Sentry.setTag(`${packageName.toLowerCase()}-supported`, true);
return;
}
clack.log.warn(
`You have an unsupported version of ${packageName} installed:
${packageId}@${packageVersion}`,
);
clack.note(
`Please upgrade to ${acceptableVersions} if you wish to use the Sentry Wizard.
Or setup using ${chalk.cyan(
'https://docs.sentry.io/platforms/react-native/manual-setup/manual-setup/',
)}`,
);
const continueWithUnsupportedVersion = await abortIfCancelled(
clack.confirm({
message: 'Do you want to continue anyway?',
}),
);
Sentry.setTag(
`${packageName.toLowerCase()}-continue-with-unsupported-version`,
continueWithUnsupportedVersion,
);
if (!continueWithUnsupportedVersion) {
await abort(undefined, 0);
}
});
}
/**
* Installs or updates a package with the user's package manager.
*
* IMPORTANT: This function modifies the `package.json`! Be sure to re-read
* it if you make additional modifications to it after calling this function!
*/
export async function installPackage({
packageName,
alreadyInstalled,
askBeforeUpdating = true,
}: {
packageName: string;
alreadyInstalled: boolean;
askBeforeUpdating?: boolean;
}): Promise<void> {
return traceStep('install-package', async () => {
if (alreadyInstalled && askBeforeUpdating) {
const shouldUpdatePackage = await abortIfCancelled(
clack.confirm({
message: `The ${chalk.bold.cyan(
packageName,
)} package is already installed. Do you want to update it to the latest version?`,
}),
);
if (!shouldUpdatePackage) {
return;
}
}
const sdkInstallSpinner = clack.spinner();
const packageManager = await getPackageManager();
sdkInstallSpinner.start(
`${alreadyInstalled ? 'Updating' : 'Installing'} ${chalk.bold.cyan(
packageName,
)} with ${chalk.bold(packageManager.label)}.`,
);
try {
await installPackageWithPackageManager(packageManager, packageName);
} catch (e) {
sdkInstallSpinner.stop('Installation failed.');
clack.log.error(
`${chalk.red(
'Encountered the following error during installation:',
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
)}\n\n${e}\n\n${chalk.dim(
'If you think this issue is caused by the Sentry wizard, let us know here:\nhttps://github.com/getsentry/sentry-wizard/issues',
)}`,
);
await abort();
}
sdkInstallSpinner.stop(
`${alreadyInstalled ? 'Updated' : 'Installed'} ${chalk.bold.cyan(
packageName,
)} with ${chalk.bold(packageManager.label)}.`,
);
});
}
export async function addSentryCliConfig(
{ authToken, org, project, url }: CliSetupConfigContent,
setupConfig: CliSetupConfig = rcCliSetupConfig,
): Promise<void> {
return traceStep('add-sentry-cli-config', async () => {
const configPath = path.join(process.cwd(), setupConfig.filename);
const configExists = fs.existsSync(configPath);
let configContents =
(configExists && fs.readFileSync(configPath, 'utf8')) || '';
configContents = addAuthTokenToSentryConfig(
configContents,
authToken,
setupConfig,
);
configContents = addOrgAndProjectToSentryConfig(
configContents,
org,
project,
setupConfig,
);
configContents = addUrlToSentryConfig(configContents, url, setupConfig);
try {
await fs.promises.writeFile(configPath, configContents, {
encoding: 'utf8',
flag: 'w',
});
clack.log.success(
`${configExists ? 'Saved' : 'Created'} ${chalk.cyan(
setupConfig.filename,
)}.`,
);
} catch {
clack.log.warning(
`Failed to add auth token to ${chalk.cyan(
setupConfig.filename,
)}. Uploading ${
setupConfig.name
} during build will likely not work locally.`,
);
}
if (setupConfig.gitignore) {
await addCliConfigFileToGitIgnore(setupConfig.filename);
} else {
clack.log.warn(
chalk.yellow('DO NOT commit auth token to your repository!'),
);
}
});
}
function addAuthTokenToSentryConfig(
configContents: string,
authToken: string | undefined,
setupConfig: CliSetupConfig,
): string {
if (!authToken) {
return configContents;
}
if (setupConfig.likelyAlreadyHasAuthToken(configContents)) {
clack.log.warn(
`${chalk.cyan(
setupConfig.filename,
)} already has auth token. Will not add one.`,
);
return configContents;
}
const newContents = `${configContents}\n${setupConfig.tokenContent(
authToken,
)}\n`;
clack.log.success(
`Added auth token to ${chalk.cyan(
setupConfig.filename,
)} for you to test uploading ${setupConfig.name} locally.`,
);
return newContents;
}
function addOrgAndProjectToSentryConfig(
configContents: string,
org: string | undefined,
project: string | undefined,
setupConfig: CliSetupConfig,
): string {
if (!org || !project) {
return configContents;
}
if (setupConfig.likelyAlreadyHasOrgAndProject(configContents)) {
clack.log.warn(
`${chalk.cyan(
setupConfig.filename,
)} already has org and project. Will not add them.`,
);
return configContents;
}
const newContents = `${configContents}\n${setupConfig.orgAndProjContent(
org,
project,
)}\n`;
clack.log.success(
`Added default org and project to ${chalk.cyan(
setupConfig.filename,
)} for you to test uploading ${setupConfig.name} locally.`,
);
return newContents;
}
function addUrlToSentryConfig(
configContents: string,
url: string | undefined,
setupConfig: CliSetupConfig,
): string {
if (!url || !setupConfig.urlContent || !setupConfig.likelyAlreadyHasUrl) {
return configContents;
}
if (setupConfig.likelyAlreadyHasUrl(configContents)) {
clack.log.warn(
`${chalk.cyan(setupConfig.filename)} already has url. Will not add one.`,
);
return configContents;
}
const newContents = `${configContents}\n${setupConfig.urlContent(url)}\n`;
clack.log.success(
`Added default url to ${chalk.cyan(
setupConfig.filename,
)} for you to test uploading ${setupConfig.name} locally.`,
);
return newContents;
}
export async function addDotEnvSentryBuildPluginFile(
authToken: string,
): Promise<void> {
const envVarContent = `# DO NOT commit this file to your repository!
# The SENTRY_AUTH_TOKEN variable is picked up by the Sentry Build Plugin.
# It's used for authentication when uploading source maps.
# You can also set this env variable in your own \`.env\` files and remove this file.
SENTRY_AUTH_TOKEN="${authToken}"
`;
const dotEnvFilePath = path.join(process.cwd(), SENTRY_DOT_ENV_FILE);
const dotEnvFileExists = fs.existsSync(dotEnvFilePath);
if (dotEnvFileExists) {
const dotEnvFileContent = fs.readFileSync(dotEnvFilePath, 'utf8');
const hasAuthToken = !!dotEnvFileContent.match(
/^\s*SENTRY_AUTH_TOKEN\s*=/g,
);
if (hasAuthToken) {
clack.log.warn(
`${chalk.bold(
SENTRY_DOT_ENV_FILE,
)} already has auth token. Will not add one.`,
);
} else {
try {
await fs.promises.writeFile(
dotEnvFilePath,
`${dotEnvFileContent}\n${envVarContent}`,
{
encoding: 'utf8',
flag: 'w',
},
);
clack.log.success(
`Added auth token to ${chalk.bold(SENTRY_DOT_ENV_FILE)}`,
);
} catch {
clack.log.warning(
`Failed to add auth token to ${chalk.bold(
SENTRY_DOT_ENV_FILE,
)}. Uploading source maps during build will likely not work locally.`,
);
}
}
} else {
try {
await fs.promises.writeFile(dotEnvFilePath, envVarContent, {
encoding: 'utf8',
flag: 'w',
});
clack.log.success(
`Created ${chalk.bold(
SENTRY_DOT_ENV_FILE,
)} with auth token for you to test source map uploading locally.`,
);
} catch {
clack.log.warning(
`Failed to create ${chalk.bold(
SENTRY_DOT_ENV_FILE,
)} with auth token. Uploading source maps during build will likely not work locally.`,
);
}
}
await addCliConfigFileToGitIgnore(SENTRY_DOT_ENV_FILE);
}
async function addCliConfigFileToGitIgnore(filename: string): Promise<void> {
//TODO: Add a check to see if the file is already ignored in .gitignore
try {
await fs.promises.appendFile(
path.join(process.cwd(), '.gitignore'),
`\n# Sentry Config File\n${filename}\n`,
{ encoding: 'utf8' },
);
clack.log.success(
`Added ${chalk.cyan(filename)} to ${chalk.cyan('.gitignore')}.`,
);
} catch {
clack.log.error(
`Failed adding ${chalk.cyan(filename)} to ${chalk.cyan(
'.gitignore',
)}. Please add it manually!`,
);
}
}
/**
* Checks if @param packageId is listed as a dependency in @param packageJson.
* If not, it will ask users if they want to continue without the package.
*
* Use this function to check if e.g. a the framework of the SDK is installed
*
* @param packageJson the package.json object
* @param packageId the npm name of the package
* @param packageName a human readable name of the package
*/
export async function ensurePackageIsInstalled(
packageJson: PackageDotJson,
packageId: string,
packageName: string,
): Promise<void> {
return traceStep('ensure-package-installed', async () => {
const installed = hasPackageInstalled(packageId, packageJson);
Sentry.setTag(`${packageName.toLowerCase()}-installed`, installed);
if (!installed) {
Sentry.setTag(`${packageName.toLowerCase()}-installed`, false);
const continueWithoutPackage = await abortIfCancelled(
clack.confirm({
message: `${packageName} does not seem to be installed. Do you still want to continue?`,
initialValue: false,
}),
);
if (!continueWithoutPackage) {
await abort(undefined, 0);
}
}
});
}
export async function getPackageDotJson(): Promise<PackageDotJson> {
const packageJsonFileContents = await fs.promises
.readFile(path.join(process.cwd(), 'package.json'), 'utf8')
.catch(() => {
clack.log.error(
'Could not find package.json. Make sure to run the wizard in the root of your app!',
);
return abort();
});
let packageJson: PackageDotJson | undefined = undefined;
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
packageJson = JSON.parse(packageJsonFileContents);
} catch {
clack.log.error(
`Unable to parse your ${chalk.cyan(
'package.json',
)}. Make sure it has a valid format!`,
);
await abort();
}
return packageJson || {};
}
async function getPackageManager(): Promise<PackageManager> {
const detectedPackageManager = detectPackageManger();
if (detectedPackageManager) {
return detectedPackageManager;
}
const selectedPackageManager: PackageManager | symbol =
await abortIfCancelled(
clack.select({
message: 'Please select your package manager.',
options: packageManagers.map((packageManager) => ({
value: packageManager,
label: packageManager.label,
})),
}),
);
Sentry.setTag('package-manager', selectedPackageManager.name);
return selectedPackageManager;
}
export function isUsingTypeScript() {
try {
return fs.existsSync(path.join(process.cwd(), 'tsconfig.json'));
} catch {
return false;
}
}
/**
* Checks if we already got project data from a previous wizard invocation.
* If yes, this data is returned.
* Otherwise, we start the login flow and ask the user to select a project.
*
* Use this function to get project data for the wizard.
*
* @param options wizard options
* @param platform the platform of the wizard
* @returns project data (org, project, token, url)
*/
export async function getOrAskForProjectData(
options: WizardOptions,
platform?:
| 'javascript-nextjs'
| 'javascript-remix'
| 'javascript-sveltekit'
| 'apple-ios'
| 'android'
| 'react-native',
): Promise<{
sentryUrl: string;
selfHosted: boolean;
selectedProject: SentryProjectData;
authToken: string;
}> {
if (options.preSelectedProject) {
return {
selfHosted: options.preSelectedProject.selfHosted,
sentryUrl: options.url ?? SAAS_URL,
authToken: options.preSelectedProject.authToken,
selectedProject: options.preSelectedProject.project,
};
}
const { url: sentryUrl, selfHosted } = await traceStep(
'ask-self-hosted',
() => askForSelfHosted(options.url),
);
const { projects, apiKeys } = await traceStep('login', () =>
askForWizardLogin({
promoCode: options.promoCode,
url: sentryUrl,
platform: platform,
}),
);
if (!projects || !projects.length) {
clack.log.error(
'No projects found. Please create a project in Sentry and try again.',
);
Sentry.setTag('no-projects-found', true);
await abort();
}
const selectedProject = await traceStep('select-project', () =>
askForProjectSelection(projects),
);
return {
sentryUrl,
selfHosted,
authToken: apiKeys.token,
selectedProject,
};
}
/**
* Asks users if they are using SaaS or self-hosted Sentry and returns the validated URL.
*
* If users started the wizard with a --url arg, that URL is used as the default and we skip
* the self-hosted question. However, the passed url is still validated and in case it's
* invalid, users are asked to enter a new one until it is valid.
*
* @param urlFromArgs the url passed via the --url arg
*/
async function askForSelfHosted(urlFromArgs?: string): Promise<{
url: string;
selfHosted: boolean;
}> {
if (!urlFromArgs) {
const choice: 'saas' | 'self-hosted' | symbol = await abortIfCancelled(
clack.select({
message: 'Are you using Sentry SaaS or self-hosted Sentry?',
options: [
{ value: 'saas', label: 'Sentry SaaS (sentry.io)' },
{
value: 'self-hosted',
label: 'Self-hosted/on-premise/single-tenant',
},
],
}),
);
if (choice === 'saas') {
Sentry.setTag('url', SAAS_URL);
Sentry.setTag('self-hosted', false);
return { url: SAAS_URL, selfHosted: false };
}
}
let validUrl: string | undefined;
let tmpUrlFromArgs = urlFromArgs;
while (validUrl === undefined) {
const url =
tmpUrlFromArgs ||
(await abortIfCancelled(
clack.text({
message: `Please enter the URL of your ${
urlFromArgs ? '' : 'self-hosted '
}Sentry instance.`,
placeholder: 'https://sentry.io/',
}),
));
tmpUrlFromArgs = undefined;
try {
validUrl = new URL(url).toString();
// We assume everywhere else that the URL ends in a slash
if (!validUrl.endsWith('/')) {
validUrl += '/';
}
} catch {
clack.log.error(
'Please enter a valid URL. (It should look something like "https://sentry.mydomain.com/")',
);
}
}
const isSelfHostedUrl = new URL(validUrl).host !== new URL(SAAS_URL).host;
Sentry.setTag('url', validUrl);
Sentry.setTag('self-hosted', isSelfHostedUrl);
return { url: validUrl, selfHosted: true };
}
async function askForWizardLogin(options: {
url: string;
promoCode?: string;
platform?:
| 'javascript-nextjs'
| 'javascript-remix'
| 'javascript-sveltekit'
| 'apple-ios'
| 'android'
| 'react-native';
}): Promise<WizardProjectData> {
Sentry.setTag('has-promo-code', !!options.promoCode);
let hasSentryAccount = await clack.confirm({
message: 'Do you already have a Sentry account?',
});
hasSentryAccount = await abortIfCancelled(hasSentryAccount);
Sentry.setTag('already-has-sentry-account', hasSentryAccount);
let wizardHash: string;
try {
wizardHash = (
await axios.get<{ hash: string }>(`${options.url}api/0/wizard/`)
).data.hash;
} catch (e: unknown) {
if (options.url !== SAAS_URL) {
clack.log.error('Loading Wizard failed. Did you provide the right URL?');
clack.log.info(JSON.stringify(e, null, 2));
await abort(
chalk.red(
'Please check your configuration and try again.\n\n Let us know if you think this is an issue with the wizard or Sentry: https://github.com/getsentry/sentry-wizard/issues',
),
);
} else {
clack.log.error('Loading Wizard failed.');
clack.log.info(JSON.stringify(e, null, 2));
await abort(
chalk.red(
'Please try again in a few minutes and let us know if this issue persists: https://github.com/getsentry/sentry-wizard/issues',
),
);
}
}
const loginUrl = new URL(
`${options.url}account/settings/wizard/${wizardHash!}/`,
);
if (!hasSentryAccount) {
loginUrl.searchParams.set('signup', '1');
if (options.platform) {
loginUrl.searchParams.set('project_platform', options.platform);
}
}
if (options.promoCode) {
loginUrl.searchParams.set('code', options.promoCode);
}
const urlToOpen = loginUrl.toString();
clack.log.info(
`${chalk.bold(
`If the browser window didn't open automatically, please open the following link to ${
hasSentryAccount ? 'log' : 'sign'
} into Sentry:`,
)}\n\n${chalk.cyan(urlToOpen)}`,
);
opn(urlToOpen).catch(() => {
// opn throws in environments that don't have a browser (e.g. remote shells) so we just noop here
});
const loginSpinner = clack.spinner();
loginSpinner.start('Waiting for you to log in using the link above');
const data = await new Promise<WizardProjectData>((resolve) => {
const pollingInterval = setInterval(() => {
axios
.get<WizardProjectData>(`${options.url}api/0/wizard/${wizardHash}/`, {
headers: {
'Accept-Encoding': 'deflate',
},
})
.then((result) => {
resolve(result.data);
clearTimeout(timeout);
clearInterval(pollingInterval);
void axios.delete(`${options.url}api/0/wizard/${wizardHash}/`);
})
.catch(() => {
// noop - just try again
});
}, 500);
const timeout = setTimeout(() => {
clearInterval(pollingInterval);
loginSpinner.stop(
'Login timed out. No worries - it happens to the best of us.',
);
Sentry.setTag('opened-wizard-link', false);
void abort('Please restart the Wizard and log in to complete the setup.');
}, 180_000);
});
loginSpinner.stop('Login complete.');
Sentry.setTag('opened-wizard-link', true);
return data;
}
async function askForProjectSelection(
projects: SentryProjectData[],
): Promise<SentryProjectData> {
const label = (project: SentryProjectData): string => {
return `${project.organization.slug}/${project.slug}`;
};
const sortedProjects = [...projects];
sortedProjects.sort((a: SentryProjectData, b: SentryProjectData) => {
return label(a).localeCompare(label(b));
});
const selection: SentryProjectData | symbol = await abortIfCancelled(
clack.select({
maxItems: 12,
message: 'Select your Sentry project.',
options: sortedProjects.map((project) => {
return {
value: project,
label: label(project),
};