UNPKG

@sentry/wizard

Version:

Sentry wizard helping you to configure your project

316 lines 20.8 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.runNextjsWizard = void 0; /* eslint-disable max-lines */ // @ts-ignore - clack is ESM and TS complains about that. It works though var prompts_1 = __importDefault(require("@clack/prompts")); var chalk_1 = __importDefault(require("chalk")); var fs = __importStar(require("fs")); // @ts-ignore - magicast is ESM and TS complains about that. It works though var magicast_1 = require("magicast"); var path = __importStar(require("path")); var clack_utils_1 = require("../utils/clack-utils"); var templates_1 = require("./templates"); // eslint-disable-next-line complexity function runNextjsWizard(options) { var _a; return __awaiter(this, void 0, void 0, function () { var packageJson, _b, sentryUrl, selfHosted, _c, projects, apiKeys, selectedProject, isUsingTypescript, configVariants, _i, configVariants_1, configVariant, jsConfig, tsConfig, jsConfigExists, tsConfigExists, shouldWriteFile, existingConfigs, overwriteExistingConfigs, sentryWebpackOptionsTemplate, sentryBuildOptionsTemplate, nextConfigJs, nextConfigMjs, nextConfigJsExists, nextConfigMjsExists, nextConfgiJsContent, probablyIncludesSdk, shouldInject, injectAnyhow, nextConfgiMjsContent, probablyIncludesSdk, shouldInject, injectAnyhow, mod, expressionToWrap, newCode, _d, shouldContinue, maybePagesDirPath, maybeSrcPagesDirPath, pagesLocation, examplePageContents, mightBeUsingVercel; return __generator(this, function (_e) { switch (_e.label) { case 0: (0, clack_utils_1.printWelcome)({ wizardName: 'Sentry Next.js Wizard', promoCode: options.promoCode, }); return [4 /*yield*/, (0, clack_utils_1.confirmContinueEvenThoughNoGitRepo)()]; case 1: _e.sent(); return [4 /*yield*/, (0, clack_utils_1.getPackageDotJson)()]; case 2: packageJson = _e.sent(); return [4 /*yield*/, (0, clack_utils_1.ensurePackageIsInstalled)(packageJson, 'next', 'Next.js')]; case 3: _e.sent(); return [4 /*yield*/, (0, clack_utils_1.askForSelfHosted)()]; case 4: _b = _e.sent(), sentryUrl = _b.url, selfHosted = _b.selfHosted; return [4 /*yield*/, (0, clack_utils_1.askForWizardLogin)({ promoCode: options.promoCode, url: sentryUrl, platform: 'javascript-nextjs', })]; case 5: _c = _e.sent(), projects = _c.projects, apiKeys = _c.apiKeys; return [4 /*yield*/, (0, clack_utils_1.askForProjectSelection)(projects)]; case 6: selectedProject = _e.sent(); return [4 /*yield*/, (0, clack_utils_1.installPackage)({ packageName: '@sentry/nextjs', alreadyInstalled: !!((_a = packageJson === null || packageJson === void 0 ? void 0 : packageJson.dependencies) === null || _a === void 0 ? void 0 : _a['@sentry/nextjs']), })]; case 7: _e.sent(); isUsingTypescript = false; try { isUsingTypescript = fs.existsSync(path.join(process.cwd(), 'tsconfig.json')); } catch (_f) { // noop - Default to assuming user is not using typescript } configVariants = ['server', 'client', 'edge']; _i = 0, configVariants_1 = configVariants; _e.label = 8; case 8: if (!(_i < configVariants_1.length)) return [3 /*break*/, 13]; configVariant = configVariants_1[_i]; jsConfig = "sentry.".concat(configVariant, ".config.js"); tsConfig = "sentry.".concat(configVariant, ".config.ts"); jsConfigExists = fs.existsSync(path.join(process.cwd(), jsConfig)); tsConfigExists = fs.existsSync(path.join(process.cwd(), tsConfig)); shouldWriteFile = true; if (!(jsConfigExists || tsConfigExists)) return [3 /*break*/, 10]; existingConfigs = []; if (jsConfigExists) { existingConfigs.push(jsConfig); } if (tsConfigExists) { existingConfigs.push(tsConfig); } return [4 /*yield*/, (0, clack_utils_1.abortIfCancelled)(prompts_1.default.confirm({ message: "Found existing Sentry ".concat(configVariant, " config (").concat(existingConfigs.join(', '), "). Overwrite ").concat(existingConfigs.length > 1 ? 'them' : 'it', "?"), }))]; case 9: overwriteExistingConfigs = _e.sent(); shouldWriteFile = overwriteExistingConfigs; if (overwriteExistingConfigs) { if (jsConfigExists) { fs.unlinkSync(path.join(process.cwd(), jsConfig)); prompts_1.default.log.warn("Removed existing ".concat(chalk_1.default.bold(jsConfig), ".")); } if (tsConfigExists) { fs.unlinkSync(path.join(process.cwd(), tsConfig)); prompts_1.default.log.warn("Removed existing ".concat(chalk_1.default.bold(tsConfig), ".")); } } _e.label = 10; case 10: if (!shouldWriteFile) return [3 /*break*/, 12]; return [4 /*yield*/, fs.promises.writeFile(path.join(process.cwd(), isUsingTypescript ? tsConfig : jsConfig), (0, templates_1.getSentryConfigContents)(selectedProject.keys[0].dsn.public, configVariant), { encoding: 'utf8', flag: 'w' })]; case 11: _e.sent(); prompts_1.default.log.success("Created fresh ".concat(chalk_1.default.bold(isUsingTypescript ? tsConfig : jsConfig), ".")); _e.label = 12; case 12: _i++; return [3 /*break*/, 8]; case 13: sentryWebpackOptionsTemplate = (0, templates_1.getNextjsWebpackPluginOptionsTemplate)(selectedProject.organization.slug, selectedProject.slug); sentryBuildOptionsTemplate = (0, templates_1.getNextjsSentryBuildOptionsTemplate)(); nextConfigJs = 'next.config.js'; nextConfigMjs = 'next.config.mjs'; nextConfigJsExists = fs.existsSync(path.join(process.cwd(), nextConfigJs)); nextConfigMjsExists = fs.existsSync(path.join(process.cwd(), nextConfigMjs)); if (!(!nextConfigJsExists && !nextConfigMjsExists)) return [3 /*break*/, 15]; return [4 /*yield*/, fs.promises.writeFile(path.join(process.cwd(), nextConfigJs), (0, templates_1.getNextjsConfigCjsTemplate)(sentryWebpackOptionsTemplate, sentryBuildOptionsTemplate), { encoding: 'utf8', flag: 'w' })]; case 14: _e.sent(); prompts_1.default.log.success("Created ".concat(chalk_1.default.bold('next.config.js'), " with Sentry configuration.")); _e.label = 15; case 15: if (!nextConfigJsExists) return [3 /*break*/, 19]; nextConfgiJsContent = fs.readFileSync(path.join(process.cwd(), nextConfigJs), 'utf8'); probablyIncludesSdk = nextConfgiJsContent.includes('@sentry/nextjs') && nextConfgiJsContent.includes('withSentryConfig'); shouldInject = true; if (!probablyIncludesSdk) return [3 /*break*/, 17]; return [4 /*yield*/, (0, clack_utils_1.abortIfCancelled)(prompts_1.default.confirm({ message: "".concat(chalk_1.default.bold(nextConfigJs), " already contains Sentry SDK configuration. Should the wizard modify it anyways?"), }))]; case 16: injectAnyhow = _e.sent(); shouldInject = injectAnyhow; _e.label = 17; case 17: if (!shouldInject) return [3 /*break*/, 19]; return [4 /*yield*/, fs.promises.appendFile(path.join(process.cwd(), nextConfigJs), (0, templates_1.getNextjsConfigCjsAppendix)(sentryWebpackOptionsTemplate, sentryBuildOptionsTemplate), 'utf8')]; case 18: _e.sent(); prompts_1.default.log.success("Added Sentry configuration to ".concat(chalk_1.default.bold(nextConfigJs), ". ").concat(chalk_1.default.dim('(you probably want to clean this up a bit!)'))); _e.label = 19; case 19: if (!nextConfigMjsExists) return [3 /*break*/, 28]; nextConfgiMjsContent = fs.readFileSync(path.join(process.cwd(), nextConfigMjs), 'utf8'); probablyIncludesSdk = nextConfgiMjsContent.includes('@sentry/nextjs') && nextConfgiMjsContent.includes('withSentryConfig'); shouldInject = true; if (!probablyIncludesSdk) return [3 /*break*/, 21]; return [4 /*yield*/, (0, clack_utils_1.abortIfCancelled)(prompts_1.default.confirm({ message: "".concat(chalk_1.default.bold(nextConfigMjs), " already contains Sentry SDK configuration. Should the wizard modify it anyways?"), }))]; case 20: injectAnyhow = _e.sent(); shouldInject = injectAnyhow; _e.label = 21; case 21: _e.trys.push([21, 24, , 28]); if (!shouldInject) return [3 /*break*/, 23]; mod = (0, magicast_1.parseModule)(nextConfgiMjsContent); mod.imports.$add({ from: '@sentry/nextjs', imported: 'withSentryConfig', local: 'withSentryConfig', }); expressionToWrap = (0, magicast_1.generateCode)(mod.exports.default.$ast).code; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment mod.exports.default = magicast_1.builders.raw("withSentryConfig(\n ".concat(expressionToWrap, ",\n ").concat(sentryWebpackOptionsTemplate, ",\n ").concat(sentryBuildOptionsTemplate, "\n)")); newCode = mod.generate().code; return [4 /*yield*/, fs.promises.writeFile(path.join(process.cwd(), nextConfigMjs), newCode, { encoding: 'utf8', flag: 'w', })]; case 22: _e.sent(); prompts_1.default.log.success("Added Sentry configuration to ".concat(chalk_1.default.bold(nextConfigMjs), ". ").concat(chalk_1.default.dim('(you probably want to clean this up a bit!)'))); _e.label = 23; case 23: return [3 /*break*/, 28]; case 24: _d = _e.sent(); prompts_1.default.log.warn(chalk_1.default.yellow("Something went wrong writing to ".concat(chalk_1.default.bold(nextConfigMjs)))); prompts_1.default.log.info("Please put the following code snippet into ".concat(chalk_1.default.bold(nextConfigMjs), ": ").concat(chalk_1.default.dim('You probably have to clean it up a bit.'), "\n")); // eslint-disable-next-line no-console console.log((0, templates_1.getNextjsConfigEsmCopyPasteSnippet)(sentryWebpackOptionsTemplate, sentryBuildOptionsTemplate)); return [4 /*yield*/, (0, clack_utils_1.abortIfCancelled)(prompts_1.default.confirm({ message: "Are you done putting the snippet above into ".concat(chalk_1.default.bold(nextConfigMjs), "?"), active: 'Yes', inactive: 'No, get me out of here', }))]; case 25: shouldContinue = _e.sent(); if (!!shouldContinue) return [3 /*break*/, 27]; return [4 /*yield*/, (0, clack_utils_1.abort)()]; case 26: _e.sent(); _e.label = 27; case 27: return [3 /*break*/, 28]; case 28: maybePagesDirPath = path.join(process.cwd(), 'pages'); maybeSrcPagesDirPath = path.join(process.cwd(), 'src', 'pages'); pagesLocation = fs.existsSync(maybePagesDirPath) && fs.lstatSync(maybePagesDirPath).isDirectory() ? ['pages'] : fs.existsSync(maybeSrcPagesDirPath) && fs.lstatSync(maybeSrcPagesDirPath).isDirectory() ? ['src', 'pages'] : undefined; if (!pagesLocation) { pagesLocation = ['pages']; fs.mkdirSync(path.join.apply(path, __spreadArray([process.cwd()], pagesLocation, false)), { recursive: true, }); } if (!pagesLocation) return [3 /*break*/, 31]; examplePageContents = (0, templates_1.getSentryExamplePageContents)({ selfHosted: selfHosted, orgSlug: selectedProject.organization.slug, projectId: selectedProject.id, url: sentryUrl, }); return [4 /*yield*/, fs.promises.writeFile(path.join.apply(path, __spreadArray(__spreadArray([process.cwd()], pagesLocation, false), ['sentry-example-page.js'], false)), examplePageContents, { encoding: 'utf8', flag: 'w' })]; case 29: _e.sent(); prompts_1.default.log.success("Created ".concat(chalk_1.default.bold(path.join.apply(path, __spreadArray(__spreadArray([], pagesLocation, false), ['sentry-example-page.js'], false))), ".")); fs.mkdirSync(path.join.apply(path, __spreadArray(__spreadArray([process.cwd()], pagesLocation, false), ['api'], false)), { recursive: true, }); return [4 /*yield*/, fs.promises.writeFile(path.join.apply(path, __spreadArray(__spreadArray([process.cwd()], pagesLocation, false), ['api', 'sentry-example-api.js'], false)), (0, templates_1.getSentryExampleApiRoute)(), { encoding: 'utf8', flag: 'w' })]; case 30: _e.sent(); prompts_1.default.log.success("Created ".concat(chalk_1.default.bold(path.join.apply(path, __spreadArray(__spreadArray([], pagesLocation, false), ['api', 'sentry-example-api.js'], false))), ".")); _e.label = 31; case 31: return [4 /*yield*/, (0, clack_utils_1.addSentryCliRc)(apiKeys.token)]; case 32: _e.sent(); mightBeUsingVercel = fs.existsSync(path.join(process.cwd(), 'vercel.json')); prompts_1.default.outro("".concat(chalk_1.default.green('Everything is set up!'), "\n\n ").concat(chalk_1.default.cyan('You can validate your setup by starting your dev environment (`next dev`) and visiting "/sentry-example-page".'), "\n").concat(mightBeUsingVercel ? "\n \u25B2 It seems like you're using Vercel. We recommend using the Sentry Vercel integration: https://vercel.com/integrations/sentry\n" : '', "\n ").concat(chalk_1.default.dim('If you encounter any issues, let us know here: https://github.com/getsentry/sentry-javascript/issues'))); return [2 /*return*/]; } }); }); } exports.runNextjsWizard = runNextjsWizard; //# sourceMappingURL=nextjs-wizard.js.map