@sentry/wizard 3.11.0 → 3.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/package.json +1 -1
  3. package/dist/src/android/android-wizard.js +8 -0
  4. package/dist/src/android/android-wizard.js.map +1 -1
  5. package/dist/src/android/code-tools.d.ts +8 -0
  6. package/dist/src/android/code-tools.js +20 -8
  7. package/dist/src/android/code-tools.js.map +1 -1
  8. package/dist/src/android/gradle.js +6 -1
  9. package/dist/src/android/gradle.js.map +1 -1
  10. package/dist/src/sourcemaps/tools/vite.js +36 -111
  11. package/dist/src/sourcemaps/tools/vite.js.map +1 -1
  12. package/dist/src/sourcemaps/tools/webpack.d.ts +6 -1
  13. package/dist/src/sourcemaps/tools/webpack.js +290 -25
  14. package/dist/src/sourcemaps/tools/webpack.js.map +1 -1
  15. package/dist/src/sveltekit/sdk-setup.js +2 -2
  16. package/dist/src/sveltekit/sdk-setup.js.map +1 -1
  17. package/dist/src/utils/ast-utils.d.ts +7 -3
  18. package/dist/src/utils/ast-utils.js +20 -5
  19. package/dist/src/utils/ast-utils.js.map +1 -1
  20. package/dist/src/utils/clack-utils.d.ts +52 -0
  21. package/dist/src/utils/clack-utils.js +169 -12
  22. package/dist/src/utils/clack-utils.js.map +1 -1
  23. package/dist/test/android/code-tools.test.d.ts +1 -0
  24. package/dist/test/android/code-tools.test.js +34 -0
  25. package/dist/test/android/code-tools.test.js.map +1 -0
  26. package/dist/test/sourcemaps/tools/webpack.test.d.ts +1 -0
  27. package/dist/test/sourcemaps/tools/webpack.test.js +179 -0
  28. package/dist/test/sourcemaps/tools/webpack.test.js.map +1 -0
  29. package/dist/test/utils/ast-utils.test.js +42 -7
  30. package/dist/test/utils/ast-utils.test.js.map +1 -1
  31. package/dist/test/utils/clack-utils.test.d.ts +1 -0
  32. package/dist/test/utils/clack-utils.test.js +200 -0
  33. package/dist/test/utils/clack-utils.test.js.map +1 -0
  34. package/package.json +1 -1
  35. package/src/android/android-wizard.ts +8 -0
  36. package/src/android/code-tools.ts +21 -7
  37. package/src/android/gradle.ts +6 -1
  38. package/src/sourcemaps/tools/vite.ts +22 -88
  39. package/src/sourcemaps/tools/webpack.ts +369 -30
  40. package/src/sveltekit/sdk-setup.ts +6 -2
  41. package/src/utils/ast-utils.ts +23 -7
  42. package/src/utils/clack-utils.ts +150 -2
  43. package/test/android/code-tools.test.ts +49 -0
  44. package/test/sourcemaps/tools/webpack.test.ts +303 -0
  45. package/test/utils/ast-utils.test.ts +28 -9
  46. package/test/utils/clack-utils.test.ts +142 -0
@@ -58,53 +58,318 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
58
58
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
59
59
  }
60
60
  };
61
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
62
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
63
+ if (ar || !(i in from)) {
64
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
65
+ ar[i] = from[i];
66
+ }
67
+ }
68
+ return to.concat(ar || Array.prototype.slice.call(from));
69
+ };
61
70
  var __importDefault = (this && this.__importDefault) || function (mod) {
62
71
  return (mod && mod.__esModule) ? mod : { "default": mod };
63
72
  };
64
73
  Object.defineProperty(exports, "__esModule", { value: true });
65
- exports.configureWebPackPlugin = void 0;
74
+ exports.modifyWebpackConfig = exports.configureWebPackPlugin = void 0;
75
+ var path = __importStar(require("path"));
76
+ var fs = __importStar(require("fs"));
66
77
  // @ts-ignore - clack is ESM and TS complains about that. It works though
67
- var prompts_1 = __importStar(require("@clack/prompts"));
78
+ var clack = __importStar(require("@clack/prompts"));
68
79
  var chalk_1 = __importDefault(require("chalk"));
80
+ var recast = __importStar(require("recast"));
81
+ var Sentry = __importStar(require("@sentry/node"));
69
82
  var clack_utils_1 = require("../../utils/clack-utils");
70
83
  var package_json_1 = require("../../utils/package-json");
71
- var getCodeSnippet = function (options) {
72
- return chalk_1.default.gray("\n".concat(chalk_1.default.greenBright('const { sentryWebpackPlugin } = require("@sentry/webpack-plugin");'), "\n\nmodule.exports = {\n // ... other config options\n ").concat(chalk_1.default.greenBright('devtool: "source-map", // Source map generation must be turned on'), "\n plugins: [\n ").concat(chalk_1.default.greenBright("sentryWebpackPlugin({\n authToken: process.env.SENTRY_AUTH_TOKEN,\n org: \"".concat(options.orgSlug, "\",\n project: \"").concat(options.projectSlug, "\",").concat(options.selfHosted ? "\n url: \"".concat(options.url, "\",") : '', " \n })")), ",\n ],\n};\n"));
84
+ var ast_utils_1 = require("../../utils/ast-utils");
85
+ var debug_1 = require("../../utils/debug");
86
+ var getCodeSnippet = function (options, colors) {
87
+ var rawImportStmt = 'const { sentryWebpackPlugin } = require("@sentry/webpack-plugin");';
88
+ var rawGenerateSourceMapsOption = 'devtool: "source-map", // Source map generation must be turned on';
89
+ var rawSentryWebpackPluginFunction = "sentryWebpackPlugin({\n authToken: process.env.SENTRY_AUTH_TOKEN,\n org: \"".concat(options.orgSlug, "\",\n project: \"").concat(options.projectSlug, "\",").concat(options.selfHosted ? "\n url: \"".concat(options.url, "\",") : '', "\n })");
90
+ var importStmt = colors ? chalk_1.default.greenBright(rawImportStmt) : rawImportStmt;
91
+ var generateSourceMapsOption = colors
92
+ ? chalk_1.default.greenBright(rawGenerateSourceMapsOption)
93
+ : rawGenerateSourceMapsOption;
94
+ var sentryWebpackPluginFunction = colors
95
+ ? chalk_1.default.greenBright(rawSentryWebpackPluginFunction)
96
+ : rawSentryWebpackPluginFunction;
97
+ var code = getWebpackConfigContent(importStmt, generateSourceMapsOption, sentryWebpackPluginFunction);
98
+ return colors ? chalk_1.default.gray(code) : code;
73
99
  };
100
+ var getWebpackConfigContent = function (importStmt, generateSourceMapsOption, sentryWebpackPluginFunction) { return "".concat(importStmt, "\n\nmodule.exports = {\n // ... other options\n ").concat(generateSourceMapsOption, ",\n plugins: [\n // Put the Sentry Webpack plugin after all other plugins\n ").concat(sentryWebpackPluginFunction, ",\n ],\n}\n"); };
74
101
  var configureWebPackPlugin = function (options) { return __awaiter(void 0, void 0, void 0, function () {
75
- var _a, _b, _c;
76
- var _d;
77
- return __generator(this, function (_e) {
78
- switch (_e.label) {
102
+ var _a, _b, _c, webpackConfigPath, _d, successfullyAdded;
103
+ var _e;
104
+ var _f;
105
+ return __generator(this, function (_g) {
106
+ switch (_g.label) {
79
107
  case 0:
80
108
  _a = clack_utils_1.installPackage;
81
- _d = {
109
+ _e = {
82
110
  packageName: '@sentry/webpack-plugin'
83
111
  };
84
112
  _b = package_json_1.hasPackageInstalled;
85
113
  _c = ['@sentry/webpack-plugin'];
86
114
  return [4 /*yield*/, (0, clack_utils_1.getPackageDotJson)()];
87
- case 1: return [4 /*yield*/, _a.apply(void 0, [(_d.alreadyInstalled = _b.apply(void 0, _c.concat([_e.sent()])),
88
- _d)])];
115
+ case 1: return [4 /*yield*/, _a.apply(void 0, [(_e.alreadyInstalled = _b.apply(void 0, _c.concat([_g.sent()])),
116
+ _e)])];
89
117
  case 2:
90
- _e.sent();
91
- prompts_1.default.log.step("Add the following code to your ".concat(chalk_1.default.bold('webpack.config.js'), " file:"));
92
- // Intentially logging directly to console here so that the code can be copied/pasted directly
93
- // eslint-disable-next-line no-console
94
- console.log(getCodeSnippet(options));
95
- return [4 /*yield*/, (0, clack_utils_1.abortIfCancelled)((0, prompts_1.select)({
96
- message: 'Did you copy the snippet above?',
97
- options: [{ label: 'Yes, continue!', value: true }],
98
- initialValue: true,
99
- }))];
100
- case 3:
101
- _e.sent();
102
- return [4 /*yield*/, (0, clack_utils_1.addDotEnvSentryBuildPluginFile)(options.authToken)];
118
+ _g.sent();
119
+ if (!((_f = (0, ast_utils_1.findFile)(path.resolve(process.cwd(), 'webpack.config'))) !== null && _f !== void 0)) return [3 /*break*/, 3];
120
+ _d = _f;
121
+ return [3 /*break*/, 5];
122
+ case 3: return [4 /*yield*/, (0, clack_utils_1.askForToolConfigPath)('Webpack', 'webpack.config.js')];
103
123
  case 4:
104
- _e.sent();
124
+ _d = (_g.sent());
125
+ _g.label = 5;
126
+ case 5:
127
+ webpackConfigPath = _d;
128
+ successfullyAdded = false;
129
+ if (!webpackConfigPath) return [3 /*break*/, 7];
130
+ return [4 /*yield*/, modifyWebpackConfig(webpackConfigPath, options)];
131
+ case 6:
132
+ successfullyAdded = _g.sent();
133
+ return [3 /*break*/, 9];
134
+ case 7: return [4 /*yield*/, (0, clack_utils_1.createNewConfigFile)(path.join(process.cwd(), 'webpack.config.js'), getCodeSnippet(options, false), 'More information about Webpack configs: https://vitejs.dev/config/')];
135
+ case 8:
136
+ successfullyAdded = _g.sent();
137
+ Sentry.setTag('created-new-config', successfullyAdded ? 'success' : 'fail');
138
+ _g.label = 9;
139
+ case 9:
140
+ if (!successfullyAdded) return [3 /*break*/, 10];
141
+ clack.log.info("We recommend checking the ".concat(webpackConfigPath ? 'modified' : 'added', " file after the wizard finished to ensure it works with your build setup."));
142
+ Sentry.setTag('ast-mod', 'success');
143
+ return [3 /*break*/, 12];
144
+ case 10:
145
+ Sentry.setTag('ast-mod', 'fail');
146
+ return [4 /*yield*/, (0, clack_utils_1.showCopyPasteInstructions)(path.basename(webpackConfigPath || 'webpack.config.js'), getCodeSnippet(options, true))];
147
+ case 11:
148
+ _g.sent();
149
+ _g.label = 12;
150
+ case 12: return [4 /*yield*/, (0, clack_utils_1.addDotEnvSentryBuildPluginFile)(options.authToken)];
151
+ case 13:
152
+ _g.sent();
105
153
  return [2 /*return*/];
106
154
  }
107
155
  });
108
156
  }); };
109
157
  exports.configureWebPackPlugin = configureWebPackPlugin;
158
+ /**
159
+ * Modifies a webpack config file to enable source map generation and add the Sentry webpack plugin
160
+ * exported only for testing
161
+ */
162
+ function modifyWebpackConfig(webpackConfigPath, options) {
163
+ return __awaiter(this, void 0, void 0, function () {
164
+ var webpackConfig, prettyConfigFilename, program, exportStmt, configObject, enabledSourcemaps, addedPlugin, code, e_1;
165
+ return __generator(this, function (_a) {
166
+ switch (_a.label) {
167
+ case 0:
168
+ _a.trys.push([0, 4, , 5]);
169
+ return [4 /*yield*/, fs.promises.readFile(webpackConfigPath, {
170
+ encoding: 'utf-8',
171
+ })];
172
+ case 1:
173
+ webpackConfig = _a.sent();
174
+ prettyConfigFilename = chalk_1.default.cyan(path.basename(webpackConfigPath));
175
+ program = recast.parse(webpackConfig.toString()).program;
176
+ return [4 /*yield*/, shouldModifyWebpackConfig(program, prettyConfigFilename)];
177
+ case 2:
178
+ if (!(_a.sent())) {
179
+ // Sentry tag is set in shouldModifyWebpackConfig
180
+ return [2 /*return*/, false];
181
+ }
182
+ exportStmt = getCjsModuleExports(program);
183
+ if (!exportStmt) {
184
+ // We only care about CJS at the moment since it's probably the most widely used format for webpack configs.
185
+ (0, debug_1.debug)("Could not find module.exports = {...} in ".concat(webpackConfigPath, "."));
186
+ Sentry.setTag('ast-mod-fail-reason', 'config-object-not-found');
187
+ return [2 /*return*/, false];
188
+ }
189
+ configObject = getWebpackConfigObject(exportStmt, program);
190
+ if (!configObject) {
191
+ (0, debug_1.debug)("Couldn't find config object in ".concat(webpackConfigPath));
192
+ Sentry.setTag('ast-mod-fail-reason', 'config-object-not-found');
193
+ return [2 /*return*/, false];
194
+ }
195
+ enabledSourcemaps = enableSourcemapsGeneration(configObject);
196
+ if (enabledSourcemaps) {
197
+ clack.log.success("Enabled source map generation in ".concat(prettyConfigFilename, "."));
198
+ }
199
+ else {
200
+ clack.log.warn("Couldn't enable source maps generation in ".concat(prettyConfigFilename, " Please follow the instructions below."));
201
+ Sentry.setTag('ast-mod-fail-reason', 'insertion-fail');
202
+ return [2 /*return*/, false];
203
+ }
204
+ addedPlugin = addSentryWebpackPlugin(program, configObject, options);
205
+ if (addedPlugin) {
206
+ clack.log.success("Added Sentry webpack plugin to ".concat(prettyConfigFilename, "."));
207
+ }
208
+ else {
209
+ clack.log.warn("Couldn't add Sentry webpack plugin to ".concat(prettyConfigFilename, ". Please follow the instructions below."));
210
+ Sentry.setTag('ast-mod-fail-reason', 'insertion-fail');
211
+ return [2 /*return*/, false];
212
+ }
213
+ code = recast.print(program).code;
214
+ return [4 /*yield*/, fs.promises.writeFile(webpackConfigPath, code)];
215
+ case 3:
216
+ _a.sent();
217
+ return [2 /*return*/, true];
218
+ case 4:
219
+ e_1 = _a.sent();
220
+ Sentry.setTag('ast-mod-fail-reason', 'insertion-fail');
221
+ (0, debug_1.debug)(e_1);
222
+ return [2 /*return*/, false];
223
+ case 5: return [2 /*return*/];
224
+ }
225
+ });
226
+ });
227
+ }
228
+ exports.modifyWebpackConfig = modifyWebpackConfig;
229
+ function shouldModifyWebpackConfig(program, prettyConfigFilename) {
230
+ return __awaiter(this, void 0, void 0, function () {
231
+ var shouldContinue;
232
+ return __generator(this, function (_a) {
233
+ switch (_a.label) {
234
+ case 0:
235
+ if (!(0, ast_utils_1.hasSentryContent)(program)) return [3 /*break*/, 2];
236
+ return [4 /*yield*/, (0, clack_utils_1.abortIfCancelled)(clack.select({
237
+ message: "Seems like ".concat(prettyConfigFilename, " already contains Sentry-related code. Should the wizard modify it anyway?"),
238
+ options: [
239
+ {
240
+ label: 'Yes, add the Sentry Webpack plugin',
241
+ value: true,
242
+ },
243
+ {
244
+ label: 'No, show me instructions to manually add the plugin',
245
+ value: false,
246
+ },
247
+ ],
248
+ initialValue: true,
249
+ }))];
250
+ case 1:
251
+ shouldContinue = _a.sent();
252
+ if (!shouldContinue) {
253
+ Sentry.setTag('ast-mod-fail-reason', 'has-sentry-content');
254
+ return [2 /*return*/, false];
255
+ }
256
+ _a.label = 2;
257
+ case 2: return [2 /*return*/, true];
258
+ }
259
+ });
260
+ });
261
+ }
262
+ function addSentryWebpackPlugin(program, configObj, options) {
263
+ var b = addSentryWebpackPluginImport(program);
264
+ var sentryPluginCall = b.callExpression(b.identifier('sentryWebpackPlugin'), [
265
+ b.objectExpression(__spreadArray([
266
+ b.objectProperty(b.identifier('authToken'), b.identifier('process.env.SENTRY_AUTH_TOKEN')),
267
+ b.objectProperty(b.identifier('org'), b.stringLiteral(options.orgSlug)),
268
+ b.objectProperty(b.identifier('project'), b.stringLiteral(options.projectSlug))
269
+ ], (options.selfHosted
270
+ ? [
271
+ b.objectProperty(b.identifier('url'), b.stringLiteral(options.url)),
272
+ ]
273
+ : []), true)),
274
+ ]);
275
+ var pluginsProp = configObj.properties.find(function (p) {
276
+ return p.type === 'Property' &&
277
+ p.key.type === 'Identifier' &&
278
+ p.key.name === 'plugins';
279
+ });
280
+ if (pluginsProp) {
281
+ if (pluginsProp.value.type === 'ArrayExpression') {
282
+ pluginsProp.value.elements.push(sentryPluginCall);
283
+ }
284
+ else {
285
+ pluginsProp.value = b.arrayExpression([sentryPluginCall]);
286
+ }
287
+ return true;
288
+ }
289
+ configObj.properties.push(b.objectProperty(b.identifier('plugins'), b.arrayExpression([sentryPluginCall])));
290
+ return true;
291
+ }
292
+ function addSentryWebpackPluginImport(program) {
293
+ var b = recast.types.builders;
294
+ var sentryPluginRequireStmt = b.variableDeclaration('const', [
295
+ b.variableDeclarator(b.objectPattern([
296
+ b.objectProperty.from({
297
+ key: b.identifier('sentryWebpackPlugin'),
298
+ value: b.identifier('sentryWebpackPlugin'),
299
+ shorthand: true,
300
+ }),
301
+ ]), b.callExpression(b.identifier('require'), [
302
+ b.stringLiteral('@sentry/webpack-plugin'),
303
+ ])),
304
+ ]);
305
+ program.body.unshift(sentryPluginRequireStmt);
306
+ return b;
307
+ }
308
+ function enableSourcemapsGeneration(configObj) {
309
+ var _a;
310
+ var b = recast.types.builders;
311
+ var devtoolProp = configObj.properties.find(function (p) {
312
+ return p.type === 'Property' &&
313
+ p.key.type === 'Identifier' &&
314
+ p.key.name === 'devtool';
315
+ });
316
+ if (devtoolProp) {
317
+ // devtool can have quite a lot of source maps values.
318
+ // see: https://webpack.js.org/configuration/devtool/#devtool
319
+ // For Sentry to work best, we should set it to "source-map" or "hidden-source-map"
320
+ // Heuristic:
321
+ // - all values that contain "hidden" will be set to "hidden-source-map"
322
+ // - all other values will be set to "source-map"
323
+ if ((devtoolProp.value.type === 'Literal' ||
324
+ devtoolProp.value.type === 'StringLiteral') &&
325
+ ((_a = devtoolProp.value.value) === null || _a === void 0 ? void 0 : _a.toString().startsWith('hidden-'))) {
326
+ devtoolProp.value = b.stringLiteral('hidden-source-map');
327
+ }
328
+ else {
329
+ devtoolProp.value = b.stringLiteral('source-map');
330
+ }
331
+ return true;
332
+ }
333
+ configObj.properties.push(b.objectProperty(b.identifier('devtool'), b.stringLiteral('source-map')));
334
+ return true;
335
+ }
336
+ function getWebpackConfigObject(moduleExports, program) {
337
+ var _a;
338
+ var rhs = moduleExports.right;
339
+ if (rhs.type === 'ObjectExpression') {
340
+ return rhs;
341
+ }
342
+ if (rhs.type === 'Identifier') {
343
+ var configId_1 = rhs.name;
344
+ var configDeclaration = program.body.find(function (s) {
345
+ return s.type === 'VariableDeclaration' &&
346
+ !!s.declarations.find(function (d) {
347
+ return d.type === 'VariableDeclarator' &&
348
+ d.id.type === 'Identifier' &&
349
+ d.id.name === configId_1;
350
+ });
351
+ });
352
+ var declarator = configDeclaration === null || configDeclaration === void 0 ? void 0 : configDeclaration.declarations.find(function (d) {
353
+ return d.type === 'VariableDeclarator' &&
354
+ d.id.type === 'Identifier' &&
355
+ d.id.name === configId_1;
356
+ });
357
+ return ((_a = declarator === null || declarator === void 0 ? void 0 : declarator.init) === null || _a === void 0 ? void 0 : _a.type) === 'ObjectExpression'
358
+ ? declarator.init
359
+ : undefined;
360
+ }
361
+ return undefined;
362
+ }
363
+ function getCjsModuleExports(program) {
364
+ var moduleExports = program.body.find(function (s) {
365
+ return s.type === 'ExpressionStatement' &&
366
+ s.expression.type === 'AssignmentExpression' &&
367
+ s.expression.left.type === 'MemberExpression' &&
368
+ s.expression.left.object.type === 'Identifier' &&
369
+ s.expression.left.object.name === 'module' &&
370
+ s.expression.left.property.type === 'Identifier' &&
371
+ s.expression.left.property.name === 'exports';
372
+ });
373
+ return moduleExports === null || moduleExports === void 0 ? void 0 : moduleExports.expression;
374
+ }
110
375
  //# sourceMappingURL=webpack.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"webpack.js","sourceRoot":"","sources":["../../../../src/sourcemaps/tools/webpack.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yEAAyE;AACzE,wDAA+C;AAC/C,gDAA0B;AAC1B,uDAKiC;AACjC,yDAA+D;AAO/D,IAAM,cAAc,GAAG,UAAC,OAAgD;IACtE,OAAA,eAAK,CAAC,IAAI,CAAC,YACX,eAAK,CAAC,WAAW,CACjB,oEAAoE,CACrE,sEAIG,eAAK,CAAC,WAAW,CACjB,mEAAmE,CACpE,iCAEG,eAAK,CAAC,WAAW,CAAC,+FAEV,OAAO,CAAC,OAAO,mCACX,OAAO,CAAC,WAAW,gBAC/B,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,yBAAiB,OAAO,CAAC,GAAG,QAAI,CAAC,CAAC,CAAC,EAAE,eAEzD,CAAC,kBAGP,CAAC;AApBA,CAoBA,CAAC;AAEI,IAAM,sBAAsB,GACjC,UAAO,OAAO;;;;;;gBACN,KAAA,4BAAc,CAAA;;oBAClB,WAAW,EAAE,wBAAwB;;gBACnB,KAAA,kCAAmB,CAAA;sBACnC,wBAAwB;gBACxB,qBAAM,IAAA,+BAAiB,GAAE,EAAA;oBAJ7B,qBAAM,mBAEJ,mBAAgB,GAAE,4BAEhB,SAAyB,GAC1B;6BACD,EAAA;;gBANF,SAME,CAAC;gBAEH,iBAAK,CAAC,GAAG,CAAC,IAAI,CACZ,yCAAkC,eAAK,CAAC,IAAI,CAAC,mBAAmB,CAAC,WAAQ,CAC1E,CAAC;gBAEF,8FAA8F;gBAC9F,sCAAsC;gBACtC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;gBAErC,qBAAM,IAAA,8BAAgB,EACpB,IAAA,gBAAM,EAAC;wBACL,OAAO,EAAE,iCAAiC;wBAC1C,OAAO,EAAE,CAAC,EAAE,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;wBACnD,YAAY,EAAE,IAAI;qBACnB,CAAC,CACH,EAAA;;gBAND,SAMC,CAAC;gBAEF,qBAAM,IAAA,4CAA8B,EAAC,OAAO,CAAC,SAAS,CAAC,EAAA;;gBAAvD,SAAuD,CAAC;;;;KACzD,CAAC;AA3BS,QAAA,sBAAsB,0BA2B/B","sourcesContent":["// @ts-ignore - clack is ESM and TS complains about that. It works though\nimport clack, { select } from '@clack/prompts';\nimport chalk from 'chalk';\nimport {\n abortIfCancelled,\n addDotEnvSentryBuildPluginFile,\n getPackageDotJson,\n installPackage,\n} from '../../utils/clack-utils';\nimport { hasPackageInstalled } from '../../utils/package-json';\n\nimport {\n SourceMapUploadToolConfigurationFunction,\n SourceMapUploadToolConfigurationOptions,\n} from './types';\n\nconst getCodeSnippet = (options: SourceMapUploadToolConfigurationOptions) =>\n chalk.gray(`\n${chalk.greenBright(\n 'const { sentryWebpackPlugin } = require(\"@sentry/webpack-plugin\");',\n)}\n\nmodule.exports = {\n // ... other config options\n ${chalk.greenBright(\n 'devtool: \"source-map\", // Source map generation must be turned on',\n )}\n plugins: [\n ${chalk.greenBright(`sentryWebpackPlugin({\n authToken: process.env.SENTRY_AUTH_TOKEN,\n org: \"${options.orgSlug}\",\n project: \"${options.projectSlug}\",${\n options.selfHosted ? `\\n url: \"${options.url}\",` : ''\n } \n })`)},\n ],\n};\n`);\n\nexport const configureWebPackPlugin: SourceMapUploadToolConfigurationFunction =\n async (options) => {\n await installPackage({\n packageName: '@sentry/webpack-plugin',\n alreadyInstalled: hasPackageInstalled(\n '@sentry/webpack-plugin',\n await getPackageDotJson(),\n ),\n });\n\n clack.log.step(\n `Add the following code to your ${chalk.bold('webpack.config.js')} file:`,\n );\n\n // Intentially logging directly to console here so that the code can be copied/pasted directly\n // eslint-disable-next-line no-console\n console.log(getCodeSnippet(options));\n\n await abortIfCancelled(\n select({\n message: 'Did you copy the snippet above?',\n options: [{ label: 'Yes, continue!', value: true }],\n initialValue: true,\n }),\n );\n\n await addDotEnvSentryBuildPluginFile(options.authToken);\n };\n"]}
1
+ {"version":3,"file":"webpack.js","sourceRoot":"","sources":["../../../../src/sourcemaps/tools/webpack.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yCAA6B;AAC7B,qCAAyB;AAEzB,yEAAyE;AACzE,oDAAwC;AACxC,gDAA0B;AAE1B,6CAAiC;AAIjC,mDAAuC;AAEvC,uDAQiC;AACjC,yDAA+D;AAO/D,mDAAmE;AACnE,2CAA0C;AAE1C,IAAM,cAAc,GAAG,UACrB,OAAgD,EAChD,MAAe;IAEf,IAAM,aAAa,GACjB,oEAAoE,CAAC;IACvE,IAAM,2BAA2B,GAC/B,mEAAmE,CAAC;IACtE,IAAM,8BAA8B,GAAG,+FAE3B,OAAO,CAAC,OAAO,mCACX,OAAO,CAAC,WAAW,gBACjC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,yBAAiB,OAAO,CAAC,GAAG,QAAI,CAAC,CAAC,CAAC,EAAE,aAEvD,CAAC;IAEN,IAAM,UAAU,GAAG,MAAM,CAAC,CAAC,CAAC,eAAK,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC;IAC7E,IAAM,wBAAwB,GAAG,MAAM;QACrC,CAAC,CAAC,eAAK,CAAC,WAAW,CAAC,2BAA2B,CAAC;QAChD,CAAC,CAAC,2BAA2B,CAAC;IAChC,IAAM,2BAA2B,GAAG,MAAM;QACxC,CAAC,CAAC,eAAK,CAAC,WAAW,CAAC,8BAA8B,CAAC;QACnD,CAAC,CAAC,8BAA8B,CAAC;IAEnC,IAAM,IAAI,GAAG,uBAAuB,CAClC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MC,CACJ,CAAC;QAEF,IAAM,UAAU,GAAG,iBAAiB,aAAjB,iBAAiB,uBAAjB,iBAAiB,CAAE,YAAY,CAAC,IAAI,CACrD,UAAC,CAAC;YACA,OAAA,CAAC,CAAC,IAAI,KAAK,oBAAoB;gBAC/B,CAAC,CAAC,EAAE,CAAC,IAAI,KAAK,YAAY;gBAC1B,CAAC,CAAC,EAAE,CAAC,IAAI,KAAK,UAAQ;QAFtB,CAEsB,CACzB,CAAC;QAEF,OAAO,CAAA,MAAA,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,IAAI,0CAAE,IAAI,MAAK,kBAAkB;YAClD,CAAC,CAAC,UAAU,CAAC,IAAI;YACjB,CAAC,CAAC,SAAS,CAAC;KACf;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,SAAS,mBAAmB,CAC1B,OAAkB;IAElB,IAAM,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CACrC,UAAC,CAAC;QACA,OAAA,CAAC,CAAC,IAAI,KAAK,qBAAqB;YAChC,CAAC,CAAC,UAAU,CAAC,IAAI,KAAK,sBAAsB;YAC5C,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,KAAK,kBAAkB;YAC7C,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,KAAK,YAAY;YAC9C,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,KAAK,QAAQ;YAC1C,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,KAAK,YAAY;YAChD,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,KAAK,SAAS;IAN7C,CAM6C,CAChD,CAAC;IACF,OAAO,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,UAAoC,CAAC;AAC7D,CAAC","sourcesContent":["import * as path from 'path';\nimport * as fs from 'fs';\n\n// @ts-ignore - clack is ESM and TS complains about that. It works though\nimport * as clack from '@clack/prompts';\nimport chalk from 'chalk';\n\nimport * as recast from 'recast';\nimport x = recast.types;\nimport t = x.namedTypes;\n\nimport * as Sentry from '@sentry/node';\n\nimport {\n abortIfCancelled,\n addDotEnvSentryBuildPluginFile,\n askForToolConfigPath,\n createNewConfigFile,\n getPackageDotJson,\n installPackage,\n showCopyPasteInstructions,\n} from '../../utils/clack-utils';\nimport { hasPackageInstalled } from '../../utils/package-json';\n\nimport {\n SourceMapUploadToolConfigurationFunction,\n SourceMapUploadToolConfigurationOptions,\n} from './types';\n\nimport { findFile, hasSentryContent } from '../../utils/ast-utils';\nimport { debug } from '../../utils/debug';\n\nconst getCodeSnippet = (\n options: SourceMapUploadToolConfigurationOptions,\n colors: boolean,\n) => {\n const rawImportStmt =\n 'const { sentryWebpackPlugin } = require(\"@sentry/webpack-plugin\");';\n const rawGenerateSourceMapsOption =\n 'devtool: \"source-map\", // Source map generation must be turned on';\n const rawSentryWebpackPluginFunction = `sentryWebpackPlugin({\n authToken: process.env.SENTRY_AUTH_TOKEN,\n org: \"${options.orgSlug}\",\n project: \"${options.projectSlug}\",${\n options.selfHosted ? `\\n url: \"${options.url}\",` : ''\n }\n })`;\n\n const importStmt = colors ? chalk.greenBright(rawImportStmt) : rawImportStmt;\n const generateSourceMapsOption = colors\n ? chalk.greenBright(rawGenerateSourceMapsOption)\n : rawGenerateSourceMapsOption;\n const sentryWebpackPluginFunction = colors\n ? chalk.greenBright(rawSentryWebpackPluginFunction)\n : rawSentryWebpackPluginFunction;\n\n const code = getWebpackConfigContent(\n importStmt,\n generateSourceMapsOption,\n sentryWebpackPluginFunction,\n );\n\n return colors ? chalk.gray(code) : code;\n};\n\nconst getWebpackConfigContent = (\n importStmt: string,\n generateSourceMapsOption: string,\n sentryWebpackPluginFunction: string,\n) => `${importStmt}\n\nmodule.exports = {\n // ... other options\n ${generateSourceMapsOption},\n plugins: [\n // Put the Sentry Webpack plugin after all other plugins\n ${sentryWebpackPluginFunction},\n ],\n}\n`;\n\nexport const configureWebPackPlugin: SourceMapUploadToolConfigurationFunction =\n async (options) => {\n await installPackage({\n packageName: '@sentry/webpack-plugin',\n alreadyInstalled: hasPackageInstalled(\n '@sentry/webpack-plugin',\n await getPackageDotJson(),\n ),\n });\n\n const webpackConfigPath =\n findFile(path.resolve(process.cwd(), 'webpack.config')) ??\n (await askForToolConfigPath('Webpack', 'webpack.config.js'));\n\n let successfullyAdded = false;\n if (webpackConfigPath) {\n successfullyAdded = await modifyWebpackConfig(webpackConfigPath, options);\n } else {\n successfullyAdded = await createNewConfigFile(\n path.join(process.cwd(), 'webpack.config.js'),\n getCodeSnippet(options, false),\n 'More information about Webpack configs: https://vitejs.dev/config/',\n );\n Sentry.setTag(\n 'created-new-config',\n successfullyAdded ? 'success' : 'fail',\n );\n }\n\n if (successfullyAdded) {\n clack.log.info(\n `We recommend checking the ${\n webpackConfigPath ? 'modified' : 'added'\n } file after the wizard finished to ensure it works with your build setup.`,\n );\n\n Sentry.setTag('ast-mod', 'success');\n } else {\n Sentry.setTag('ast-mod', 'fail');\n await showCopyPasteInstructions(\n path.basename(webpackConfigPath || 'webpack.config.js'),\n getCodeSnippet(options, true),\n );\n }\n\n await addDotEnvSentryBuildPluginFile(options.authToken);\n };\n\n/**\n * Modifies a webpack config file to enable source map generation and add the Sentry webpack plugin\n * exported only for testing\n */\nexport async function modifyWebpackConfig(\n webpackConfigPath: string,\n options: SourceMapUploadToolConfigurationOptions,\n): Promise<boolean> {\n try {\n const webpackConfig = await fs.promises.readFile(webpackConfigPath, {\n encoding: 'utf-8',\n });\n\n const prettyConfigFilename = chalk.cyan(path.basename(webpackConfigPath));\n\n // no idea why recast returns any here, this is dumb :/\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const program = recast.parse(webpackConfig.toString()).program as t.Program;\n\n if (!(await shouldModifyWebpackConfig(program, prettyConfigFilename))) {\n // Sentry tag is set in shouldModifyWebpackConfig\n return false;\n }\n\n const exportStmt = getCjsModuleExports(program);\n if (!exportStmt) {\n // We only care about CJS at the moment since it's probably the most widely used format for webpack configs.\n debug(`Could not find module.exports = {...} in ${webpackConfigPath}.`);\n Sentry.setTag('ast-mod-fail-reason', 'config-object-not-found');\n return false;\n }\n\n const configObject = getWebpackConfigObject(exportStmt, program);\n\n if (!configObject) {\n debug(`Couldn't find config object in ${webpackConfigPath}`);\n Sentry.setTag('ast-mod-fail-reason', 'config-object-not-found');\n return false;\n }\n\n const enabledSourcemaps = enableSourcemapsGeneration(configObject);\n\n if (enabledSourcemaps) {\n clack.log.success(\n `Enabled source map generation in ${prettyConfigFilename}.`,\n );\n } else {\n clack.log.warn(\n `Couldn't enable source maps generation in ${prettyConfigFilename} Please follow the instructions below.`,\n );\n Sentry.setTag('ast-mod-fail-reason', 'insertion-fail');\n return false;\n }\n\n const addedPlugin = addSentryWebpackPlugin(program, configObject, options);\n if (addedPlugin) {\n clack.log.success(\n `Added Sentry webpack plugin to ${prettyConfigFilename}.`,\n );\n } else {\n clack.log.warn(\n `Couldn't add Sentry webpack plugin to ${prettyConfigFilename}. Please follow the instructions below.`,\n );\n Sentry.setTag('ast-mod-fail-reason', 'insertion-fail');\n return false;\n }\n\n const code = recast.print(program).code;\n await fs.promises.writeFile(webpackConfigPath, code);\n\n return true;\n } catch (e) {\n Sentry.setTag('ast-mod-fail-reason', 'insertion-fail');\n debug(e);\n return false;\n }\n}\n\nasync function shouldModifyWebpackConfig(\n program: t.Program,\n prettyConfigFilename: string,\n) {\n if (hasSentryContent(program)) {\n const shouldContinue = await abortIfCancelled(\n clack.select({\n message: `Seems like ${prettyConfigFilename} already contains Sentry-related code. Should the wizard modify it anyway?`,\n options: [\n {\n label: 'Yes, add the Sentry Webpack plugin',\n value: true,\n },\n {\n label: 'No, show me instructions to manually add the plugin',\n value: false,\n },\n ],\n initialValue: true,\n }),\n );\n\n if (!shouldContinue) {\n Sentry.setTag('ast-mod-fail-reason', 'has-sentry-content');\n return false;\n }\n }\n\n return true;\n}\n\nfunction addSentryWebpackPlugin(\n program: t.Program,\n configObj: t.ObjectExpression,\n options: SourceMapUploadToolConfigurationOptions,\n) {\n const b = addSentryWebpackPluginImport(program);\n\n const sentryPluginCall = b.callExpression(\n b.identifier('sentryWebpackPlugin'),\n [\n b.objectExpression([\n b.objectProperty(\n b.identifier('authToken'),\n b.identifier('process.env.SENTRY_AUTH_TOKEN'),\n ),\n b.objectProperty(b.identifier('org'), b.stringLiteral(options.orgSlug)),\n b.objectProperty(\n b.identifier('project'),\n b.stringLiteral(options.projectSlug),\n ),\n ...(options.selfHosted\n ? [\n b.objectProperty(\n b.identifier('url'),\n b.stringLiteral(options.url),\n ),\n ]\n : []),\n ]),\n ],\n );\n\n const pluginsProp = configObj.properties.find(\n (p): p is t.Property =>\n p.type === 'Property' &&\n p.key.type === 'Identifier' &&\n p.key.name === 'plugins',\n );\n\n if (pluginsProp) {\n if (pluginsProp.value.type === 'ArrayExpression') {\n pluginsProp.value.elements.push(sentryPluginCall);\n } else {\n pluginsProp.value = b.arrayExpression([sentryPluginCall]);\n }\n return true;\n }\n\n configObj.properties.push(\n b.objectProperty(\n b.identifier('plugins'),\n b.arrayExpression([sentryPluginCall]),\n ),\n );\n\n return true;\n}\n\nfunction addSentryWebpackPluginImport(program: t.Program) {\n const b = recast.types.builders;\n\n const sentryPluginRequireStmt = b.variableDeclaration('const', [\n b.variableDeclarator(\n b.objectPattern([\n b.objectProperty.from({\n key: b.identifier('sentryWebpackPlugin'),\n value: b.identifier('sentryWebpackPlugin'),\n shorthand: true,\n }),\n ]),\n b.callExpression(b.identifier('require'), [\n b.stringLiteral('@sentry/webpack-plugin'),\n ]),\n ),\n ]);\n\n program.body.unshift(sentryPluginRequireStmt);\n return b;\n}\n\nfunction enableSourcemapsGeneration(configObj: t.ObjectExpression): boolean {\n const b = recast.types.builders;\n\n const devtoolProp = configObj.properties.find(\n (p): p is t.Property =>\n p.type === 'Property' &&\n p.key.type === 'Identifier' &&\n p.key.name === 'devtool',\n );\n\n if (devtoolProp) {\n // devtool can have quite a lot of source maps values.\n // see: https://webpack.js.org/configuration/devtool/#devtool\n // For Sentry to work best, we should set it to \"source-map\" or \"hidden-source-map\"\n // Heuristic:\n // - all values that contain \"hidden\" will be set to \"hidden-source-map\"\n // - all other values will be set to \"source-map\"\n if (\n (devtoolProp.value.type === 'Literal' ||\n devtoolProp.value.type === 'StringLiteral') &&\n devtoolProp.value.value?.toString().startsWith('hidden-')\n ) {\n devtoolProp.value = b.stringLiteral('hidden-source-map');\n } else {\n devtoolProp.value = b.stringLiteral('source-map');\n }\n return true;\n }\n\n configObj.properties.push(\n b.objectProperty(b.identifier('devtool'), b.stringLiteral('source-map')),\n );\n\n return true;\n}\n\nfunction getWebpackConfigObject(\n moduleExports: t.AssignmentExpression,\n program: t.Program,\n): t.ObjectExpression | undefined {\n const rhs = moduleExports.right;\n if (rhs.type === 'ObjectExpression') {\n return rhs;\n }\n if (rhs.type === 'Identifier') {\n const configId = rhs.name;\n\n const configDeclaration = program.body.find(\n (s): s is t.VariableDeclaration =>\n s.type === 'VariableDeclaration' &&\n !!s.declarations.find(\n (d) =>\n d.type === 'VariableDeclarator' &&\n d.id.type === 'Identifier' &&\n d.id.name === configId,\n ),\n );\n\n const declarator = configDeclaration?.declarations.find(\n (d): d is t.VariableDeclarator =>\n d.type === 'VariableDeclarator' &&\n d.id.type === 'Identifier' &&\n d.id.name === configId,\n );\n\n return declarator?.init?.type === 'ObjectExpression'\n ? declarator.init\n : undefined;\n }\n\n return undefined;\n}\n\nfunction getCjsModuleExports(\n program: t.Program,\n): t.AssignmentExpression | undefined {\n const moduleExports = program.body.find(\n (s): s is t.ExpressionStatement =>\n s.type === 'ExpressionStatement' &&\n s.expression.type === 'AssignmentExpression' &&\n s.expression.left.type === 'MemberExpression' &&\n s.expression.left.object.type === 'Identifier' &&\n s.expression.left.object.name === 'module' &&\n s.expression.left.property.type === 'Identifier' &&\n s.expression.left.property.name === 'exports',\n );\n return moduleExports?.expression as t.AssignmentExpression;\n}\n"]}
@@ -210,7 +210,7 @@ function mergeHooksFile(hooksFile, hookType, dsn) {
210
210
  case 0: return [4 /*yield*/, (0, magicast_1.loadFile)(hooksFile)];
211
211
  case 1:
212
212
  originalHooksMod = _a.sent();
213
- if ((0, ast_utils_1.hasSentryContent)(originalHooksMod)) {
213
+ if ((0, ast_utils_1.hasSentryContent)(originalHooksMod.$ast)) {
214
214
  // We don't want to mess with files that already have Sentry content.
215
215
  // Let's just bail out at this point.
216
216
  prompts_1.default.log.warn("File ".concat(chalk_1.default.cyan(path.basename(hooksFile)), " already contains Sentry code.\nSkipping adding Sentry functionality to."));
@@ -421,7 +421,7 @@ function modifyViteConfig(viteConfigPath, projectInfo) {
421
421
  case 2:
422
422
  _a.trys.push([2, 4, , 6]);
423
423
  viteModule = (0, magicast_1.parseModule)(viteConfigContent);
424
- if ((0, ast_utils_1.hasSentryContent)(viteModule)) {
424
+ if ((0, ast_utils_1.hasSentryContent)(viteModule.$ast)) {
425
425
  prompts_1.default.log.warn("File ".concat(chalk_1.default.cyan(path.basename(viteConfigPath)), " already contains Sentry code.\nSkipping adding Sentry functionality to."));
426
426
  return [2 /*return*/];
427
427
  }
@@ -1 +1 @@
1
- {"version":3,"file":"sdk-setup.js","sourceRoot":"","sources":["../../../src/sveltekit/sdk-setup.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,qCAAyB;AACzB,yCAA6B;AAC7B,uCAA2B;AAC3B,gDAA0B;AAE1B,yEAAyE;AACzE,2DAAmC;AAGnC,4EAA4E;AAC5E,qCAAyE;AACzE,4EAA4E;AAC5E,4CAAiD;AACjD,yCAA6E;AAC7E,oDAA2E;AAC3E,wCAAuC;AACvC,gDAAgE;AAEhE,IAAM,kBAAkB,GAAG,kBAAkB,CAAC;AAsB9C,SAAsB,2BAA2B,CAC/C,WAAwB,EACxB,YAAiC;;;;;;oBAE3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,OAAI,CAAC,CAAC,CAAC,EAAE,yBAEpE,CAAC,mCAIR,CAAC;AAjBA,CAiBA,CAAC;AAEH;;GAEG;AACH,SAAS,yBAAyB,CAAC,mBAA4B;IAC7D,6DAA6D;IAC7D,IAAM,eAAe,qBAAO,mBAAmB,CAAC,IAAI,OAAC,CAAC;IACtD,IAAM,qBAAqB,GAAG,eAAe;SAC1C,OAAO,EAAE;SACT,IAAI,CAAC,UAAC,IAAI,IAAK,OAAA,IAAI,CAAC,IAAI,KAAK,mBAAmB,EAAjC,CAAiC,CAAC,CAAC;IAErD,IAAM,sBAAsB,GAAG,qBAAqB;QAClD,CAAC,CAAC,mBAAmB,CAAC,IAAI,CAAC,OAAO,CAAC,qBAAqB,CAAC,GAAG,CAAC;QAC7D,CAAC,CAAC,CAAC,CAAC;IACN,OAAO,sBAAsB,CAAC;AAChC,CAAC","sourcesContent":["import type { ExportNamedDeclaration, Program } from '@babel/types';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as url from 'url';\nimport chalk from 'chalk';\n\n// @ts-ignore - clack is ESM and TS complains about that. It works though\nimport clack from '@clack/prompts';\n// @ts-ignore - magicast is ESM and TS complains about that. It works though\nimport type { ProxifiedModule } from 'magicast';\n// @ts-ignore - magicast is ESM and TS complains about that. It works though\nimport { builders, generateCode, loadFile, parseModule } from 'magicast';\n// @ts-ignore - magicast is ESM and TS complains about that. It works though\nimport { addVitePlugin } from 'magicast/helpers';\nimport { getClientHooksTemplate, getServerHooksTemplate } from './templates';\nimport { abortIfCancelled, isUsingTypeScript } from '../utils/clack-utils';\nimport { debug } from '../utils/debug';\nimport { findFile, hasSentryContent } from '../utils/ast-utils';\n\nconst SVELTE_CONFIG_FILE = 'svelte.config.js';\n\nexport type PartialSvelteConfig = {\n kit?: {\n files?: {\n hooks?: {\n client?: string;\n server?: string;\n };\n routes?: string;\n };\n };\n};\n\ntype ProjectInfo = {\n dsn: string;\n org: string;\n project: string;\n selfHosted: boolean;\n url: string;\n};\n\nexport async function createOrMergeSvelteKitFiles(\n projectInfo: ProjectInfo,\n svelteConfig: PartialSvelteConfig,\n): Promise<void> {\n const { clientHooksPath, serverHooksPath } = getHooksConfigDirs(svelteConfig);\n\n // full file paths with correct file ending (or undefined if not found)\n const originalClientHooksFile = findFile(clientHooksPath);\n const originalServerHooksFile = findFile(serverHooksPath);\n\n const viteConfig = findFile(path.resolve(process.cwd(), 'vite.config'));\n\n const fileEnding = isUsingTypeScript() ? 'ts' : 'js';\n\n const { dsn } = projectInfo;\n\n if (!originalClientHooksFile) {\n clack.log.info('No client hooks file found, creating a new one.');\n await createNewHooksFile(`${clientHooksPath}.${fileEnding}`, 'client', dsn);\n }\n if (!originalServerHooksFile) {\n clack.log.info('No server hooks file found, creating a new one.');\n await createNewHooksFile(`${serverHooksPath}.${fileEnding}`, 'server', dsn);\n }\n\n if (originalClientHooksFile) {\n await mergeHooksFile(originalClientHooksFile, 'client', dsn);\n }\n if (originalServerHooksFile) {\n await mergeHooksFile(originalServerHooksFile, 'server', dsn);\n }\n\n if (viteConfig) {\n await modifyViteConfig(viteConfig, projectInfo);\n }\n}\n\n/**\n * Attempts to read the svelte.config.js file to find the location of the hooks files.\n * If users specified a custom location, we'll use that. Otherwise, we'll use the default.\n */\nfunction getHooksConfigDirs(svelteConfig: PartialSvelteConfig): {\n clientHooksPath: string;\n serverHooksPath: string;\n} {\n const relativeUserClientHooksPath = svelteConfig?.kit?.files?.hooks?.client;\n const relativeUserServerHooksPath = svelteConfig?.kit?.files?.hooks?.server;\n const userClientHooksPath =\n relativeUserClientHooksPath &&\n path.resolve(process.cwd(), relativeUserClientHooksPath);\n const userServerHooksPath =\n relativeUserServerHooksPath &&\n path.resolve(process.cwd(), relativeUserServerHooksPath);\n\n const defaulHooksDir = path.resolve(process.cwd(), 'src');\n const defaultClientHooksPath = path.resolve(defaulHooksDir, 'hooks.client'); // file ending missing on purpose\n const defaultServerHooksPath = path.resolve(defaulHooksDir, 'hooks.server'); // same here\n\n return {\n clientHooksPath: userClientHooksPath || defaultClientHooksPath,\n serverHooksPath: userServerHooksPath || defaultServerHooksPath,\n };\n}\n\n/**\n * Reads the template, replaces the dsn placeholder with the actual dsn and writes the file to @param hooksFileDest\n */\nasync function createNewHooksFile(\n hooksFileDest: string,\n hooktype: 'client' | 'server',\n dsn: string,\n): Promise<void> {\n const filledTemplate =\n hooktype === 'client'\n ? getClientHooksTemplate(dsn)\n : getServerHooksTemplate(dsn);\n\n await fs.promises.mkdir(path.dirname(hooksFileDest), { recursive: true });\n await fs.promises.writeFile(hooksFileDest, filledTemplate);\n\n clack.log.success(`Created ${hooksFileDest}`);\n}\n\n/**\n * Merges the users' hooks file with Sentry-related code.\n *\n * Both hooks:\n * - add import * as Sentry\n * - add Sentry.init\n * - add handleError hook wrapper\n *\n * Additionally in Server hook:\n * - add handle hook handler\n */\nasync function mergeHooksFile(\n hooksFile: string,\n hookType: 'client' | 'server',\n dsn: string,\n): Promise<void> {\n const originalHooksMod = await loadFile(hooksFile);\n if (hasSentryContent(originalHooksMod)) {\n // We don't want to mess with files that already have Sentry content.\n // Let's just bail out at this point.\n clack.log.warn(\n `File ${chalk.cyan(\n path.basename(hooksFile),\n )} already contains Sentry code.\nSkipping adding Sentry functionality to.`,\n );\n return;\n }\n\n originalHooksMod.imports.$add({\n from: '@sentry/sveltekit',\n imported: '*',\n local: 'Sentry',\n });\n\n if (hookType === 'client') {\n insertClientInitCall(dsn, originalHooksMod);\n } else {\n insertServerInitCall(dsn, originalHooksMod);\n }\n\n wrapHandleError(originalHooksMod);\n\n if (hookType === 'server') {\n wrapHandle(originalHooksMod);\n }\n\n const modifiedCode = originalHooksMod.generate().code;\n\n await fs.promises.writeFile(hooksFile, modifiedCode);\n\n clack.log.success(`Added Sentry code to ${hooksFile}`);\n}\n\nfunction insertClientInitCall(\n dsn: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n originalHooksMod: ProxifiedModule<any>,\n): void {\n const initCallComment = `\n // If you don't want to use Session Replay, remove the \\`Replay\\` integration, \n // \\`replaysSessionSampleRate\\` and \\`replaysOnErrorSampleRate\\` options.`;\n\n // This assignment of any values is fine because we're just creating a function call in magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const initCall = builders.functionCall('Sentry.init', {\n dsn,\n tracesSampleRate: 1.0,\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0,\n integrations: [builders.newExpression('Sentry.Replay')],\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const initCallWithComment = builders.raw(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n `${initCallComment}\\n${generateCode(initCall).code}`,\n );\n\n const originalHooksModAST = originalHooksMod.$ast as Program;\n\n const initCallInsertionIndex = getInitCallInsertionIndex(originalHooksModAST);\n\n originalHooksModAST.body.splice(\n initCallInsertionIndex,\n 0,\n // @ts-ignore - string works here because the AST is proxified by magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n generateCode(initCallWithComment).code,\n );\n}\n\nfunction insertServerInitCall(\n dsn: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n originalHooksMod: ProxifiedModule<any>,\n): void {\n // This assignment of any values is fine because we're just creating a function call in magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const initCall = builders.functionCall('Sentry.init', {\n dsn,\n tracesSampleRate: 1.0,\n });\n\n const originalHooksModAST = originalHooksMod.$ast as Program;\n\n const initCallInsertionIndex = getInitCallInsertionIndex(originalHooksModAST);\n\n originalHooksModAST.body.splice(\n initCallInsertionIndex,\n 0,\n // @ts-ignore - string works here because the AST is proxified by magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n generateCode(initCall).code,\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction wrapHandleError(mod: ProxifiedModule<any>): void {\n const modAst = mod.exports.$ast as Program;\n const namedExports = modAst.body.filter(\n (node) => node.type === 'ExportNamedDeclaration',\n ) as ExportNamedDeclaration[];\n\n let foundHandleError = false;\n\n namedExports.forEach((modExport) => {\n const declaration = modExport.declaration;\n if (!declaration) {\n return;\n }\n if (declaration.type === 'FunctionDeclaration') {\n if (!declaration.id || declaration.id.name !== 'handleError') {\n return;\n }\n foundHandleError = true;\n const userCode = generateCode(declaration).code;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handleError = builders.raw(\n `Sentry.handleErrorWithSentry(${userCode.replace(\n 'handleError',\n '_handleError',\n )})`,\n );\n // because magicast doesn't overwrite the original function export, we need to remove it manually\n modAst.body = modAst.body.filter((node) => node !== modExport);\n } else if (declaration.type === 'VariableDeclaration') {\n const declarations = declaration.declarations;\n declarations.forEach((declaration) => {\n // @ts-ignore - id should always have a name in this case\n if (!declaration.id || declaration.id.name !== 'handleError') {\n return;\n }\n foundHandleError = true;\n const userCode = declaration.init;\n const stringifiedUserCode = userCode ? generateCode(userCode).code : '';\n // @ts-ignore - we can just place a string here, magicast will convert it to a node\n declaration.init = `Sentry.handleErrorWithSentry(${stringifiedUserCode})`;\n });\n }\n });\n\n if (!foundHandleError) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handleError = builders.functionCall(\n 'Sentry.handleErrorWithSentry',\n );\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction wrapHandle(mod: ProxifiedModule<any>): void {\n const modAst = mod.exports.$ast as Program;\n const namedExports = modAst.body.filter(\n (node) => node.type === 'ExportNamedDeclaration',\n ) as ExportNamedDeclaration[];\n\n let foundHandle = false;\n\n namedExports.forEach((modExport) => {\n const declaration = modExport.declaration;\n if (!declaration) {\n return;\n }\n if (declaration.type === 'FunctionDeclaration') {\n if (!declaration.id || declaration.id.name !== 'handle') {\n return;\n }\n foundHandle = true;\n const userCode = generateCode(declaration).code;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handle = builders.raw(\n `sequence(Sentry.sentryHandle(), ${userCode.replace(\n 'handle',\n '_handle',\n )})`,\n );\n // because of an issue with magicast, we need to remove the original export\n modAst.body = modAst.body.filter((node) => node !== modExport);\n } else if (declaration.type === 'VariableDeclaration') {\n const declarations = declaration.declarations;\n declarations.forEach((declaration) => {\n // @ts-ignore - id should always have a name in this case\n if (!declaration.id || declaration.id.name !== 'handle') {\n return;\n }\n const userCode = declaration.init;\n const stringifiedUserCode = userCode ? generateCode(userCode).code : '';\n // @ts-ignore - we can just place a string here, magicast will convert it to a node\n declaration.init = `sequence(Sentry.sentryHandle(), ${stringifiedUserCode})`;\n foundHandle = true;\n });\n }\n });\n\n if (!foundHandle) {\n // can't use builders.functionCall here because it doesn't yet\n // support member expressions (Sentry.sentryHandle()) in args\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handle = builders.raw('sequence(Sentry.sentryHandle())');\n }\n\n try {\n mod.imports.$add({\n from: '@sveltejs/kit/hooks',\n imported: 'sequence',\n local: 'sequence',\n });\n } catch (_) {\n // It's possible sequence is already imported. in this case, magicast throws but that's fine.\n }\n}\n\nexport async function loadSvelteConfig(): Promise<PartialSvelteConfig> {\n const configFilePath = path.join(process.cwd(), SVELTE_CONFIG_FILE);\n\n try {\n if (!fs.existsSync(configFilePath)) {\n return {};\n }\n\n const configUrl = url.pathToFileURL(configFilePath).href;\n const svelteConfigModule = (await import(configUrl)) as {\n default: PartialSvelteConfig;\n };\n\n return svelteConfigModule?.default || {};\n } catch (e: unknown) {\n clack.log.error(`Couldn't load ${SVELTE_CONFIG_FILE}.\nPlease make sure, you're running this wizard with Node 16 or newer`);\n clack.log.info(\n chalk.dim(\n typeof e === 'object' && e != null && 'toString' in e\n ? e.toString()\n : typeof e === 'string'\n ? e\n : 'Unknown error',\n ),\n );\n\n return {};\n }\n}\n\nasync function modifyViteConfig(\n viteConfigPath: string,\n projectInfo: ProjectInfo,\n): Promise<void> {\n const viteConfigContent = (\n await fs.promises.readFile(viteConfigPath, 'utf-8')\n ).toString();\n\n const { org, project, url, selfHosted } = projectInfo;\n\n try {\n const viteModule = parseModule(viteConfigContent);\n\n if (hasSentryContent(viteModule)) {\n clack.log.warn(\n `File ${chalk.cyan(\n path.basename(viteConfigPath),\n )} already contains Sentry code.\nSkipping adding Sentry functionality to.`,\n );\n return;\n }\n\n addVitePlugin(viteModule, {\n imported: 'sentrySvelteKit',\n from: '@sentry/sveltekit',\n constructor: 'sentrySvelteKit',\n options: {\n sourceMapsUploadOptions: {\n org,\n project,\n ...(selfHosted && { url }),\n },\n },\n index: 0,\n });\n\n const code = generateCode(viteModule.$ast).code;\n\n await fs.promises.writeFile(viteConfigPath, code);\n } catch (e) {\n debug(e);\n await showFallbackViteCopyPasteSnippet(\n viteConfigPath,\n getViteConfigCodeSnippet(org, project, selfHosted, url),\n );\n }\n}\n\nasync function showFallbackViteCopyPasteSnippet(\n viteConfigPath: string,\n codeSnippet: string,\n) {\n const viteConfigFilename = path.basename(viteConfigPath);\n\n clack.log.warning(\n `Couldn't automatically modify your ${chalk.cyan(viteConfigFilename)}\n${chalk.dim(`This sometimes happens when we encounter more complex vite configs.\nIt may not seem like it but sometimes our magical powers are limited ;)`)}`,\n );\n\n clack.log.info(\"But don't worry - it's super easy to do this yourself!\");\n\n clack.log.step(\n `Add the following code to your ${chalk.cyan(viteConfigFilename)}:`,\n );\n\n // Intentionally logging to console here for easier copy/pasting\n // eslint-disable-next-line no-console\n console.log(codeSnippet);\n\n await abortIfCancelled(\n clack.select({\n message: 'Did you copy the snippet above?',\n options: [\n { label: 'Yes!', value: true, hint: \"Great, that's already it!\" },\n ],\n initialValue: true,\n }),\n );\n}\n\nconst getViteConfigCodeSnippet = (\n org: string,\n project: string,\n selfHosted: boolean,\n url: string,\n) =>\n chalk.gray(`\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\n${chalk.greenBright(\"import { sentrySvelteKit } from '@sentry/sveltekit'\")}\n\nexport default defineConfig({\n plugins: [\n // Make sure \\`sentrySvelteKit\\` is registered before \\`sveltekit\\`\n ${chalk.greenBright(`sentrySvelteKit({\n sourceMapsUploadOptions: {\n org: '${org}',\n project: '${project}',${selfHosted ? `\\n url: '${url}',` : ''}\n } \n }),`)}\n sveltekit(),\n ]\n});\n`);\n\n/**\n * We want to insert the init call on top of the file but after all import statements\n */\nfunction getInitCallInsertionIndex(originalHooksModAST: Program): number {\n // We need to deep-copy here because reverse mutates in place\n const copiedBodyNodes = [...originalHooksModAST.body];\n const lastImportDeclaration = copiedBodyNodes\n .reverse()\n .find((node) => node.type === 'ImportDeclaration');\n\n const initCallInsertionIndex = lastImportDeclaration\n ? originalHooksModAST.body.indexOf(lastImportDeclaration) + 1\n : 0;\n return initCallInsertionIndex;\n}\n"]}
1
+ {"version":3,"file":"sdk-setup.js","sourceRoot":"","sources":["../../../src/sveltekit/sdk-setup.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,qCAAyB;AACzB,yCAA6B;AAC7B,uCAA2B;AAC3B,gDAA0B;AAE1B,yEAAyE;AACzE,2DAAmC;AAGnC,4EAA4E;AAC5E,qCAAyE;AACzE,4EAA4E;AAC5E,4CAAiD;AACjD,yCAA6E;AAC7E,oDAA2E;AAC3E,wCAAuC;AACvC,gDAAgE;AAMhE,IAAM,kBAAkB,GAAG,kBAAkB,CAAC;AAsB9C,SAAsB,2BAA2B,CAC/C,WAAwB,EACxB,YAAiC;;;;;;oBAE3B,KAAuC,kBAAkB,CAAC,YAAY,CAAC,EAArE,eAAe,qBAAA,EAAE,eAAe,qBAAA,CAAsC;oBAGxE,uBAAuB,GAAG,IAAA,oBAAQ,EAAC,eAAe,CAAC,CAAC;oBACpD,uBAAuB,GAAG,IAAA,oBAAQ,EAAC,eAAe,CAAC,CAAC;oBAEpD,UAAU,GAAG,IAAA,oBAAQ,EAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE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AAC,IAAI,IAAK,OAAA,IAAI,CAAC,IAAI,KAAK,mBAAmB,EAAjC,CAAiC,CAAC,CAAC;IAErD,IAAM,sBAAsB,GAAG,qBAAqB;QAClD,CAAC,CAAC,mBAAmB,CAAC,IAAI,CAAC,OAAO,CAAC,qBAAqB,CAAC,GAAG,CAAC;QAC7D,CAAC,CAAC,CAAC,CAAC;IACN,OAAO,sBAAsB,CAAC;AAChC,CAAC","sourcesContent":["import type { ExportNamedDeclaration, Program } from '@babel/types';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as url from 'url';\nimport chalk from 'chalk';\n\n// @ts-ignore - clack is ESM and TS complains about that. It works though\nimport clack from '@clack/prompts';\n// @ts-ignore - magicast is ESM and TS complains about that. It works though\nimport type { ProxifiedModule } from 'magicast';\n// @ts-ignore - magicast is ESM and TS complains about that. It works though\nimport { builders, generateCode, loadFile, parseModule } from 'magicast';\n// @ts-ignore - magicast is ESM and TS complains about that. It works though\nimport { addVitePlugin } from 'magicast/helpers';\nimport { getClientHooksTemplate, getServerHooksTemplate } from './templates';\nimport { abortIfCancelled, isUsingTypeScript } from '../utils/clack-utils';\nimport { debug } from '../utils/debug';\nimport { findFile, hasSentryContent } from '../utils/ast-utils';\n\nimport * as recast from 'recast';\nimport x = recast.types;\nimport t = x.namedTypes;\n\nconst SVELTE_CONFIG_FILE = 'svelte.config.js';\n\nexport type PartialSvelteConfig = {\n kit?: {\n files?: {\n hooks?: {\n client?: string;\n server?: string;\n };\n routes?: string;\n };\n };\n};\n\ntype ProjectInfo = {\n dsn: string;\n org: string;\n project: string;\n selfHosted: boolean;\n url: string;\n};\n\nexport async function createOrMergeSvelteKitFiles(\n projectInfo: ProjectInfo,\n svelteConfig: PartialSvelteConfig,\n): Promise<void> {\n const { clientHooksPath, serverHooksPath } = getHooksConfigDirs(svelteConfig);\n\n // full file paths with correct file ending (or undefined if not found)\n const originalClientHooksFile = findFile(clientHooksPath);\n const originalServerHooksFile = findFile(serverHooksPath);\n\n const viteConfig = findFile(path.resolve(process.cwd(), 'vite.config'));\n\n const fileEnding = isUsingTypeScript() ? 'ts' : 'js';\n\n const { dsn } = projectInfo;\n\n if (!originalClientHooksFile) {\n clack.log.info('No client hooks file found, creating a new one.');\n await createNewHooksFile(`${clientHooksPath}.${fileEnding}`, 'client', dsn);\n }\n if (!originalServerHooksFile) {\n clack.log.info('No server hooks file found, creating a new one.');\n await createNewHooksFile(`${serverHooksPath}.${fileEnding}`, 'server', dsn);\n }\n\n if (originalClientHooksFile) {\n await mergeHooksFile(originalClientHooksFile, 'client', dsn);\n }\n if (originalServerHooksFile) {\n await mergeHooksFile(originalServerHooksFile, 'server', dsn);\n }\n\n if (viteConfig) {\n await modifyViteConfig(viteConfig, projectInfo);\n }\n}\n\n/**\n * Attempts to read the svelte.config.js file to find the location of the hooks files.\n * If users specified a custom location, we'll use that. Otherwise, we'll use the default.\n */\nfunction getHooksConfigDirs(svelteConfig: PartialSvelteConfig): {\n clientHooksPath: string;\n serverHooksPath: string;\n} {\n const relativeUserClientHooksPath = svelteConfig?.kit?.files?.hooks?.client;\n const relativeUserServerHooksPath = svelteConfig?.kit?.files?.hooks?.server;\n const userClientHooksPath =\n relativeUserClientHooksPath &&\n path.resolve(process.cwd(), relativeUserClientHooksPath);\n const userServerHooksPath =\n relativeUserServerHooksPath &&\n path.resolve(process.cwd(), relativeUserServerHooksPath);\n\n const defaulHooksDir = path.resolve(process.cwd(), 'src');\n const defaultClientHooksPath = path.resolve(defaulHooksDir, 'hooks.client'); // file ending missing on purpose\n const defaultServerHooksPath = path.resolve(defaulHooksDir, 'hooks.server'); // same here\n\n return {\n clientHooksPath: userClientHooksPath || defaultClientHooksPath,\n serverHooksPath: userServerHooksPath || defaultServerHooksPath,\n };\n}\n\n/**\n * Reads the template, replaces the dsn placeholder with the actual dsn and writes the file to @param hooksFileDest\n */\nasync function createNewHooksFile(\n hooksFileDest: string,\n hooktype: 'client' | 'server',\n dsn: string,\n): Promise<void> {\n const filledTemplate =\n hooktype === 'client'\n ? getClientHooksTemplate(dsn)\n : getServerHooksTemplate(dsn);\n\n await fs.promises.mkdir(path.dirname(hooksFileDest), { recursive: true });\n await fs.promises.writeFile(hooksFileDest, filledTemplate);\n\n clack.log.success(`Created ${hooksFileDest}`);\n}\n\n/**\n * Merges the users' hooks file with Sentry-related code.\n *\n * Both hooks:\n * - add import * as Sentry\n * - add Sentry.init\n * - add handleError hook wrapper\n *\n * Additionally in Server hook:\n * - add handle hook handler\n */\nasync function mergeHooksFile(\n hooksFile: string,\n hookType: 'client' | 'server',\n dsn: string,\n): Promise<void> {\n const originalHooksMod = await loadFile(hooksFile);\n if (hasSentryContent(originalHooksMod.$ast as t.Program)) {\n // We don't want to mess with files that already have Sentry content.\n // Let's just bail out at this point.\n clack.log.warn(\n `File ${chalk.cyan(\n path.basename(hooksFile),\n )} already contains Sentry code.\nSkipping adding Sentry functionality to.`,\n );\n return;\n }\n\n originalHooksMod.imports.$add({\n from: '@sentry/sveltekit',\n imported: '*',\n local: 'Sentry',\n });\n\n if (hookType === 'client') {\n insertClientInitCall(dsn, originalHooksMod);\n } else {\n insertServerInitCall(dsn, originalHooksMod);\n }\n\n wrapHandleError(originalHooksMod);\n\n if (hookType === 'server') {\n wrapHandle(originalHooksMod);\n }\n\n const modifiedCode = originalHooksMod.generate().code;\n\n await fs.promises.writeFile(hooksFile, modifiedCode);\n\n clack.log.success(`Added Sentry code to ${hooksFile}`);\n}\n\nfunction insertClientInitCall(\n dsn: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n originalHooksMod: ProxifiedModule<any>,\n): void {\n const initCallComment = `\n // If you don't want to use Session Replay, remove the \\`Replay\\` integration, \n // \\`replaysSessionSampleRate\\` and \\`replaysOnErrorSampleRate\\` options.`;\n\n // This assignment of any values is fine because we're just creating a function call in magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const initCall = builders.functionCall('Sentry.init', {\n dsn,\n tracesSampleRate: 1.0,\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0,\n integrations: [builders.newExpression('Sentry.Replay')],\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const initCallWithComment = builders.raw(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n `${initCallComment}\\n${generateCode(initCall).code}`,\n );\n\n const originalHooksModAST = originalHooksMod.$ast as Program;\n\n const initCallInsertionIndex = getInitCallInsertionIndex(originalHooksModAST);\n\n originalHooksModAST.body.splice(\n initCallInsertionIndex,\n 0,\n // @ts-ignore - string works here because the AST is proxified by magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n generateCode(initCallWithComment).code,\n );\n}\n\nfunction insertServerInitCall(\n dsn: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n originalHooksMod: ProxifiedModule<any>,\n): void {\n // This assignment of any values is fine because we're just creating a function call in magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const initCall = builders.functionCall('Sentry.init', {\n dsn,\n tracesSampleRate: 1.0,\n });\n\n const originalHooksModAST = originalHooksMod.$ast as Program;\n\n const initCallInsertionIndex = getInitCallInsertionIndex(originalHooksModAST);\n\n originalHooksModAST.body.splice(\n initCallInsertionIndex,\n 0,\n // @ts-ignore - string works here because the AST is proxified by magicast\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n generateCode(initCall).code,\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction wrapHandleError(mod: ProxifiedModule<any>): void {\n const modAst = mod.exports.$ast as Program;\n const namedExports = modAst.body.filter(\n (node) => node.type === 'ExportNamedDeclaration',\n ) as ExportNamedDeclaration[];\n\n let foundHandleError = false;\n\n namedExports.forEach((modExport) => {\n const declaration = modExport.declaration;\n if (!declaration) {\n return;\n }\n if (declaration.type === 'FunctionDeclaration') {\n if (!declaration.id || declaration.id.name !== 'handleError') {\n return;\n }\n foundHandleError = true;\n const userCode = generateCode(declaration).code;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handleError = builders.raw(\n `Sentry.handleErrorWithSentry(${userCode.replace(\n 'handleError',\n '_handleError',\n )})`,\n );\n // because magicast doesn't overwrite the original function export, we need to remove it manually\n modAst.body = modAst.body.filter((node) => node !== modExport);\n } else if (declaration.type === 'VariableDeclaration') {\n const declarations = declaration.declarations;\n declarations.forEach((declaration) => {\n // @ts-ignore - id should always have a name in this case\n if (!declaration.id || declaration.id.name !== 'handleError') {\n return;\n }\n foundHandleError = true;\n const userCode = declaration.init;\n const stringifiedUserCode = userCode ? generateCode(userCode).code : '';\n // @ts-ignore - we can just place a string here, magicast will convert it to a node\n declaration.init = `Sentry.handleErrorWithSentry(${stringifiedUserCode})`;\n });\n }\n });\n\n if (!foundHandleError) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handleError = builders.functionCall(\n 'Sentry.handleErrorWithSentry',\n );\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction wrapHandle(mod: ProxifiedModule<any>): void {\n const modAst = mod.exports.$ast as Program;\n const namedExports = modAst.body.filter(\n (node) => node.type === 'ExportNamedDeclaration',\n ) as ExportNamedDeclaration[];\n\n let foundHandle = false;\n\n namedExports.forEach((modExport) => {\n const declaration = modExport.declaration;\n if (!declaration) {\n return;\n }\n if (declaration.type === 'FunctionDeclaration') {\n if (!declaration.id || declaration.id.name !== 'handle') {\n return;\n }\n foundHandle = true;\n const userCode = generateCode(declaration).code;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handle = builders.raw(\n `sequence(Sentry.sentryHandle(), ${userCode.replace(\n 'handle',\n '_handle',\n )})`,\n );\n // because of an issue with magicast, we need to remove the original export\n modAst.body = modAst.body.filter((node) => node !== modExport);\n } else if (declaration.type === 'VariableDeclaration') {\n const declarations = declaration.declarations;\n declarations.forEach((declaration) => {\n // @ts-ignore - id should always have a name in this case\n if (!declaration.id || declaration.id.name !== 'handle') {\n return;\n }\n const userCode = declaration.init;\n const stringifiedUserCode = userCode ? generateCode(userCode).code : '';\n // @ts-ignore - we can just place a string here, magicast will convert it to a node\n declaration.init = `sequence(Sentry.sentryHandle(), ${stringifiedUserCode})`;\n foundHandle = true;\n });\n }\n });\n\n if (!foundHandle) {\n // can't use builders.functionCall here because it doesn't yet\n // support member expressions (Sentry.sentryHandle()) in args\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n mod.exports.handle = builders.raw('sequence(Sentry.sentryHandle())');\n }\n\n try {\n mod.imports.$add({\n from: '@sveltejs/kit/hooks',\n imported: 'sequence',\n local: 'sequence',\n });\n } catch (_) {\n // It's possible sequence is already imported. in this case, magicast throws but that's fine.\n }\n}\n\nexport async function loadSvelteConfig(): Promise<PartialSvelteConfig> {\n const configFilePath = path.join(process.cwd(), SVELTE_CONFIG_FILE);\n\n try {\n if (!fs.existsSync(configFilePath)) {\n return {};\n }\n\n const configUrl = url.pathToFileURL(configFilePath).href;\n const svelteConfigModule = (await import(configUrl)) as {\n default: PartialSvelteConfig;\n };\n\n return svelteConfigModule?.default || {};\n } catch (e: unknown) {\n clack.log.error(`Couldn't load ${SVELTE_CONFIG_FILE}.\nPlease make sure, you're running this wizard with Node 16 or newer`);\n clack.log.info(\n chalk.dim(\n typeof e === 'object' && e != null && 'toString' in e\n ? e.toString()\n : typeof e === 'string'\n ? e\n : 'Unknown error',\n ),\n );\n\n return {};\n }\n}\n\nasync function modifyViteConfig(\n viteConfigPath: string,\n projectInfo: ProjectInfo,\n): Promise<void> {\n const viteConfigContent = (\n await fs.promises.readFile(viteConfigPath, 'utf-8')\n ).toString();\n\n const { org, project, url, selfHosted } = projectInfo;\n\n try {\n const viteModule = parseModule(viteConfigContent);\n\n if (hasSentryContent(viteModule.$ast as t.Program)) {\n clack.log.warn(\n `File ${chalk.cyan(\n path.basename(viteConfigPath),\n )} already contains Sentry code.\nSkipping adding Sentry functionality to.`,\n );\n return;\n }\n\n addVitePlugin(viteModule, {\n imported: 'sentrySvelteKit',\n from: '@sentry/sveltekit',\n constructor: 'sentrySvelteKit',\n options: {\n sourceMapsUploadOptions: {\n org,\n project,\n ...(selfHosted && { url }),\n },\n },\n index: 0,\n });\n\n const code = generateCode(viteModule.$ast).code;\n\n await fs.promises.writeFile(viteConfigPath, code);\n } catch (e) {\n debug(e);\n await showFallbackViteCopyPasteSnippet(\n viteConfigPath,\n getViteConfigCodeSnippet(org, project, selfHosted, url),\n );\n }\n}\n\nasync function showFallbackViteCopyPasteSnippet(\n viteConfigPath: string,\n codeSnippet: string,\n) {\n const viteConfigFilename = path.basename(viteConfigPath);\n\n clack.log.warning(\n `Couldn't automatically modify your ${chalk.cyan(viteConfigFilename)}\n${chalk.dim(`This sometimes happens when we encounter more complex vite configs.\nIt may not seem like it but sometimes our magical powers are limited ;)`)}`,\n );\n\n clack.log.info(\"But don't worry - it's super easy to do this yourself!\");\n\n clack.log.step(\n `Add the following code to your ${chalk.cyan(viteConfigFilename)}:`,\n );\n\n // Intentionally logging to console here for easier copy/pasting\n // eslint-disable-next-line no-console\n console.log(codeSnippet);\n\n await abortIfCancelled(\n clack.select({\n message: 'Did you copy the snippet above?',\n options: [\n { label: 'Yes!', value: true, hint: \"Great, that's already it!\" },\n ],\n initialValue: true,\n }),\n );\n}\n\nconst getViteConfigCodeSnippet = (\n org: string,\n project: string,\n selfHosted: boolean,\n url: string,\n) =>\n chalk.gray(`\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\n${chalk.greenBright(\"import { sentrySvelteKit } from '@sentry/sveltekit'\")}\n\nexport default defineConfig({\n plugins: [\n // Make sure \\`sentrySvelteKit\\` is registered before \\`sveltekit\\`\n ${chalk.greenBright(`sentrySvelteKit({\n sourceMapsUploadOptions: {\n org: '${org}',\n project: '${project}',${selfHosted ? `\\n url: '${url}',` : ''}\n } \n }),`)}\n sveltekit(),\n ]\n});\n`);\n\n/**\n * We want to insert the init call on top of the file but after all import statements\n */\nfunction getInitCallInsertionIndex(originalHooksModAST: Program): number {\n // We need to deep-copy here because reverse mutates in place\n const copiedBodyNodes = [...originalHooksModAST.body];\n const lastImportDeclaration = copiedBodyNodes\n .reverse()\n .find((node) => node.type === 'ImportDeclaration');\n\n const initCallInsertionIndex = lastImportDeclaration\n ? originalHooksModAST.body.indexOf(lastImportDeclaration) + 1\n : 0;\n return initCallInsertionIndex;\n}\n"]}
@@ -1,8 +1,12 @@
1
- import { ProxifiedModule } from 'magicast';
1
+ import * as recast from 'recast';
2
+ import x = recast.types;
3
+ import t = x.namedTypes;
2
4
  /**
3
5
  * Checks if a file where we don't know its concrete file type yet exists
4
6
  * and returns the full path to the file with the correct file type.
5
7
  */
6
8
  export declare function findFile(filePath: string, fileTypes?: string[]): string | undefined;
7
- /** Checks if a Sentry package is already mentioned in the file */
8
- export declare function hasSentryContent(mod: ProxifiedModule<object>): boolean;
9
+ /**
10
+ * checks for require('@sentry/*') syntax
11
+ */
12
+ export declare function hasSentryContent(program: t.Program): boolean;
@@ -25,21 +25,36 @@ var __importStar = (this && this.__importStar) || function (mod) {
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.hasSentryContent = exports.findFile = void 0;
27
27
  var fs = __importStar(require("fs"));
28
+ var recast = __importStar(require("recast"));
28
29
  /**
29
30
  * Checks if a file where we don't know its concrete file type yet exists
30
31
  * and returns the full path to the file with the correct file type.
31
32
  */
32
33
  function findFile(filePath, fileTypes) {
33
- if (fileTypes === void 0) { fileTypes = ['.js', '.ts', '.mjs']; }
34
+ if (fileTypes === void 0) { fileTypes = ['.js', '.ts', '.mjs', '.cjs']; }
34
35
  return fileTypes
35
36
  .map(function (type) { return "".concat(filePath).concat(type); })
36
37
  .find(function (file) { return fs.existsSync(file); });
37
38
  }
38
39
  exports.findFile = findFile;
39
- /** Checks if a Sentry package is already mentioned in the file */
40
- function hasSentryContent(mod) {
41
- var imports = mod.imports.$items.map(function (i) { return i.from; });
42
- return !!imports.find(function (i) { return i.startsWith('@sentry/'); });
40
+ /**
41
+ * checks for require('@sentry/*') syntax
42
+ */
43
+ function hasSentryContent(program) {
44
+ var foundSentry = false;
45
+ recast.visit(program, {
46
+ visitStringLiteral: function (path) {
47
+ foundSentry = foundSentry || path.node.value.startsWith('@sentry/');
48
+ this.traverse(path);
49
+ },
50
+ visitLiteral: function (path) {
51
+ var _a;
52
+ foundSentry =
53
+ foundSentry || ((_a = path.node.value) === null || _a === void 0 ? void 0 : _a.toString().startsWith('@sentry/'));
54
+ this.traverse(path);
55
+ },
56
+ });
57
+ return !!foundSentry;
43
58
  }
44
59
  exports.hasSentryContent = hasSentryContent;
45
60
  //# sourceMappingURL=ast-utils.js.map