@sentry/wizard 3.16.5 → 3.17.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.
- package/CHANGELOG.md +7 -0
- package/dist/package.json +2 -2
- package/dist/src/apple/cocoapod.js +2 -0
- package/dist/src/apple/cocoapod.js.map +1 -1
- package/dist/src/react-native/metro.d.ts +13 -0
- package/dist/src/react-native/metro.js +398 -0
- package/dist/src/react-native/metro.js.map +1 -0
- package/dist/src/react-native/react-native-wizard.d.ts +2 -0
- package/dist/src/react-native/react-native-wizard.js +139 -38
- package/dist/src/react-native/react-native-wizard.js.map +1 -1
- package/dist/src/react-native/uninstall.js +4 -0
- package/dist/src/react-native/uninstall.js.map +1 -1
- package/dist/src/react-native/xcode.d.ts +7 -3
- package/dist/src/react-native/xcode.js +43 -11
- package/dist/src/react-native/xcode.js.map +1 -1
- package/dist/src/remix/remix-wizard.js +80 -37
- package/dist/src/remix/remix-wizard.js.map +1 -1
- package/dist/src/remix/sdk-setup.d.ts +1 -0
- package/dist/src/remix/sdk-setup.js +21 -1
- package/dist/src/remix/sdk-setup.js.map +1 -1
- package/dist/src/utils/ast-utils.d.ts +14 -0
- package/dist/src/utils/ast-utils.js +49 -1
- package/dist/src/utils/ast-utils.js.map +1 -1
- package/dist/test/react-native/metro.test.d.ts +1 -0
- package/dist/test/react-native/metro.test.js +125 -0
- package/dist/test/react-native/metro.test.js.map +1 -0
- package/dist/test/react-native/xcode.test.js +40 -2
- package/dist/test/react-native/xcode.test.js.map +1 -1
- package/package.json +2 -2
- package/src/apple/cocoapod.ts +2 -0
- package/src/react-native/metro.ts +409 -0
- package/src/react-native/react-native-wizard.ts +103 -7
- package/src/react-native/uninstall.ts +3 -0
- package/src/react-native/xcode.ts +70 -12
- package/src/remix/remix-wizard.ts +51 -15
- package/src/remix/sdk-setup.ts +31 -0
- package/src/utils/ast-utils.ts +52 -0
- package/test/react-native/metro.test.ts +283 -0
- package/test/react-native/xcode.test.ts +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AAED,8DAA8D;AAC9D,SAAgB,iBAAiB,CAAC,gBAAwB,EAAE,YAAiB;IAC3E,IAAM,UAAU,GAAG,YAAY,CAAC,SAAS,EAAE,CAAC;IAC5C,IAAM,cAAc,GAAG,EAAE,CAAC,YAAY,CAAC,gBAAgB,EAAE,OAAO,CAAC,CAAC;IAClE,IAAI,UAAU,KAAK,cAAc,EAAE;QACjC,OAAO;KACR;IAED,EAAE,CAAC,aAAa,CAAC,gBAAgB,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;IACxD,iBAAK,CAAC,GAAG,CAAC,OAAO,CACf,eAAK,CAAC,KAAK,CAAC,wBAAiB,eAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,oBAAiB,CAAC,CAC5E,CAAC;AACJ,CAAC;AAXD,8CAWC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unsafe-assignment */\n/* eslint-disable @typescript-eslint/no-unsafe-call */\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport * as fs from 'fs';\n// @ts-ignore - clack is ESM and TS complains about that. It works though\nimport clack from '@clack/prompts';\nimport chalk from 'chalk';\n\ntype BuildPhase = { shellScript: string };\ntype BuildPhaseMap = Record<string, BuildPhase>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getValidExistingBuildPhases(xcodeProject: any): BuildPhaseMap {\n const map: BuildPhaseMap = {};\n const raw = xcodeProject.hash.project.objects.PBXShellScriptBuildPhase || {};\n for (const key in raw) {\n const val = raw[key];\n val.isa && (map[key] = val);\n }\n\n return map;\n}\n\nexport function patchBundlePhase(bundlePhase: BuildPhase | undefined) {\n if (!bundlePhase) {\n clack.log.warn(\n `Could not find ${chalk.cyan(\n 'Bundle React Native code and images',\n )} build phase.`,\n );\n return;\n }\n\n const bundlePhaseIncludesSentry = doesBundlePhaseIncludeSentry(bundlePhase);\n if (bundlePhaseIncludesSentry) {\n clack.log.warn(\n `Build phase ${chalk.cyan(\n 'Bundle React Native code and images',\n )} already includes Sentry.`,\n );\n return;\n }\n\n const script: string = JSON.parse(bundlePhase.shellScript);\n bundlePhase.shellScript = JSON.stringify(\n addSentryToBundleShellScript(script),\n );\n clack.log.success(\n `Patched Build phase ${chalk.cyan('Bundle React Native code and images')}.`,\n );\n}\n\nexport function unPatchBundlePhase(bundlePhase: BuildPhase | undefined) {\n if (!bundlePhase) {\n clack.log.warn(\n `Could not find ${chalk.cyan(\n 'Bundle React Native code and images',\n )} build phase.`,\n );\n return;\n }\n\n if (!bundlePhase.shellScript.match(/sentry-cli\\s+react-native\\s+xcode/i)) {\n clack.log.success(\n `Build phase ${chalk.cyan(\n 'Bundle React Native code and images',\n )} does not include Sentry.`,\n );\n return;\n }\n\n bundlePhase.shellScript = JSON.stringify(\n removeSentryFromBundleShellScript(\n <string>JSON.parse(bundlePhase.shellScript),\n ),\n );\n clack.log.success(\n `Build phase ${chalk.cyan(\n 'Bundle React Native code and images',\n )} unpatched successfully.`,\n );\n}\n\nexport function removeSentryFromBundleShellScript(script: string): string {\n return (\n script\n // remove sentry properties export\n .replace(/^export SENTRY_PROPERTIES=sentry.properties\\r?\\n/m, '')\n .replace(\n /^\\/bin\\/sh .*?..\\/node_modules\\/@sentry\\/react-native\\/scripts\\/collect-modules.sh\"?\\r?\\n/m,\n '',\n )\n // unwrap react-native-xcode.sh command. In case someone replaced it\n // entirely with the sentry-cli command we need to put the original\n // version back in.\n .replace(\n /\\.\\.\\/node_modules\\/@sentry\\/cli\\/bin\\/sentry-cli\\s+react-native\\s+xcode\\s+\\$REACT_NATIVE_XCODE/i,\n '$REACT_NATIVE_XCODE',\n )\n );\n}\n\nexport function findBundlePhase(buildPhases: BuildPhaseMap) {\n return Object.values(buildPhases).find((buildPhase) =>\n buildPhase.shellScript.match(/\\/scripts\\/react-native-xcode\\.sh/i),\n );\n}\n\nexport function doesBundlePhaseIncludeSentry(buildPhase: BuildPhase) {\n return !!buildPhase.shellScript.match(/sentry-cli\\s+react-native\\s+xcode/i);\n}\n\nexport function addSentryToBundleShellScript(script: string): string {\n return (\n 'export SENTRY_PROPERTIES=sentry.properties\\n' +\n 'export EXTRA_PACKAGER_ARGS=\"--sourcemap-output $DERIVED_FILE_DIR/main.jsbundle.map\"\\n' +\n script.replace(\n '$REACT_NATIVE_XCODE',\n () =>\n // eslint-disable-next-line no-useless-escape\n '\\\\\"../node_modules/@sentry/cli/bin/sentry-cli react-native xcode $REACT_NATIVE_XCODE\\\\\"',\n ) +\n '\\n/bin/sh -c \"$WITH_ENVIRONMENT ../node_modules/@sentry/react-native/scripts/collect-modules.sh\"\\n'\n );\n}\n\nexport function addDebugFilesUploadPhase(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n xcodeProject: any,\n { debugFilesUploadPhaseExists }: { debugFilesUploadPhaseExists: boolean },\n) {\n if (debugFilesUploadPhaseExists) {\n clack.log.warn(\n `Build phase ${chalk.cyan(\n 'Upload Debug Symbols to Sentry',\n )} already exists.`,\n );\n return;\n }\n\n xcodeProject.addBuildPhase(\n [],\n 'PBXShellScriptBuildPhase',\n 'Upload Debug Symbols to Sentry',\n null,\n {\n shellPath: '/bin/sh',\n shellScript: `\nWITH_ENVIRONMENT=\"../node_modules/react-native/scripts/xcode/with-environment.sh\"\nif [ -f \"$WITH_ENVIRONMENT\" ]; then\n . \"$WITH_ENVIRONMENT\"\nfi\nexport SENTRY_PROPERTIES=sentry.properties\n[ \"$SENTRY_INCLUDE_NATIVE_SOURCES\" = \"true\" ] && INCLUDE_SOURCES_FLAG=\"--include-sources\" || INCLUDE_SOURCES_FLAG=\"\"\n../node_modules/@sentry/cli/bin/sentry-cli debug-files upload \"$INCLUDE_SOURCES_FLAG\" \"$DWARF_DSYM_FOLDER_PATH\"\n`,\n },\n );\n clack.log.success(\n `Added Build phase ${chalk.cyan('Upload Debug Symbols to Sentry')}.`,\n );\n}\n\nexport function unPatchDebugFilesUploadPhase(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n xcodeProject: any,\n) {\n const buildPhasesMap =\n xcodeProject.hash.project.objects.PBXShellScriptBuildPhase || {};\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const debugFilesUploadPhaseResult = findDebugFilesUploadPhase(buildPhasesMap);\n if (!debugFilesUploadPhaseResult) {\n clack.log.success(\n `Build phase ${chalk.cyan('Upload Debug Symbols to Sentry')} not found.`,\n );\n return;\n }\n\n const [debugFilesUploadPhaseKey] = debugFilesUploadPhaseResult;\n const firstTarget: string = xcodeProject.getFirstTarget().uuid;\n const nativeTargets = xcodeProject.hash.project.objects.PBXNativeTarget;\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete buildPhasesMap[debugFilesUploadPhaseKey];\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete buildPhasesMap[`${debugFilesUploadPhaseKey}_comment`];\n const phases = nativeTargets[firstTarget].buildPhases;\n if (phases) {\n for (let i = 0; i < phases.length; i++) {\n if (phases[i].value === debugFilesUploadPhaseKey) {\n phases.splice(i, 1);\n break;\n }\n }\n }\n clack.log.success(\n `Build phase ${chalk.cyan(\n 'Upload Debug Symbols to Sentry',\n )} removed successfully.`,\n );\n}\n\nexport function findDebugFilesUploadPhase(\n buildPhasesMap: Record<string, BuildPhase>,\n): [key: string, buildPhase: BuildPhase] | undefined {\n return Object.entries(buildPhasesMap).find(\n ([_, buildPhase]) =>\n typeof buildPhase !== 'string' &&\n !!buildPhase.shellScript.match(\n /sentry-cli\\s+(upload-dsym|debug-files upload)\\b/,\n ),\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function writeXcodeProject(xcodeProjectPath: string, xcodeProject: any) {\n const newContent = xcodeProject.writeSync();\n const currentContent = fs.readFileSync(xcodeProjectPath, 'utf-8');\n if (newContent === currentContent) {\n return;\n }\n\n fs.writeFileSync(xcodeProjectPath, newContent, 'utf-8');\n clack.log.success(\n chalk.green(`Xcode project ${chalk.cyan(xcodeProjectPath)} changes saved.`),\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"xc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EAAE,CAAC,YAAY,CAAC,gBAAgB,EAAE,OAAO,CAAC,CAAC;IAClE,IAAI,UAAU,KAAK,cAAc,EAAE;QACjC,OAAO;KACR;IAED,EAAE,CAAC,aAAa,CAAC,gBAAgB,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;IACxD,iBAAK,CAAC,GAAG,CAAC,OAAO,CACf,eAAK,CAAC,KAAK,CAAC,wBAAiB,eAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,oBAAiB,CAAC,CAC5E,CAAC;AACJ,CAAC;AAXD,8CAWC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unsafe-assignment */\n/* eslint-disable @typescript-eslint/no-unsafe-call */\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport * as fs from 'fs';\n// @ts-ignore - clack is ESM and TS complains about that. It works though\nimport clack from '@clack/prompts';\nimport chalk from 'chalk';\n\ntype BuildPhase = { shellScript: string };\ntype BuildPhaseMap = Record<string, BuildPhase>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getValidExistingBuildPhases(xcodeProject: any): BuildPhaseMap {\n const map: BuildPhaseMap = {};\n const raw = xcodeProject.hash.project.objects.PBXShellScriptBuildPhase || {};\n for (const key in raw) {\n const val = raw[key];\n val.isa && (map[key] = val);\n }\n\n return map;\n}\n\nexport function patchBundlePhase(\n bundlePhase: BuildPhase | undefined,\n patch: (script: string) => string,\n) {\n if (!bundlePhase) {\n clack.log.warn(\n `Could not find ${chalk.cyan(\n 'Bundle React Native code and images',\n )} build phase.`,\n );\n return;\n }\n\n const bundlePhaseIncludesSentry = doesBundlePhaseIncludeSentry(bundlePhase);\n if (bundlePhaseIncludesSentry) {\n clack.log.warn(\n `Build phase ${chalk.cyan(\n 'Bundle React Native code and images',\n )} already includes Sentry.`,\n );\n return;\n }\n\n const script: string = JSON.parse(bundlePhase.shellScript);\n bundlePhase.shellScript = JSON.stringify(patch(script));\n clack.log.success(\n `Patched Build phase ${chalk.cyan('Bundle React Native code and images')}.`,\n );\n}\n\nexport function unPatchBundlePhase(bundlePhase: BuildPhase | undefined) {\n if (!bundlePhase) {\n clack.log.warn(\n `Could not find ${chalk.cyan(\n 'Bundle React Native code and images',\n )} build phase.`,\n );\n return;\n }\n\n if (\n !bundlePhase.shellScript.match(/sentry-cli\\s+react-native\\s+xcode/i) &&\n !bundlePhase.shellScript.includes('sentry-xcode.sh')\n ) {\n clack.log.success(\n `Build phase ${chalk.cyan(\n 'Bundle React Native code and images',\n )} does not include Sentry.`,\n );\n return;\n }\n\n bundlePhase.shellScript = JSON.stringify(\n removeSentryFromBundleShellScript(\n <string>JSON.parse(bundlePhase.shellScript),\n ),\n );\n clack.log.success(\n `Build phase ${chalk.cyan(\n 'Bundle React Native code and images',\n )} unpatched successfully.`,\n );\n}\n\nexport function removeSentryFromBundleShellScript(script: string): string {\n return (\n script\n // remove sentry properties export\n .replace(/^export SENTRY_PROPERTIES=sentry.properties\\r?\\n/m, '')\n .replace(\n /^\\/bin\\/sh .*?..\\/node_modules\\/@sentry\\/react-native\\/scripts\\/collect-modules.sh\"?\\r?\\n/m,\n '',\n )\n // unwrap react-native-xcode.sh command. In case someone replaced it\n // entirely with the sentry-cli command we need to put the original\n // version back in.\n .replace(\n /\\.\\.\\/node_modules\\/@sentry\\/cli\\/bin\\/sentry-cli\\s+react-native\\s+xcode\\s+\\$REACT_NATIVE_XCODE/i,\n '$REACT_NATIVE_XCODE',\n )\n .replace(\n // eslint-disable-next-line no-useless-escape\n /\\\"\\/bin\\/sh.*?sentry-xcode.sh\\s+\\$REACT_NATIVE_XCODE/i,\n // eslint-disable-next-line no-useless-escape\n '\"$REACT_NATIVE_XCODE',\n )\n );\n}\n\nexport function findBundlePhase(buildPhases: BuildPhaseMap) {\n return Object.values(buildPhases).find((buildPhase) =>\n buildPhase.shellScript.match(/\\/scripts\\/react-native-xcode\\.sh/i),\n );\n}\n\nexport function doesBundlePhaseIncludeSentry(buildPhase: BuildPhase) {\n const containsSentryCliRNCommand = !!buildPhase.shellScript.match(\n /sentry-cli\\s+react-native\\s+xcode/i,\n );\n const containsBundledScript =\n buildPhase.shellScript.includes('sentry-xcode.sh');\n return containsSentryCliRNCommand || containsBundledScript;\n}\n\nexport function addSentryWithBundledScriptsToBundleShellScript(\n script: string,\n): string {\n return script.replace(\n '$REACT_NATIVE_XCODE',\n // eslint-disable-next-line no-useless-escape\n '\\\\\"/bin/sh ../node_modules/@sentry/react-native/scripts/sentry-xcode.sh $REACT_NATIVE_XCODE\\\\\"',\n );\n}\n\nexport function addSentryWithCliToBundleShellScript(script: string): string {\n return (\n 'export SENTRY_PROPERTIES=sentry.properties\\n' +\n 'export EXTRA_PACKAGER_ARGS=\"--sourcemap-output $DERIVED_FILE_DIR/main.jsbundle.map\"\\n' +\n script.replace(\n '$REACT_NATIVE_XCODE',\n () =>\n // eslint-disable-next-line no-useless-escape\n '\\\\\"../node_modules/@sentry/cli/bin/sentry-cli react-native xcode $REACT_NATIVE_XCODE\\\\\"',\n ) +\n '\\n/bin/sh -c \"$WITH_ENVIRONMENT ../node_modules/@sentry/react-native/scripts/collect-modules.sh\"\\n'\n );\n}\n\nexport function addDebugFilesUploadPhaseWithBundledScripts(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n xcodeProject: any,\n { debugFilesUploadPhaseExists }: { debugFilesUploadPhaseExists: boolean },\n) {\n if (debugFilesUploadPhaseExists) {\n clack.log.warn(\n `Build phase ${chalk.cyan(\n 'Upload Debug Symbols to Sentry',\n )} already exists.`,\n );\n return;\n }\n\n xcodeProject.addBuildPhase(\n [],\n 'PBXShellScriptBuildPhase',\n 'Upload Debug Symbols to Sentry',\n null,\n {\n shellPath: '/bin/sh',\n shellScript: `/bin/sh ../node_modules/@sentry/react-native/scripts/sentry-xcode-debug-files.sh`,\n },\n );\n clack.log.success(\n `Added Build phase ${chalk.cyan('Upload Debug Symbols to Sentry')}.`,\n );\n}\n\nexport function addDebugFilesUploadPhaseWithCli(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n xcodeProject: any,\n { debugFilesUploadPhaseExists }: { debugFilesUploadPhaseExists: boolean },\n) {\n if (debugFilesUploadPhaseExists) {\n clack.log.warn(\n `Build phase ${chalk.cyan(\n 'Upload Debug Symbols to Sentry',\n )} already exists.`,\n );\n return;\n }\n\n xcodeProject.addBuildPhase(\n [],\n 'PBXShellScriptBuildPhase',\n 'Upload Debug Symbols to Sentry',\n null,\n {\n shellPath: '/bin/sh',\n shellScript: `\nWITH_ENVIRONMENT=\"../node_modules/react-native/scripts/xcode/with-environment.sh\"\nif [ -f \"$WITH_ENVIRONMENT\" ]; then\n . \"$WITH_ENVIRONMENT\"\nfi\nexport SENTRY_PROPERTIES=sentry.properties\n[ \"$SENTRY_INCLUDE_NATIVE_SOURCES\" = \"true\" ] && INCLUDE_SOURCES_FLAG=\"--include-sources\" || INCLUDE_SOURCES_FLAG=\"\"\n../node_modules/@sentry/cli/bin/sentry-cli debug-files upload \"$INCLUDE_SOURCES_FLAG\" \"$DWARF_DSYM_FOLDER_PATH\"\n`,\n },\n );\n clack.log.success(\n `Added Build phase ${chalk.cyan('Upload Debug Symbols to Sentry')}.`,\n );\n}\n\nexport function unPatchDebugFilesUploadPhase(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n xcodeProject: any,\n) {\n const buildPhasesMap =\n xcodeProject.hash.project.objects.PBXShellScriptBuildPhase || {};\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const debugFilesUploadPhaseResult = findDebugFilesUploadPhase(buildPhasesMap);\n if (!debugFilesUploadPhaseResult) {\n clack.log.success(\n `Build phase ${chalk.cyan('Upload Debug Symbols to Sentry')} not found.`,\n );\n return;\n }\n\n const [debugFilesUploadPhaseKey] = debugFilesUploadPhaseResult;\n const firstTarget: string = xcodeProject.getFirstTarget().uuid;\n const nativeTargets = xcodeProject.hash.project.objects.PBXNativeTarget;\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete buildPhasesMap[debugFilesUploadPhaseKey];\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete buildPhasesMap[`${debugFilesUploadPhaseKey}_comment`];\n const phases = nativeTargets[firstTarget].buildPhases;\n if (phases) {\n for (let i = 0; i < phases.length; i++) {\n if (phases[i].value === debugFilesUploadPhaseKey) {\n phases.splice(i, 1);\n break;\n }\n }\n }\n clack.log.success(\n `Build phase ${chalk.cyan(\n 'Upload Debug Symbols to Sentry',\n )} removed successfully.`,\n );\n}\n\nexport function findDebugFilesUploadPhase(\n buildPhasesMap: Record<string, BuildPhase>,\n): [key: string, buildPhase: BuildPhase] | undefined {\n return Object.entries(buildPhasesMap).find(([_, buildPhase]) => {\n const containsCliDebugUpload =\n typeof buildPhase !== 'string' &&\n !!buildPhase.shellScript.match(\n /sentry-cli\\s+(upload-dsym|debug-files upload)\\b/,\n );\n const containsBundledDebugUpload =\n typeof buildPhase !== 'string' &&\n buildPhase.shellScript.includes('sentry-xcode-debug-files.sh');\n return containsCliDebugUpload || containsBundledDebugUpload;\n });\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function writeXcodeProject(xcodeProjectPath: string, xcodeProject: any) {\n const newContent = xcodeProject.writeSync();\n const currentContent = fs.readFileSync(xcodeProjectPath, 'utf-8');\n if (newContent === currentContent) {\n return;\n }\n\n fs.writeFileSync(xcodeProjectPath, newContent, 'utf-8');\n clack.log.success(\n chalk.green(`Xcode project ${chalk.cyan(xcodeProjectPath)} changes saved.`),\n );\n}\n"]}
|
|
@@ -50,6 +50,8 @@ var debug_1 = require("../utils/debug");
|
|
|
50
50
|
var telemetry_1 = require("../telemetry");
|
|
51
51
|
var utils_1 = require("./utils");
|
|
52
52
|
var Constants_1 = require("../../lib/Constants");
|
|
53
|
+
var ast_utils_1 = require("../utils/ast-utils");
|
|
54
|
+
var vite_1 = require("../sourcemaps/tools/vite");
|
|
53
55
|
function runRemixWizard(options) {
|
|
54
56
|
return __awaiter(this, void 0, void 0, function () {
|
|
55
57
|
return __generator(this, function (_a) {
|
|
@@ -63,7 +65,7 @@ function runRemixWizard(options) {
|
|
|
63
65
|
exports.runRemixWizard = runRemixWizard;
|
|
64
66
|
function runRemixWizardWithTelemetry(options) {
|
|
65
67
|
return __awaiter(this, void 0, void 0, function () {
|
|
66
|
-
var remixConfig, packageJson, _a, selectedProject, authToken, sentryUrl, dsn, isTS, isV2;
|
|
68
|
+
var remixConfig, packageJson, _a, selectedProject, authToken, sentryUrl, selfHosted, dsn, isTS, isV2, viteConfig;
|
|
67
69
|
var _this = this;
|
|
68
70
|
return __generator(this, function (_b) {
|
|
69
71
|
switch (_b.label) {
|
|
@@ -89,7 +91,7 @@ function runRemixWizardWithTelemetry(options) {
|
|
|
89
91
|
_b.sent();
|
|
90
92
|
return [4 /*yield*/, (0, clack_utils_1.getOrAskForProjectData)(options, 'javascript-remix')];
|
|
91
93
|
case 5:
|
|
92
|
-
_a = _b.sent(), selectedProject = _a.selectedProject, authToken = _a.authToken, sentryUrl = _a.sentryUrl;
|
|
94
|
+
_a = _b.sent(), selectedProject = _a.selectedProject, authToken = _a.authToken, sentryUrl = _a.sentryUrl, selfHosted = _a.selfHosted;
|
|
93
95
|
return [4 /*yield*/, (0, clack_utils_1.installPackage)({
|
|
94
96
|
packageName: '@sentry/remix',
|
|
95
97
|
alreadyInstalled: (0, package_json_1.hasPackageInstalled)('@sentry/remix', packageJson),
|
|
@@ -99,20 +101,23 @@ function runRemixWizardWithTelemetry(options) {
|
|
|
99
101
|
dsn = selectedProject.keys[0].dsn.public;
|
|
100
102
|
isTS = (0, clack_utils_1.isUsingTypeScript)();
|
|
101
103
|
isV2 = (0, sdk_setup_1.isRemixV2)(remixConfig, packageJson);
|
|
104
|
+
viteConfig = (0, ast_utils_1.findFile)('vite.config');
|
|
102
105
|
return [4 /*yield*/, (0, clack_utils_1.addSentryCliConfig)({ authToken: authToken }, clack_utils_1.rcCliSetupConfig)];
|
|
103
106
|
case 7:
|
|
104
107
|
_b.sent();
|
|
105
|
-
|
|
108
|
+
if (!viteConfig) return [3 /*break*/, 9];
|
|
109
|
+
return [4 /*yield*/, (0, telemetry_1.traceStep)('Update vite configuration for sourcemap uploads', function () { return __awaiter(_this, void 0, void 0, function () {
|
|
106
110
|
var e_1;
|
|
107
111
|
return __generator(this, function (_a) {
|
|
108
112
|
switch (_a.label) {
|
|
109
113
|
case 0:
|
|
110
114
|
_a.trys.push([0, 2, , 3]);
|
|
111
|
-
return [4 /*yield*/, (0,
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
url: sentryUrl
|
|
115
|
-
|
|
115
|
+
return [4 /*yield*/, (0, vite_1.configureVitePlugin)({
|
|
116
|
+
orgSlug: selectedProject.organization.slug,
|
|
117
|
+
projectSlug: selectedProject.slug,
|
|
118
|
+
url: sentryUrl,
|
|
119
|
+
selfHosted: selfHosted,
|
|
120
|
+
authToken: authToken,
|
|
116
121
|
})];
|
|
117
122
|
case 1:
|
|
118
123
|
_a.sent();
|
|
@@ -120,7 +125,7 @@ function runRemixWizardWithTelemetry(options) {
|
|
|
120
125
|
case 2:
|
|
121
126
|
e_1 = _a.sent();
|
|
122
127
|
prompts_1.default.log
|
|
123
|
-
.warn("Could not update
|
|
128
|
+
.warn("Could not update vite configuration to generate and upload sourcemaps.\n Please update your vite configuration manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/sourcemaps/");
|
|
124
129
|
(0, debug_1.debug)(e_1);
|
|
125
130
|
return [3 /*break*/, 3];
|
|
126
131
|
case 3: return [2 /*return*/];
|
|
@@ -129,29 +134,67 @@ function runRemixWizardWithTelemetry(options) {
|
|
|
129
134
|
}); })];
|
|
130
135
|
case 8:
|
|
131
136
|
_b.sent();
|
|
132
|
-
return [
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
137
|
+
return [3 /*break*/, 11];
|
|
138
|
+
case 9: return [4 /*yield*/, (0, telemetry_1.traceStep)('Update build script for sourcemap uploads', function () { return __awaiter(_this, void 0, void 0, function () {
|
|
139
|
+
var e_2;
|
|
140
|
+
return __generator(this, function (_a) {
|
|
141
|
+
switch (_a.label) {
|
|
142
|
+
case 0:
|
|
143
|
+
_a.trys.push([0, 2, , 3]);
|
|
144
|
+
return [4 /*yield*/, (0, sdk_setup_1.updateBuildScript)({
|
|
145
|
+
org: selectedProject.organization.slug,
|
|
146
|
+
project: selectedProject.slug,
|
|
147
|
+
url: sentryUrl === Constants_1.DEFAULT_URL ? undefined : sentryUrl,
|
|
148
|
+
isHydrogen: (0, utils_1.isHydrogenApp)(packageJson),
|
|
149
|
+
})];
|
|
150
|
+
case 1:
|
|
151
|
+
_a.sent();
|
|
152
|
+
return [3 /*break*/, 3];
|
|
153
|
+
case 2:
|
|
154
|
+
e_2 = _a.sent();
|
|
155
|
+
prompts_1.default.log
|
|
156
|
+
.warn("Could not update build script to generate and upload sourcemaps.\n Please update your build script manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/sourcemaps/");
|
|
157
|
+
(0, debug_1.debug)(e_2);
|
|
158
|
+
return [3 /*break*/, 3];
|
|
159
|
+
case 3: return [2 /*return*/];
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
}); })];
|
|
163
|
+
case 10:
|
|
164
|
+
_b.sent();
|
|
165
|
+
_b.label = 11;
|
|
166
|
+
case 11: return [4 /*yield*/, (0, telemetry_1.traceStep)('Instrument root route', function () { return __awaiter(_this, void 0, void 0, function () {
|
|
167
|
+
var e_3;
|
|
168
|
+
return __generator(this, function (_a) {
|
|
169
|
+
switch (_a.label) {
|
|
170
|
+
case 0:
|
|
171
|
+
_a.trys.push([0, 2, , 3]);
|
|
172
|
+
return [4 /*yield*/, (0, sdk_setup_1.instrumentRootRoute)(isV2, isTS)];
|
|
173
|
+
case 1:
|
|
174
|
+
_a.sent();
|
|
175
|
+
return [3 /*break*/, 3];
|
|
176
|
+
case 2:
|
|
177
|
+
e_3 = _a.sent();
|
|
178
|
+
prompts_1.default.log.warn("Could not instrument root route.\n Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/");
|
|
179
|
+
(0, debug_1.debug)(e_3);
|
|
180
|
+
return [3 /*break*/, 3];
|
|
181
|
+
case 3: return [2 /*return*/];
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
}); })];
|
|
185
|
+
case 12:
|
|
152
186
|
_b.sent();
|
|
187
|
+
(0, telemetry_1.traceStep)('Reveal missing entry files', function () {
|
|
188
|
+
try {
|
|
189
|
+
(0, sdk_setup_1.runRemixReveal)(isTS);
|
|
190
|
+
}
|
|
191
|
+
catch (e) {
|
|
192
|
+
prompts_1.default.log.warn("Could not run 'npx remix reveal'.\n Please create your entry files manually");
|
|
193
|
+
(0, debug_1.debug)(e);
|
|
194
|
+
}
|
|
195
|
+
});
|
|
153
196
|
return [4 /*yield*/, (0, telemetry_1.traceStep)('Initialize Sentry on client entry', function () { return __awaiter(_this, void 0, void 0, function () {
|
|
154
|
-
var
|
|
197
|
+
var e_4;
|
|
155
198
|
return __generator(this, function (_a) {
|
|
156
199
|
switch (_a.label) {
|
|
157
200
|
case 0:
|
|
@@ -161,18 +204,18 @@ function runRemixWizardWithTelemetry(options) {
|
|
|
161
204
|
_a.sent();
|
|
162
205
|
return [3 /*break*/, 3];
|
|
163
206
|
case 2:
|
|
164
|
-
|
|
207
|
+
e_4 = _a.sent();
|
|
165
208
|
prompts_1.default.log.warn("Could not initialize Sentry on client entry.\n Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/");
|
|
166
|
-
(0, debug_1.debug)(
|
|
209
|
+
(0, debug_1.debug)(e_4);
|
|
167
210
|
return [3 /*break*/, 3];
|
|
168
211
|
case 3: return [2 /*return*/];
|
|
169
212
|
}
|
|
170
213
|
});
|
|
171
214
|
}); })];
|
|
172
|
-
case
|
|
215
|
+
case 13:
|
|
173
216
|
_b.sent();
|
|
174
217
|
return [4 /*yield*/, (0, telemetry_1.traceStep)('Initialize Sentry on server entry', function () { return __awaiter(_this, void 0, void 0, function () {
|
|
175
|
-
var
|
|
218
|
+
var e_5;
|
|
176
219
|
return __generator(this, function (_a) {
|
|
177
220
|
switch (_a.label) {
|
|
178
221
|
case 0:
|
|
@@ -182,15 +225,15 @@ function runRemixWizardWithTelemetry(options) {
|
|
|
182
225
|
_a.sent();
|
|
183
226
|
return [3 /*break*/, 3];
|
|
184
227
|
case 2:
|
|
185
|
-
|
|
228
|
+
e_5 = _a.sent();
|
|
186
229
|
prompts_1.default.log.warn("Could not initialize Sentry on server entry.\n Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/");
|
|
187
|
-
(0, debug_1.debug)(
|
|
230
|
+
(0, debug_1.debug)(e_5);
|
|
188
231
|
return [3 /*break*/, 3];
|
|
189
232
|
case 3: return [2 /*return*/];
|
|
190
233
|
}
|
|
191
234
|
});
|
|
192
235
|
}); })];
|
|
193
|
-
case
|
|
236
|
+
case 14:
|
|
194
237
|
_b.sent();
|
|
195
238
|
prompts_1.default.outro("\n".concat(chalk_1.default.green('Sentry has been successfully configured for your Remix project.'), "\n\n").concat(chalk_1.default.cyan('You can now deploy your project to see Sentry in action.'), "\n\n").concat(chalk_1.default.cyan("To learn more about how to use Sentry with Remix, visit our documentation:\nhttps://docs.sentry.io/platforms/javascript/guides/remix/")));
|
|
196
239
|
return [2 /*return*/];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remix-wizard.js","sourceRoot":"","sources":["../../../src/remix/remix-wizard.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+EAA+E;AAC/E,2DAAmC;AACnC,gDAA0B;AAE1B,oDAU8B;AAC9B,sDAA4D;AA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AA6B,EAAC,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,EAAA;;wCAApD,SAAoD,CAAC;;;;wCAErD,iBAAK,CAAC,GAAG,CAAC,IAAI,CAAC,sKACkG,CAAC,CAAC;wCACnH,IAAA,aAAK,EAAC,GAAC,CAAC,CAAC;;;;;6BAEZ,CAAC,EAAA;;oBARF,SAQE,CAAC;oBAEH,iBAAK,CAAC,KAAK,CAAC,YACZ,eAAK,CAAC,KAAK,CACX,iEAAiE,CAClE,iBAEC,eAAK,CAAC,IAAI,CAAC,0DAA0D,CAAC,iBAEtE,eAAK,CAAC,IAAI,CACV,uIACwD,CACzD,CAAE,CAAC,CAAC;;;;;CACJ","sourcesContent":["// @ts-expect-error - clack is ESM and TS complains about that. It works though\nimport clack from '@clack/prompts';\nimport chalk from 'chalk';\n\nimport {\n addSentryCliConfig,\n confirmContinueIfNoOrDirtyGitRepo,\n ensurePackageIsInstalled,\n getOrAskForProjectData,\n getPackageDotJson,\n installPackage,\n isUsingTypeScript,\n printWelcome,\n rcCliSetupConfig,\n} from '../utils/clack-utils';\nimport { hasPackageInstalled } from '../utils/package-json';\nimport { WizardOptions } from '../utils/types';\nimport {\n initializeSentryOnEntryClient,\n initializeSentryOnEntryServer,\n updateBuildScript,\n instrumentRootRoute,\n isRemixV2,\n loadRemixConfig,\n runRemixReveal,\n} from './sdk-setup';\nimport { debug } from '../utils/debug';\nimport { traceStep, withTelemetry } from '../telemetry';\nimport { isHydrogenApp } from './utils';\nimport { DEFAULT_URL } from '../../lib/Constants';\nimport { findFile } from '../utils/ast-utils';\nimport { configureVitePlugin } from '../sourcemaps/tools/vite';\n\nexport async function runRemixWizard(options: WizardOptions): Promise<void> {\n return withTelemetry(\n {\n enabled: options.telemetryEnabled,\n integration: 'remix',\n },\n () => runRemixWizardWithTelemetry(options),\n );\n}\n\nasync function runRemixWizardWithTelemetry(\n options: WizardOptions,\n): Promise<void> {\n printWelcome({\n wizardName: 'Sentry Remix Wizard',\n promoCode: options.promoCode,\n telemetryEnabled: options.telemetryEnabled,\n });\n\n await confirmContinueIfNoOrDirtyGitRepo();\n\n const remixConfig = await loadRemixConfig();\n const packageJson = await getPackageDotJson();\n\n // We expect `@remix-run/dev` to be installed for every Remix project\n await ensurePackageIsInstalled(packageJson, '@remix-run/dev', 'Remix');\n\n const { selectedProject, authToken, sentryUrl, selfHosted } =\n await getOrAskForProjectData(options, 'javascript-remix');\n\n await installPackage({\n packageName: '@sentry/remix',\n alreadyInstalled: hasPackageInstalled('@sentry/remix', packageJson),\n });\n\n const dsn = selectedProject.keys[0].dsn.public;\n\n const isTS = isUsingTypeScript();\n const isV2 = isRemixV2(remixConfig, packageJson);\n const viteConfig = findFile('vite.config');\n\n await addSentryCliConfig({ authToken }, rcCliSetupConfig);\n\n if (viteConfig) {\n await traceStep(\n 'Update vite configuration for sourcemap uploads',\n async () => {\n try {\n await configureVitePlugin({\n orgSlug: selectedProject.organization.slug,\n projectSlug: selectedProject.slug,\n url: sentryUrl,\n selfHosted,\n authToken,\n });\n } catch (e) {\n clack.log\n .warn(`Could not update vite configuration to generate and upload sourcemaps.\n Please update your vite configuration manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/sourcemaps/`);\n debug(e);\n }\n },\n );\n } else {\n await traceStep('Update build script for sourcemap uploads', async () => {\n try {\n await updateBuildScript({\n org: selectedProject.organization.slug,\n project: selectedProject.slug,\n url: sentryUrl === DEFAULT_URL ? undefined : sentryUrl,\n isHydrogen: isHydrogenApp(packageJson),\n });\n } catch (e) {\n clack.log\n .warn(`Could not update build script to generate and upload sourcemaps.\n Please update your build script manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/sourcemaps/`);\n debug(e);\n }\n });\n }\n\n await traceStep('Instrument root route', async () => {\n try {\n await instrumentRootRoute(isV2, isTS);\n } catch (e) {\n clack.log.warn(`Could not instrument root route.\n Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/`);\n debug(e);\n }\n });\n\n traceStep('Reveal missing entry files', () => {\n try {\n runRemixReveal(isTS);\n } catch (e) {\n clack.log.warn(`Could not run 'npx remix reveal'.\n Please create your entry files manually`);\n debug(e);\n }\n });\n\n await traceStep('Initialize Sentry on client entry', async () => {\n try {\n await initializeSentryOnEntryClient(dsn, isTS);\n } catch (e) {\n clack.log.warn(`Could not initialize Sentry on client entry.\n Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/`);\n debug(e);\n }\n });\n\n await traceStep('Initialize Sentry on server entry', async () => {\n try {\n await initializeSentryOnEntryServer(dsn, isV2, isTS);\n } catch (e) {\n clack.log.warn(`Could not initialize Sentry on server entry.\n Please do it manually using instructions from https://docs.sentry.io/platforms/javascript/guides/remix/manual-setup/`);\n debug(e);\n }\n });\n\n clack.outro(`\n${chalk.green(\n 'Sentry has been successfully configured for your Remix project.',\n)}\n\n${chalk.cyan('You can now deploy your project to see Sentry in action.')}\n\n${chalk.cyan(\n `To learn more about how to use Sentry with Remix, visit our documentation:\nhttps://docs.sentry.io/platforms/javascript/guides/remix/`,\n)}`);\n}\n"]}
|
|
@@ -10,6 +10,7 @@ export type PartialRemixConfig = {
|
|
|
10
10
|
v2_routeConvention?: boolean;
|
|
11
11
|
};
|
|
12
12
|
};
|
|
13
|
+
export declare function runRemixReveal(isTS: boolean): void;
|
|
13
14
|
export declare function isRemixV2(remixConfig: PartialRemixConfig, packageJson: PackageDotJson): boolean;
|
|
14
15
|
export declare function loadRemixConfig(): Promise<PartialRemixConfig>;
|
|
15
16
|
export declare function instrumentRootRoute(isV2?: boolean, isTS?: boolean): Promise<void>;
|
|
@@ -63,10 +63,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
63
63
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
64
64
|
};
|
|
65
65
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
66
|
-
exports.initializeSentryOnEntryServer = exports.initializeSentryOnEntryClient = exports.updateBuildScript = exports.instrumentRootRoute = exports.loadRemixConfig = exports.isRemixV2 = void 0;
|
|
66
|
+
exports.initializeSentryOnEntryServer = exports.initializeSentryOnEntryClient = exports.updateBuildScript = exports.instrumentRootRoute = exports.loadRemixConfig = exports.isRemixV2 = exports.runRemixReveal = void 0;
|
|
67
67
|
var fs = __importStar(require("fs"));
|
|
68
68
|
var path = __importStar(require("path"));
|
|
69
69
|
var url = __importStar(require("url"));
|
|
70
|
+
var childProcess = __importStar(require("child_process"));
|
|
70
71
|
// @ts-expect-error - clack is ESM and TS complains about that. It works though
|
|
71
72
|
var prompts_1 = __importDefault(require("@clack/prompts"));
|
|
72
73
|
var chalk_1 = __importDefault(require("chalk"));
|
|
@@ -80,6 +81,22 @@ var root_v2_1 = require("./codemods/root-v2");
|
|
|
80
81
|
var handle_error_1 = require("./codemods/handle-error");
|
|
81
82
|
var clack_utils_1 = require("../utils/clack-utils");
|
|
82
83
|
var REMIX_CONFIG_FILE = 'remix.config.js';
|
|
84
|
+
var REMIX_REVEAL_COMMAND = 'npx remix reveal';
|
|
85
|
+
function runRemixReveal(isTS) {
|
|
86
|
+
// Check if entry files already exist
|
|
87
|
+
var clientEntryFilename = "entry.client.".concat(isTS ? 'tsx' : 'jsx');
|
|
88
|
+
var serverEntryFilename = "entry.server.".concat(isTS ? 'tsx' : 'jsx');
|
|
89
|
+
var clientEntryPath = path.join(process.cwd(), 'app', clientEntryFilename);
|
|
90
|
+
var serverEntryPath = path.join(process.cwd(), 'app', serverEntryFilename);
|
|
91
|
+
if (fs.existsSync(clientEntryPath) && fs.existsSync(serverEntryPath)) {
|
|
92
|
+
prompts_1.default.log.info("Found entry files ".concat(chalk_1.default.cyan(clientEntryFilename), " and ").concat(chalk_1.default.cyan(serverEntryFilename), "."));
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
prompts_1.default.log.info("Couldn't find entry files in your project. Trying to run ".concat(chalk_1.default.cyan(REMIX_REVEAL_COMMAND), "..."));
|
|
96
|
+
prompts_1.default.log.info(childProcess.execSync(REMIX_REVEAL_COMMAND).toString());
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
exports.runRemixReveal = runRemixReveal;
|
|
83
100
|
function insertClientInitCall(dsn, originalHooksMod) {
|
|
84
101
|
var initCall = magicast_1.builders.functionCall('Sentry.init', {
|
|
85
102
|
dsn: dsn,
|
|
@@ -208,6 +225,9 @@ function updateBuildScript(args) {
|
|
|
208
225
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
|
209
226
|
packageJson.scripts.build = packageJson.scripts.build.replace(buildCommand, instrumentedBuildCommand);
|
|
210
227
|
}
|
|
228
|
+
else {
|
|
229
|
+
throw new Error("`build` script doesn't contain a known build command. Please update it manually.");
|
|
230
|
+
}
|
|
211
231
|
return [4 /*yield*/, fs.promises.writeFile(path.join(process.cwd(), 'package.json'), JSON.stringify(packageJson, null, 2))];
|
|
212
232
|
case 2:
|
|
213
233
|
_a.sent();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk-setup.js","sourceRoot":"","sources":["../../../src/remix/sdk-setup.ts"],"names":[],"mappings":";AAAA,4DAA4D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAO5D,qCAAyB;AACzB,yCAA6B;AAC7B,uCAA2B;AAE3B,+EAA+E;AAC/E,2DAAmC;AACnC,gDAA0B;AAC1B,iCAAyC;AAEzC,kFAAkF;AAClF,qCAAuE;AACvE,sDAA0E;AAC1E,iCAAsE;AACtE,8CAA2D;AAC3D,8CAA2D;AAC3D,wDAAgE;AAChE,oDAAyD;AAczD,IAAM,iBAAiB,GAAG,iBAAiB,CAAC;AAE5C,SAAS,oBAAoB,CAC3B,GAAW,EACX,gBAAsC;IAEtC,IAAM,QAAQ,GAAG,mBAAQ,CAAC,YAAY,CAAC,aAAa,EAAE;QACpD,GAAG,KAAA;QACH,gBAAgB,EAAE,GAAG;QACrB,wBAAwB,EAAE,GAAG;QAC7B,wBAA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ACvE,sBAAO;qBACR;oBAED,sBAAsB,CAAC,OAAO,CAAC,IAAI,CAAC;wBAClC,IAAI,EAAE,eAAe;wBACrB,QAAQ,EAAE,GAAG;wBACb,KAAK,EAAE,QAAQ;qBAChB,CAAC,CAAC;oBAEH,oBAAoB,CAAC,GAAG,EAAE,sBAAsB,CAAC,CAAC;oBAElD,IAAI,IAAI,EAAE;wBACF,uBAAuB,GAAG,IAAA,oCAAqB,EACnD,sBAAsB,EACtB,mBAAmB,CACpB,CAAC;wBAEF,IAAI,uBAAuB,EAAE;4BAC3B,iBAAK,CAAC,GAAG,CAAC,OAAO,CACf,uBAAgB,eAAK,CAAC,IAAI,CAAC,aAAa,CAAC,iBAAO,eAAK,CAAC,IAAI,CACxD,UAAG,mBAAmB,CAAE,CACzB,CAAE,CACJ,CAAC;yBACH;qBACF;oBAED,qBAAM,IAAA,oBAAS,EACb,sBAAsB,CAAC,IAAI,EAC3B,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,mBAAmB,CAAC,CACrD,EAAA;;oBAHD,SAGC,CAAC;oBAEF,iBAAK,CAAC,GAAG,CAAC,OAAO,CACf,gEAAyD,eAAK,CAAC,IAAI,CACjE,mBAAmB,CACpB,MAAG,CACL,CAAC;;;;;CACH;AApDD,sEAoDC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unsafe-assignment */\n\nimport type { Program } from '@babel/types';\n\n// @ts-expect-error - magicast is ESM and TS complains about that. It works though\nimport type { ProxifiedModule } from 'magicast';\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as url from 'url';\n\n// @ts-expect-error - clack is ESM and TS complains about that. It works though\nimport clack from '@clack/prompts';\nimport chalk from 'chalk';\nimport { gte, minVersion } from 'semver';\n\n// @ts-expect-error - magicast is ESM and TS complains about that. It works though\nimport { builders, generateCode, loadFile, writeFile } from 'magicast';\nimport { PackageDotJson, getPackageVersion } from '../utils/package-json';\nimport { getInitCallInsertionIndex, hasSentryContent } from './utils';\nimport { instrumentRootRouteV1 } from './codemods/root-v1';\nimport { instrumentRootRouteV2 } from './codemods/root-v2';\nimport { instrumentHandleError } from './codemods/handle-error';\nimport { getPackageDotJson } from '../utils/clack-utils';\n\nexport type PartialRemixConfig = {\n unstable_dev?: boolean;\n future?: {\n v2_dev?: boolean;\n v2_errorBoundary?: boolean;\n v2_headers?: boolean;\n v2_meta?: boolean;\n v2_normalizeFormMethod?: boolean;\n v2_routeConvention?: boolean;\n };\n};\n\nconst REMIX_CONFIG_FILE = 'remix.config.js';\n\nfunction insertClientInitCall(\n dsn: string,\n originalHooksMod: ProxifiedModule<any>,\n): void {\n const initCall = builders.functionCall('Sentry.init', {\n dsn,\n tracesSampleRate: 1.0,\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0,\n integrations: [\n builders.newExpression('Sentry.BrowserTracing', {\n routingInstrumentation: builders.functionCall(\n 'Sentry.remixRouterInstrumentation',\n builders.raw('useEffect'),\n builders.raw('useLocation'),\n builders.raw('useMatches'),\n ),\n }),\n builders.newExpression('Sentry.Replay'),\n ],\n });\n\n const originalHooksModAST = originalHooksMod.$ast as Program;\n const initCallInsertionIndex = getInitCallInsertionIndex(originalHooksModAST);\n\n originalHooksModAST.body.splice(\n initCallInsertionIndex,\n 0,\n // @ts-expect-error - 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\nfunction insertServerInitCall(\n dsn: string,\n originalHooksMod: ProxifiedModule<any>,\n) {\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-expect-error - 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\nexport function isRemixV2(\n remixConfig: PartialRemixConfig,\n packageJson: PackageDotJson,\n): boolean {\n const remixVersion = getPackageVersion('@remix-run/react', packageJson);\n if (!remixVersion) {\n return false;\n }\n\n const minVer = minVersion(remixVersion);\n\n if (!minVer) {\n return false;\n }\n\n const isV2Remix = gte(minVer, '2.0.0');\n\n return isV2Remix || remixConfig?.future?.v2_errorBoundary || false;\n}\n\nexport async function loadRemixConfig(): Promise<PartialRemixConfig> {\n const configFilePath = path.join(process.cwd(), REMIX_CONFIG_FILE);\n\n try {\n if (!fs.existsSync(configFilePath)) {\n return {};\n }\n\n const configUrl = url.pathToFileURL(configFilePath).href;\n const remixConfigModule = (await import(configUrl)) as {\n default: PartialRemixConfig;\n };\n\n return remixConfigModule?.default || {};\n } catch (e: unknown) {\n clack.log.error(`Couldn't load ${REMIX_CONFIG_FILE}.`);\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\nexport async function instrumentRootRoute(\n isV2?: boolean,\n isTS?: boolean,\n): Promise<void> {\n const rootFilename = `root.${isTS ? 'tsx' : 'jsx'}`;\n\n if (isV2) {\n await instrumentRootRouteV2(rootFilename);\n } else {\n await instrumentRootRouteV1(rootFilename);\n }\n\n clack.log.success(\n `Successfully instrumented root route ${chalk.cyan(rootFilename)}.`,\n );\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n}\n\nexport async function updateBuildScript(args: {\n org: string;\n project: string;\n url?: string;\n isHydrogen: boolean;\n}): Promise<void> {\n const packageJson = await getPackageDotJson();\n\n if (!packageJson.scripts) {\n packageJson.scripts = {};\n }\n\n const buildCommand = args.isHydrogen\n ? 'shopify hydrogen build'\n : 'remix build';\n\n const instrumentedBuildCommand =\n `${buildCommand} --sourcemap && sentry-upload-sourcemaps --org ${args.org} --project ${args.project}` +\n (args.url ? ` --url ${args.url}` : '') +\n (args.isHydrogen ? ' --buildPath ./dist' : '');\n\n if (!packageJson.scripts.build) {\n packageJson.scripts.build = instrumentedBuildCommand;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n } else if (packageJson.scripts.build.includes(buildCommand)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n packageJson.scripts.build = packageJson.scripts.build.replace(\n buildCommand,\n instrumentedBuildCommand,\n );\n }\n\n await fs.promises.writeFile(\n path.join(process.cwd(), 'package.json'),\n JSON.stringify(packageJson, null, 2),\n );\n\n clack.log.success(\n `Successfully updated ${chalk.cyan('build')} script in ${chalk.cyan(\n 'package.json',\n )} to generate and upload sourcemaps.`,\n );\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n}\n\nexport async function initializeSentryOnEntryClient(\n dsn: string,\n isTS: boolean,\n): Promise<void> {\n const clientEntryFilename = `entry.client.${isTS ? 'tsx' : 'jsx'}`;\n\n const originalEntryClient = path.join(\n process.cwd(),\n 'app',\n clientEntryFilename,\n );\n\n const originalEntryClientMod = await loadFile(originalEntryClient);\n\n if (hasSentryContent(originalEntryClient, originalEntryClientMod.$code)) {\n return;\n }\n\n originalEntryClientMod.imports.$add({\n from: '@sentry/remix',\n imported: '*',\n local: 'Sentry',\n });\n\n originalEntryClientMod.imports.$add({\n from: 'react',\n imported: 'useEffect',\n local: 'useEffect',\n });\n\n originalEntryClientMod.imports.$add({\n from: '@remix-run/react',\n imported: 'useLocation',\n local: 'useLocation',\n });\n\n originalEntryClientMod.imports.$add({\n from: '@remix-run/react',\n imported: 'useMatches',\n local: 'useMatches',\n });\n\n insertClientInitCall(dsn, originalEntryClientMod);\n\n await writeFile(\n originalEntryClientMod.$ast,\n path.join(process.cwd(), 'app', clientEntryFilename),\n );\n\n clack.log.success(\n `Successfully initialized Sentry on client entry point ${chalk.cyan(\n clientEntryFilename,\n )}`,\n );\n}\n\nexport async function initializeSentryOnEntryServer(\n dsn: string,\n isV2: boolean,\n isTS: boolean,\n): Promise<void> {\n const serverEntryFilename = `entry.server.${isTS ? 'tsx' : 'jsx'}`;\n\n const originalEntryServer = path.join(\n process.cwd(),\n 'app',\n serverEntryFilename,\n );\n\n const originalEntryServerMod = await loadFile(originalEntryServer);\n\n if (hasSentryContent(originalEntryServer, originalEntryServerMod.$code)) {\n return;\n }\n\n originalEntryServerMod.imports.$add({\n from: '@sentry/remix',\n imported: '*',\n local: 'Sentry',\n });\n\n insertServerInitCall(dsn, originalEntryServerMod);\n\n if (isV2) {\n const handleErrorInstrumented = instrumentHandleError(\n originalEntryServerMod,\n serverEntryFilename,\n );\n\n if (handleErrorInstrumented) {\n clack.log.success(\n `Instrumented ${chalk.cyan('handleError')} in ${chalk.cyan(\n `${serverEntryFilename}`,\n )}`,\n );\n }\n }\n\n await writeFile(\n originalEntryServerMod.$ast,\n path.join(process.cwd(), 'app', serverEntryFilename),\n );\n\n clack.log.success(\n `Successfully initialized Sentry on server entry point ${chalk.cyan(\n serverEntryFilename,\n )}.`,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sdk-setup.js","sourceRoot":"","sources":["../../../src/remix/sdk-setup.ts"],"names":[],"mappings":";AAAA,4DAA4D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAO5D,qCAAyB;AACzB,yCAA6B;AAC7B,uCAA2B;AAC3B,0DAA8C;AAE9C,+EAA+E;AAC/E,2DAAmC;AACnC,gDAA0B;AAC1B,iCAAyC;AAEzC,kFAAkF;AAClF,qCAAuE;AACvE,sDAA0E;AAC1E,iCAAsE;AACtE,8CAA2D;AAC3D,8CAA2D;AAC3D,wDAAgE;AAChE,oDAAyD;AAczD,IAAM,iBAAiB,GAAG,iBAAiB,CAAC;AAC5C,IAAM,oBAAoB,GAAG,kBAAkB,CAAC;AAEhD,SAAgB,cAAc,CAAC,IAAa;IAC1C,qCAAqC;IACrC,IAAM,mBAAmB,GAAG,uBAAgB,IAAI,CAAC,CAAC,CAAC,KAAK,C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EAAE,GAAG;wBACb,KAAK,EAAE,QAAQ;qBAChB,CAAC,CAAC;oBAEH,oBAAoB,CAAC,GAAG,EAAE,sBAAsB,CAAC,CAAC;oBAElD,IAAI,IAAI,EAAE;wBACF,uBAAuB,GAAG,IAAA,oCAAqB,EACnD,sBAAsB,EACtB,mBAAmB,CACpB,CAAC;wBAEF,IAAI,uBAAuB,EAAE;4BAC3B,iBAAK,CAAC,GAAG,CAAC,OAAO,CACf,uBAAgB,eAAK,CAAC,IAAI,CAAC,aAAa,CAAC,iBAAO,eAAK,CAAC,IAAI,CACxD,UAAG,mBAAmB,CAAE,CACzB,CAAE,CACJ,CAAC;yBACH;qBACF;oBAED,qBAAM,IAAA,oBAAS,EACb,sBAAsB,CAAC,IAAI,EAC3B,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,mBAAmB,CAAC,CACrD,EAAA;;oBAHD,SAGC,CAAC;oBAEF,iBAAK,CAAC,GAAG,CAAC,OAAO,CACf,gEAAyD,eAAK,CAAC,IAAI,CACjE,mBAAmB,CACpB,MAAG,CACL,CAAC;;;;;CACH;AApDD,sEAoDC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unsafe-assignment */\n\nimport type { Program } from '@babel/types';\n\n// @ts-expect-error - magicast is ESM and TS complains about that. It works though\nimport type { ProxifiedModule } from 'magicast';\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as url from 'url';\nimport * as childProcess from 'child_process';\n\n// @ts-expect-error - clack is ESM and TS complains about that. It works though\nimport clack from '@clack/prompts';\nimport chalk from 'chalk';\nimport { gte, minVersion } from 'semver';\n\n// @ts-expect-error - magicast is ESM and TS complains about that. It works though\nimport { builders, generateCode, loadFile, writeFile } from 'magicast';\nimport { PackageDotJson, getPackageVersion } from '../utils/package-json';\nimport { getInitCallInsertionIndex, hasSentryContent } from './utils';\nimport { instrumentRootRouteV1 } from './codemods/root-v1';\nimport { instrumentRootRouteV2 } from './codemods/root-v2';\nimport { instrumentHandleError } from './codemods/handle-error';\nimport { getPackageDotJson } from '../utils/clack-utils';\n\nexport type PartialRemixConfig = {\n unstable_dev?: boolean;\n future?: {\n v2_dev?: boolean;\n v2_errorBoundary?: boolean;\n v2_headers?: boolean;\n v2_meta?: boolean;\n v2_normalizeFormMethod?: boolean;\n v2_routeConvention?: boolean;\n };\n};\n\nconst REMIX_CONFIG_FILE = 'remix.config.js';\nconst REMIX_REVEAL_COMMAND = 'npx remix reveal';\n\nexport function runRemixReveal(isTS: boolean): void {\n // Check if entry files already exist\n const clientEntryFilename = `entry.client.${isTS ? 'tsx' : 'jsx'}`;\n const serverEntryFilename = `entry.server.${isTS ? 'tsx' : 'jsx'}`;\n\n const clientEntryPath = path.join(process.cwd(), 'app', clientEntryFilename);\n const serverEntryPath = path.join(process.cwd(), 'app', serverEntryFilename);\n\n if (fs.existsSync(clientEntryPath) && fs.existsSync(serverEntryPath)) {\n clack.log.info(\n `Found entry files ${chalk.cyan(clientEntryFilename)} and ${chalk.cyan(\n serverEntryFilename,\n )}.`,\n );\n } else {\n clack.log.info(\n `Couldn't find entry files in your project. Trying to run ${chalk.cyan(\n REMIX_REVEAL_COMMAND,\n )}...`,\n );\n\n clack.log.info(childProcess.execSync(REMIX_REVEAL_COMMAND).toString());\n }\n}\n\nfunction insertClientInitCall(\n dsn: string,\n originalHooksMod: ProxifiedModule<any>,\n): void {\n const initCall = builders.functionCall('Sentry.init', {\n dsn,\n tracesSampleRate: 1.0,\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0,\n integrations: [\n builders.newExpression('Sentry.BrowserTracing', {\n routingInstrumentation: builders.functionCall(\n 'Sentry.remixRouterInstrumentation',\n builders.raw('useEffect'),\n builders.raw('useLocation'),\n builders.raw('useMatches'),\n ),\n }),\n builders.newExpression('Sentry.Replay'),\n ],\n });\n\n const originalHooksModAST = originalHooksMod.$ast as Program;\n const initCallInsertionIndex = getInitCallInsertionIndex(originalHooksModAST);\n\n originalHooksModAST.body.splice(\n initCallInsertionIndex,\n 0,\n // @ts-expect-error - 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\nfunction insertServerInitCall(\n dsn: string,\n originalHooksMod: ProxifiedModule<any>,\n) {\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-expect-error - 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\nexport function isRemixV2(\n remixConfig: PartialRemixConfig,\n packageJson: PackageDotJson,\n): boolean {\n const remixVersion = getPackageVersion('@remix-run/react', packageJson);\n if (!remixVersion) {\n return false;\n }\n\n const minVer = minVersion(remixVersion);\n\n if (!minVer) {\n return false;\n }\n\n const isV2Remix = gte(minVer, '2.0.0');\n\n return isV2Remix || remixConfig?.future?.v2_errorBoundary || false;\n}\n\nexport async function loadRemixConfig(): Promise<PartialRemixConfig> {\n const configFilePath = path.join(process.cwd(), REMIX_CONFIG_FILE);\n\n try {\n if (!fs.existsSync(configFilePath)) {\n return {};\n }\n\n const configUrl = url.pathToFileURL(configFilePath).href;\n const remixConfigModule = (await import(configUrl)) as {\n default: PartialRemixConfig;\n };\n\n return remixConfigModule?.default || {};\n } catch (e: unknown) {\n clack.log.error(`Couldn't load ${REMIX_CONFIG_FILE}.`);\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\nexport async function instrumentRootRoute(\n isV2?: boolean,\n isTS?: boolean,\n): Promise<void> {\n const rootFilename = `root.${isTS ? 'tsx' : 'jsx'}`;\n\n if (isV2) {\n await instrumentRootRouteV2(rootFilename);\n } else {\n await instrumentRootRouteV1(rootFilename);\n }\n\n clack.log.success(\n `Successfully instrumented root route ${chalk.cyan(rootFilename)}.`,\n );\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n}\n\nexport async function updateBuildScript(args: {\n org: string;\n project: string;\n url?: string;\n isHydrogen: boolean;\n}): Promise<void> {\n const packageJson = await getPackageDotJson();\n\n if (!packageJson.scripts) {\n packageJson.scripts = {};\n }\n\n const buildCommand = args.isHydrogen\n ? 'shopify hydrogen build'\n : 'remix build';\n\n const instrumentedBuildCommand =\n `${buildCommand} --sourcemap && sentry-upload-sourcemaps --org ${args.org} --project ${args.project}` +\n (args.url ? ` --url ${args.url}` : '') +\n (args.isHydrogen ? ' --buildPath ./dist' : '');\n\n if (!packageJson.scripts.build) {\n packageJson.scripts.build = instrumentedBuildCommand;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n } else if (packageJson.scripts.build.includes(buildCommand)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n packageJson.scripts.build = packageJson.scripts.build.replace(\n buildCommand,\n instrumentedBuildCommand,\n );\n } else {\n throw new Error(\n \"`build` script doesn't contain a known build command. Please update it manually.\",\n );\n }\n\n await fs.promises.writeFile(\n path.join(process.cwd(), 'package.json'),\n JSON.stringify(packageJson, null, 2),\n );\n\n clack.log.success(\n `Successfully updated ${chalk.cyan('build')} script in ${chalk.cyan(\n 'package.json',\n )} to generate and upload sourcemaps.`,\n );\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n}\n\nexport async function initializeSentryOnEntryClient(\n dsn: string,\n isTS: boolean,\n): Promise<void> {\n const clientEntryFilename = `entry.client.${isTS ? 'tsx' : 'jsx'}`;\n\n const originalEntryClient = path.join(\n process.cwd(),\n 'app',\n clientEntryFilename,\n );\n\n const originalEntryClientMod = await loadFile(originalEntryClient);\n\n if (hasSentryContent(originalEntryClient, originalEntryClientMod.$code)) {\n return;\n }\n\n originalEntryClientMod.imports.$add({\n from: '@sentry/remix',\n imported: '*',\n local: 'Sentry',\n });\n\n originalEntryClientMod.imports.$add({\n from: 'react',\n imported: 'useEffect',\n local: 'useEffect',\n });\n\n originalEntryClientMod.imports.$add({\n from: '@remix-run/react',\n imported: 'useLocation',\n local: 'useLocation',\n });\n\n originalEntryClientMod.imports.$add({\n from: '@remix-run/react',\n imported: 'useMatches',\n local: 'useMatches',\n });\n\n insertClientInitCall(dsn, originalEntryClientMod);\n\n await writeFile(\n originalEntryClientMod.$ast,\n path.join(process.cwd(), 'app', clientEntryFilename),\n );\n\n clack.log.success(\n `Successfully initialized Sentry on client entry point ${chalk.cyan(\n clientEntryFilename,\n )}`,\n );\n}\n\nexport async function initializeSentryOnEntryServer(\n dsn: string,\n isV2: boolean,\n isTS: boolean,\n): Promise<void> {\n const serverEntryFilename = `entry.server.${isTS ? 'tsx' : 'jsx'}`;\n\n const originalEntryServer = path.join(\n process.cwd(),\n 'app',\n serverEntryFilename,\n );\n\n const originalEntryServerMod = await loadFile(originalEntryServer);\n\n if (hasSentryContent(originalEntryServer, originalEntryServerMod.$code)) {\n return;\n }\n\n originalEntryServerMod.imports.$add({\n from: '@sentry/remix',\n imported: '*',\n local: 'Sentry',\n });\n\n insertServerInitCall(dsn, originalEntryServerMod);\n\n if (isV2) {\n const handleErrorInstrumented = instrumentHandleError(\n originalEntryServerMod,\n serverEntryFilename,\n );\n\n if (handleErrorInstrumented) {\n clack.log.success(\n `Instrumented ${chalk.cyan('handleError')} in ${chalk.cyan(\n `${serverEntryFilename}`,\n )}`,\n );\n }\n }\n\n await writeFile(\n originalEntryServerMod.$ast,\n path.join(process.cwd(), 'app', serverEntryFilename),\n );\n\n clack.log.success(\n `Successfully initialized Sentry on server entry point ${chalk.cyan(\n serverEntryFilename,\n )}.`,\n );\n}\n"]}
|
|
@@ -79,4 +79,18 @@ export declare function parseJsonC(jsonString: string): JsonCParseResult;
|
|
|
79
79
|
* @returns the JSON-C string
|
|
80
80
|
*/
|
|
81
81
|
export declare function printJsonC(ast: t.Program): string;
|
|
82
|
+
/**
|
|
83
|
+
* Walks the program body and returns index of the last variable assignment initialized by require statement.
|
|
84
|
+
* Only counts top level require statements.
|
|
85
|
+
*
|
|
86
|
+
* @returns index of the last `const foo = require('bar');` statement
|
|
87
|
+
*/
|
|
88
|
+
export declare function getLastRequireIndex(program: t.Program): number;
|
|
89
|
+
/**
|
|
90
|
+
* Walks the statements and removes require statements which first argument includes the predicate.
|
|
91
|
+
* Only removes top level require statements like `const foo = require('bar');`
|
|
92
|
+
*
|
|
93
|
+
* @returns True if any require statement was removed.
|
|
94
|
+
*/
|
|
95
|
+
export declare function removeRequire(program: t.Program, predicate: string): boolean;
|
|
82
96
|
export {};
|
|
@@ -43,7 +43,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
|
|
|
43
43
|
return to.concat(ar || Array.prototype.slice.call(from));
|
|
44
44
|
};
|
|
45
45
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
46
|
-
exports.printJsonC = exports.parseJsonC = exports.setOrUpdateObjectProperty = exports.getOrSetObjectProperty = exports.getObjectProperty = exports.hasSentryContent = exports.findFile = void 0;
|
|
46
|
+
exports.removeRequire = exports.getLastRequireIndex = exports.printJsonC = exports.parseJsonC = exports.setOrUpdateObjectProperty = exports.getOrSetObjectProperty = exports.getObjectProperty = exports.hasSentryContent = exports.findFile = void 0;
|
|
47
47
|
var fs = __importStar(require("fs"));
|
|
48
48
|
var recast = __importStar(require("recast"));
|
|
49
49
|
var b = recast.types.builders;
|
|
@@ -208,4 +208,52 @@ function printJsonC(ast) {
|
|
|
208
208
|
return js.substring(1, js.length - 1);
|
|
209
209
|
}
|
|
210
210
|
exports.printJsonC = printJsonC;
|
|
211
|
+
/**
|
|
212
|
+
* Walks the program body and returns index of the last variable assignment initialized by require statement.
|
|
213
|
+
* Only counts top level require statements.
|
|
214
|
+
*
|
|
215
|
+
* @returns index of the last `const foo = require('bar');` statement
|
|
216
|
+
*/
|
|
217
|
+
function getLastRequireIndex(program) {
|
|
218
|
+
var lastRequireIdex = 0;
|
|
219
|
+
program.body.forEach(function (s, i) {
|
|
220
|
+
if (s.type === 'VariableDeclaration' &&
|
|
221
|
+
s.declarations[0].type === 'VariableDeclarator' &&
|
|
222
|
+
s.declarations[0].init !== null &&
|
|
223
|
+
typeof s.declarations[0].init !== 'undefined' &&
|
|
224
|
+
s.declarations[0].init.type === 'CallExpression' &&
|
|
225
|
+
s.declarations[0].init.callee.type === 'Identifier' &&
|
|
226
|
+
s.declarations[0].init.callee.name === 'require') {
|
|
227
|
+
lastRequireIdex = i;
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
return lastRequireIdex;
|
|
231
|
+
}
|
|
232
|
+
exports.getLastRequireIndex = getLastRequireIndex;
|
|
233
|
+
/**
|
|
234
|
+
* Walks the statements and removes require statements which first argument includes the predicate.
|
|
235
|
+
* Only removes top level require statements like `const foo = require('bar');`
|
|
236
|
+
*
|
|
237
|
+
* @returns True if any require statement was removed.
|
|
238
|
+
*/
|
|
239
|
+
function removeRequire(program, predicate) {
|
|
240
|
+
var removedAtLeastOne = false;
|
|
241
|
+
program.body = program.body.filter(function (s) {
|
|
242
|
+
if (s.type === 'VariableDeclaration' &&
|
|
243
|
+
s.declarations[0].type === 'VariableDeclarator' &&
|
|
244
|
+
s.declarations[0].init !== null &&
|
|
245
|
+
typeof s.declarations[0].init !== 'undefined' &&
|
|
246
|
+
s.declarations[0].init.type === 'CallExpression' &&
|
|
247
|
+
s.declarations[0].init.callee.type === 'Identifier' &&
|
|
248
|
+
s.declarations[0].init.callee.name === 'require' &&
|
|
249
|
+
s.declarations[0].init.arguments[0].type === 'StringLiteral' &&
|
|
250
|
+
s.declarations[0].init.arguments[0].value.includes(predicate)) {
|
|
251
|
+
removedAtLeastOne = true;
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
return true;
|
|
255
|
+
});
|
|
256
|
+
return removedAtLeastOne;
|
|
257
|
+
}
|
|
258
|
+
exports.removeRequire = removeRequire;
|
|
211
259
|
//# sourceMappingURL=ast-utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ast-utils.js","sourceRoot":"","sources":["../../../src/utils/ast-utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,qCAAyB;AAEzB,6CAAiC;AAIjC,IAAM,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC;AAEhC;;;GAGG;AACH,SAAgB,QAAQ,CACtB,QAAgB,EAChB,SAAoD;IAApD,0BAAA,EAAA,aAAuB,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC;IAEpD,OAAO,SAAS;SACb,GAAG,CAAC,UAAC,IAAI,IAAK,OAAA,UAAG,QAAQ,SAAG,IAAI,CAAE,EAApB,CAAoB,CAAC;SACnC,IAAI,CAAC,UAAC,IAAI,IAAK,OAAA,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,EAAnB,CAAmB,CAAC,CAAC;AACzC,CAAC;AAPD,4BAOC;AAED;;GAEG;AACH,SAAgB,gBAAgB,CAAC,OAAkB;IACjD,IAAI,WAAW,GAAwB,KAAK,CAAC;IAC7C,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE;QACpB,kBAAkB,YAAC,IAAI;YACrB,WAAW,GAAG,WAAW,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;YACpE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QACtB,CAAC;QACD,YAAY,YAAC,IAAI;;YACf,WAAW;gBACT,WAAW,KAAI,MAAA,IAAI,CAAC,IAAI,CAAC,KAAK,0CAAE,QAAQ,GAAG,UAAU,CAAC,UAAU,CAAC,CAAA,CAAC;YACpE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QACtB,CAAC;KACF,CAAC,CAAC;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CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,qBAAqB;YACzC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,KAAK,kBAAkB;YAClD,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC;YACzB,SAAS,CAAC;QAEZ,IAAI,UAAU,EAAE;YACd,OAAO,EAAE,UAAU,YAAA,EAAE,GAAG,KAAA,EAAE,CAAC;SAC5B;KACF;IAAC,WAAM;QACN,WAAW;KACZ;IACD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,GAAG,EAAE,SAAS,EAAE,CAAC;AACnD,CAAC;AApBD,gCAoBC;AAED;;;;;;;;;GASG;AACH,SAAgB,UAAU,CAAC,GAAc;IACvC,IAAM,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;IAClC,OAAO,EAAE,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACxC,CAAC;AAHD,gCAGC","sourcesContent":["import * as fs from 'fs';\n\nimport * as recast from 'recast';\nimport x = recast.types;\nimport t = x.namedTypes;\n\nconst b = recast.types.builders;\n\n/**\n * Checks if a file where we don't know its concrete file type yet exists\n * and returns the full path to the file with the correct file type.\n */\nexport function findFile(\n filePath: string,\n fileTypes: string[] = ['.js', '.ts', '.mjs', '.cjs'],\n): string | undefined {\n return fileTypes\n .map((type) => `${filePath}${type}`)\n .find((file) => fs.existsSync(file));\n}\n\n/**\n * checks for require('@sentry/*') syntax\n */\nexport function hasSentryContent(program: t.Program): boolean {\n let foundSentry: boolean | undefined = false;\n recast.visit(program, {\n visitStringLiteral(path) {\n foundSentry = foundSentry || path.node.value.startsWith('@sentry/');\n this.traverse(path);\n },\n visitLiteral(path) {\n foundSentry =\n foundSentry || path.node.value?.toString().startsWith('@sentry/');\n this.traverse(path);\n },\n });\n\n return !!foundSentry;\n}\n\n/**\n * Searches for a property of an ObjectExpression by name\n *\n * @param object the ObjectExpression to search in\n * @param name the name of the property to search for\n *\n * @returns the property if it exists\n */\nexport function getObjectProperty(\n object: t.ObjectExpression,\n name: string,\n): t.Property | undefined {\n return object.properties.find((p): p is t.Property => {\n const isObjectProp = p.type === 'Property' || p.type === 'ObjectProperty';\n\n if (!isObjectProp) {\n return false;\n }\n\n const hasMatchingLiteralKey =\n isObjectProp &&\n (p.key.type === 'Literal' || p.key.type === 'StringLiteral') &&\n p.key.value === name;\n\n if (hasMatchingLiteralKey) {\n return true;\n }\n\n // has matching identifier key\n return isObjectProp && p.key.type === 'Identifier' && p.key.name === name;\n });\n}\n\n/**\n * Attempts to find a property of an ObjectExpression by name. If it doesn't exist,\n * the property will be added to the ObjectExpression with the provided default value.\n *\n * @param object the parent object expression to search in\n * @param name the name of the property to search for\n * @param defaultValue the default value to set if the property doesn't exist\n *\n * @returns the\n */\nexport function getOrSetObjectProperty(\n object: t.ObjectExpression,\n name: string,\n defaultValue:\n | t.Literal\n | t.BooleanLiteral\n | t.StringLiteral\n | t.ObjectExpression,\n): t.Property {\n const existingProperty = getObjectProperty(object, name);\n\n if (existingProperty) {\n return existingProperty;\n }\n\n const newProperty = b.property.from({\n kind: 'init',\n key: b.stringLiteral(name),\n value: defaultValue,\n });\n\n object.properties.push(newProperty);\n\n return newProperty;\n}\n\n/**\n * Sets a property of an ObjectExpression if it exists, otherwise adds it\n * to the ObjectExpression. Optionally, a comment can be added to the\n * property.\n *\n * @param object the ObjectExpression to set the property on\n * @param name the name of the property to set\n * @param value the value of the property to set\n * @param comment (optional) a comment to add to the property\n */\nexport function setOrUpdateObjectProperty(\n object: t.ObjectExpression,\n name: string,\n value: t.Literal | t.BooleanLiteral | t.StringLiteral | t.ObjectExpression,\n comment?: string,\n) {\n const newComments =\n comment &&\n comment.split('\\n').map((c) => b.commentLine(` ${c}`, true, false));\n\n const existingProperty = getObjectProperty(object, name);\n\n if (existingProperty) {\n existingProperty.value = value;\n if (newComments) {\n existingProperty.comments = [\n ...(existingProperty?.comments || []),\n ...newComments,\n ];\n }\n } else {\n object.properties.push(\n b.objectProperty.from({\n key: b.stringLiteral(name),\n value,\n ...(newComments && {\n comments: newComments,\n }),\n }),\n );\n }\n}\n\ntype JsonCParseResult =\n | {\n jsonObject: t.ObjectExpression;\n ast: t.Program;\n }\n | {\n jsonObject: undefined;\n ast: undefined;\n };\n\n/**\n * Parses a JSON string with (potential) comments (JSON-C) and returns the JS AST\n * that can be walked and modified with recast like a normal JS AST.\n *\n * This is done by wrapping the JSON-C string in parentheses, thereby making it\n * a JS `Program` with an `ExpressionStatement` as its body. The expression is then\n * extracted from the AST and returned alongside the AST.\n *\n * To preserve as much original formatting as possible, the returned `ast`\n * property should be passed to {@link `printJsonC`} to get the JSON-C string back.\n *\n * If the input is not valid JSON-C, the result will be undefined.\n *\n * @see {@link JsonCParseResult}\n *\n * @param jsonString a JSON-C string\n *\n * @returns a {@link JsonCParseResult}, containing either the JSON-C object and the AST or undefined in both cases\n */\nexport function parseJsonC(jsonString: string): JsonCParseResult {\n try {\n const jsTsConfig = `(${jsonString})`;\n // no idea why recast returns any here, this is dumb :/\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const ast = recast.parse(jsTsConfig.toString()).program as t.Program;\n\n const jsonObject =\n (ast.body[0].type === 'ExpressionStatement' &&\n ast.body[0].expression.type === 'ObjectExpression' &&\n ast.body[0].expression) ||\n undefined;\n\n if (jsonObject) {\n return { jsonObject, ast };\n }\n } catch {\n /* empty */\n }\n return { jsonObject: undefined, ast: undefined };\n}\n\n/**\n * Takes the AST of a parsed JSON-C \"program\" and returns the JSON-C string without\n * any of the temporary JS wrapper code that was previously applied.\n *\n * Only use this in conjunction with {@link `parseJsonC`}\n *\n * @param ast the `ast` returned from {@link `parseJsonC`}\n *\n * @returns the JSON-C string\n */\nexport function printJsonC(ast: t.Program): string {\n const js = recast.print(ast).code;\n return js.substring(1, js.length - 1);\n}\n"]}
|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C","sourcesContent":["import * as fs from 'fs';\n\nimport * as recast from 'recast';\nimport x = recast.types;\nimport t = x.namedTypes;\n\nconst b = recast.types.builders;\n\n/**\n * Checks if a file where we don't know its concrete file type yet exists\n * and returns the full path to the file with the correct file type.\n */\nexport function findFile(\n filePath: string,\n fileTypes: string[] = ['.js', '.ts', '.mjs', '.cjs'],\n): string | undefined {\n return fileTypes\n .map((type) => `${filePath}${type}`)\n .find((file) => fs.existsSync(file));\n}\n\n/**\n * checks for require('@sentry/*') syntax\n */\nexport function hasSentryContent(program: t.Program): boolean {\n let foundSentry: boolean | undefined = false;\n recast.visit(program, {\n visitStringLiteral(path) {\n foundSentry = foundSentry || path.node.value.startsWith('@sentry/');\n this.traverse(path);\n },\n visitLiteral(path) {\n foundSentry =\n foundSentry || path.node.value?.toString().startsWith('@sentry/');\n this.traverse(path);\n },\n });\n\n return !!foundSentry;\n}\n\n/**\n * Searches for a property of an ObjectExpression by name\n *\n * @param object the ObjectExpression to search in\n * @param name the name of the property to search for\n *\n * @returns the property if it exists\n */\nexport function getObjectProperty(\n object: t.ObjectExpression,\n name: string,\n): t.Property | undefined {\n return object.properties.find((p): p is t.Property => {\n const isObjectProp = p.type === 'Property' || p.type === 'ObjectProperty';\n\n if (!isObjectProp) {\n return false;\n }\n\n const hasMatchingLiteralKey =\n isObjectProp &&\n (p.key.type === 'Literal' || p.key.type === 'StringLiteral') &&\n p.key.value === name;\n\n if (hasMatchingLiteralKey) {\n return true;\n }\n\n // has matching identifier key\n return isObjectProp && p.key.type === 'Identifier' && p.key.name === name;\n });\n}\n\n/**\n * Attempts to find a property of an ObjectExpression by name. If it doesn't exist,\n * the property will be added to the ObjectExpression with the provided default value.\n *\n * @param object the parent object expression to search in\n * @param name the name of the property to search for\n * @param defaultValue the default value to set if the property doesn't exist\n *\n * @returns the\n */\nexport function getOrSetObjectProperty(\n object: t.ObjectExpression,\n name: string,\n defaultValue:\n | t.Literal\n | t.BooleanLiteral\n | t.StringLiteral\n | t.ObjectExpression,\n): t.Property {\n const existingProperty = getObjectProperty(object, name);\n\n if (existingProperty) {\n return existingProperty;\n }\n\n const newProperty = b.property.from({\n kind: 'init',\n key: b.stringLiteral(name),\n value: defaultValue,\n });\n\n object.properties.push(newProperty);\n\n return newProperty;\n}\n\n/**\n * Sets a property of an ObjectExpression if it exists, otherwise adds it\n * to the ObjectExpression. Optionally, a comment can be added to the\n * property.\n *\n * @param object the ObjectExpression to set the property on\n * @param name the name of the property to set\n * @param value the value of the property to set\n * @param comment (optional) a comment to add to the property\n */\nexport function setOrUpdateObjectProperty(\n object: t.ObjectExpression,\n name: string,\n value: t.Literal | t.BooleanLiteral | t.StringLiteral | t.ObjectExpression,\n comment?: string,\n) {\n const newComments =\n comment &&\n comment.split('\\n').map((c) => b.commentLine(` ${c}`, true, false));\n\n const existingProperty = getObjectProperty(object, name);\n\n if (existingProperty) {\n existingProperty.value = value;\n if (newComments) {\n existingProperty.comments = [\n ...(existingProperty?.comments || []),\n ...newComments,\n ];\n }\n } else {\n object.properties.push(\n b.objectProperty.from({\n key: b.stringLiteral(name),\n value,\n ...(newComments && {\n comments: newComments,\n }),\n }),\n );\n }\n}\n\ntype JsonCParseResult =\n | {\n jsonObject: t.ObjectExpression;\n ast: t.Program;\n }\n | {\n jsonObject: undefined;\n ast: undefined;\n };\n\n/**\n * Parses a JSON string with (potential) comments (JSON-C) and returns the JS AST\n * that can be walked and modified with recast like a normal JS AST.\n *\n * This is done by wrapping the JSON-C string in parentheses, thereby making it\n * a JS `Program` with an `ExpressionStatement` as its body. The expression is then\n * extracted from the AST and returned alongside the AST.\n *\n * To preserve as much original formatting as possible, the returned `ast`\n * property should be passed to {@link `printJsonC`} to get the JSON-C string back.\n *\n * If the input is not valid JSON-C, the result will be undefined.\n *\n * @see {@link JsonCParseResult}\n *\n * @param jsonString a JSON-C string\n *\n * @returns a {@link JsonCParseResult}, containing either the JSON-C object and the AST or undefined in both cases\n */\nexport function parseJsonC(jsonString: string): JsonCParseResult {\n try {\n const jsTsConfig = `(${jsonString})`;\n // no idea why recast returns any here, this is dumb :/\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const ast = recast.parse(jsTsConfig.toString()).program as t.Program;\n\n const jsonObject =\n (ast.body[0].type === 'ExpressionStatement' &&\n ast.body[0].expression.type === 'ObjectExpression' &&\n ast.body[0].expression) ||\n undefined;\n\n if (jsonObject) {\n return { jsonObject, ast };\n }\n } catch {\n /* empty */\n }\n return { jsonObject: undefined, ast: undefined };\n}\n\n/**\n * Takes the AST of a parsed JSON-C \"program\" and returns the JSON-C string without\n * any of the temporary JS wrapper code that was previously applied.\n *\n * Only use this in conjunction with {@link `parseJsonC`}\n *\n * @param ast the `ast` returned from {@link `parseJsonC`}\n *\n * @returns the JSON-C string\n */\nexport function printJsonC(ast: t.Program): string {\n const js = recast.print(ast).code;\n return js.substring(1, js.length - 1);\n}\n\n/**\n * Walks the program body and returns index of the last variable assignment initialized by require statement.\n * Only counts top level require statements.\n *\n * @returns index of the last `const foo = require('bar');` statement\n */\nexport function getLastRequireIndex(program: t.Program): number {\n let lastRequireIdex = 0;\n program.body.forEach((s, i) => {\n if (\n s.type === 'VariableDeclaration' &&\n s.declarations[0].type === 'VariableDeclarator' &&\n s.declarations[0].init !== null &&\n typeof s.declarations[0].init !== 'undefined' &&\n s.declarations[0].init.type === 'CallExpression' &&\n s.declarations[0].init.callee.type === 'Identifier' &&\n s.declarations[0].init.callee.name === 'require'\n ) {\n lastRequireIdex = i;\n }\n });\n return lastRequireIdex;\n}\n\n/**\n * Walks the statements and removes require statements which first argument includes the predicate.\n * Only removes top level require statements like `const foo = require('bar');`\n *\n * @returns True if any require statement was removed.\n */\nexport function removeRequire(program: t.Program, predicate: string): boolean {\n let removedAtLeastOne = false;\n program.body = program.body.filter((s) => {\n if (\n s.type === 'VariableDeclaration' &&\n s.declarations[0].type === 'VariableDeclarator' &&\n s.declarations[0].init !== null &&\n typeof s.declarations[0].init !== 'undefined' &&\n s.declarations[0].init.type === 'CallExpression' &&\n s.declarations[0].init.callee.type === 'Identifier' &&\n s.declarations[0].init.callee.name === 'require' &&\n s.declarations[0].init.arguments[0].type === 'StringLiteral' &&\n s.declarations[0].init.arguments[0].value.includes(predicate)\n ) {\n removedAtLeastOne = true;\n return false;\n }\n return true;\n });\n return removedAtLeastOne;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|