@sentry/bundler-plugin-core 3.2.4 → 3.3.0-alpha.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/dist/cjs/index.js CHANGED
@@ -2,23 +2,23 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var SentryCli = require('@sentry/cli');
6
5
  var core = require('@babel/core');
7
6
  var componentNameAnnotatePlugin = require('@sentry/babel-plugin-component-annotate');
7
+ var SentryCli = require('@sentry/cli');
8
8
  var fs = require('fs');
9
- var path = require('path');
9
+ var glob = require('glob');
10
10
  var MagicString = require('magic-string');
11
+ var path = require('path');
11
12
  var unplugin = require('unplugin');
12
- var findUp = require('find-up');
13
+ var dotenv = require('dotenv');
13
14
  var os = require('os');
15
+ var findUp = require('find-up');
14
16
  var crypto = require('crypto');
15
17
  var childProcess = require('child_process');
16
- var glob = require('glob');
17
- var util = require('util');
18
18
  var https = require('node:https');
19
19
  var node_stream = require('node:stream');
20
20
  var node_zlib = require('node:zlib');
21
- var dotenv = require('dotenv');
21
+ var util = require('util');
22
22
 
23
23
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
24
24
 
@@ -40,20 +40,21 @@ function _interopNamespace(e) {
40
40
  return Object.freeze(n);
41
41
  }
42
42
 
43
- var SentryCli__default = /*#__PURE__*/_interopDefaultLegacy(SentryCli);
44
43
  var componentNameAnnotatePlugin__default = /*#__PURE__*/_interopDefaultLegacy(componentNameAnnotatePlugin);
44
+ var SentryCli__default = /*#__PURE__*/_interopDefaultLegacy(SentryCli);
45
45
  var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
46
46
  var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
47
+ var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
47
48
  var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
48
49
  var path__namespace = /*#__PURE__*/_interopNamespace(path);
49
- var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
50
- var findUp__default = /*#__PURE__*/_interopDefaultLegacy(findUp);
50
+ var dotenv__namespace = /*#__PURE__*/_interopNamespace(dotenv);
51
51
  var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
52
+ var os__namespace = /*#__PURE__*/_interopNamespace(os);
53
+ var findUp__default = /*#__PURE__*/_interopDefaultLegacy(findUp);
52
54
  var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
53
55
  var childProcess__default = /*#__PURE__*/_interopDefaultLegacy(childProcess);
54
- var util__namespace = /*#__PURE__*/_interopNamespace(util);
55
56
  var https__namespace = /*#__PURE__*/_interopNamespace(https);
56
- var dotenv__namespace = /*#__PURE__*/_interopNamespace(dotenv);
57
+ var util__namespace = /*#__PURE__*/_interopNamespace(util);
57
58
 
58
59
  function ownKeys(object, enumerableOnly) {
59
60
  var keys = Object.keys(object);
@@ -445,555 +446,168 @@ function _toPropertyKey(arg) {
445
446
  return typeof key === "symbol" ? key : String(key);
446
447
  }
447
448
 
449
+ // eslint-disable-next-line @typescript-eslint/unbound-method
450
+ const objectToString = Object.prototype.toString;
451
+
448
452
  /**
449
- * Checks whether the given input is already an array, and if it isn't, wraps it in one.
453
+ * Checks whether given value's type is one of a few Error or Error-like
454
+ * {@link isError}.
450
455
  *
451
- * @param maybeArray Input to turn into an array, if necessary
452
- * @returns The input, if already an array, or an array with the input as the only element, if not
456
+ * @param wat A value to be checked.
457
+ * @returns A boolean representing the result.
453
458
  */
454
- function arrayify$1(maybeArray) {
455
- return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
459
+ function isError(wat) {
460
+ switch (objectToString.call(wat)) {
461
+ case '[object Error]':
462
+ case '[object Exception]':
463
+ case '[object DOMException]':
464
+ return true;
465
+ default:
466
+ return isInstanceOf(wat, Error);
467
+ }
456
468
  }
457
469
  /**
458
- * Get the closes package.json from a given starting point upwards.
459
- * This handles a few edge cases:
460
- * * Check if a given file package.json appears to be an actual NPM package.json file
461
- * * Stop at the home dir, to avoid looking too deeply
470
+ * Checks whether given value is an instance of the given built-in class.
471
+ *
472
+ * @param wat The value to be checked
473
+ * @param className
474
+ * @returns A boolean representing the result.
462
475
  */
463
- function getPackageJson() {
464
- var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
465
- cwd = _ref.cwd,
466
- stopAt = _ref.stopAt;
467
- return lookupPackageJson(cwd !== null && cwd !== void 0 ? cwd : process.cwd(), path__default["default"].normalize(stopAt !== null && stopAt !== void 0 ? stopAt : os__default["default"].homedir()));
476
+ function isBuiltin(wat, className) {
477
+ return objectToString.call(wat) === `[object ${className}]`;
468
478
  }
469
- function parseMajorVersion(version) {
470
- // if it has a `v` prefix, remove it
471
- if (version.startsWith("v")) {
472
- version = version.slice(1);
473
- }
474
479
 
475
- // First, try simple lookup of exact, ~ and ^ versions
476
- var regex = /^[\^~]?(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
477
- var match = version.match(regex);
478
- if (match) {
479
- return parseInt(match[1], 10);
480
- }
481
-
482
- // Try to parse e.g. 1.x
483
- var coerced = parseInt(version, 10);
484
- if (!Number.isNaN(coerced)) {
485
- return coerced;
486
- }
487
-
488
- // Match <= and >= ranges.
489
- var gteLteRegex = /^[<>]=\s*(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
490
- var gteLteMatch = version.match(gteLteRegex);
491
- if (gteLteMatch) {
492
- return parseInt(gteLteMatch[1], 10);
493
- }
494
-
495
- // match < ranges
496
- var ltRegex = /^<\s*(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
497
- var ltMatch = version.match(ltRegex);
498
- if (ltMatch) {
499
- // Two scenarios:
500
- // a) < 2.0.0 --> return 1
501
- // b) < 2.1.0 --> return 2
502
-
503
- var major = parseInt(ltMatch[1], 10);
504
- if (
505
- // minor version > 0
506
- typeof ltMatch[2] === "string" && parseInt(ltMatch[2].slice(1), 10) > 0 ||
507
- // patch version > 0
508
- typeof ltMatch[3] === "string" && parseInt(ltMatch[3].slice(1), 10) > 0) {
509
- return major;
510
- }
511
- return major - 1;
512
- }
513
-
514
- // match > ranges
515
- var gtRegex = /^>\s*(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
516
- var gtMatch = version.match(gtRegex);
517
- if (gtMatch) {
518
- // We always return the version here, even though it _may_ be incorrect
519
- // E.g. if given > 2.0.0, it should be 2 if there exists any 2.x.x version, else 3
520
- // Since there is no way for us to know this, we're going to assume any kind of patch/feature release probably exists
521
- return parseInt(gtMatch[1], 10);
522
- }
523
- return undefined;
480
+ /**
481
+ * Checks whether given value's type is ErrorEvent
482
+ * {@link isErrorEvent}.
483
+ *
484
+ * @param wat A value to be checked.
485
+ * @returns A boolean representing the result.
486
+ */
487
+ function isErrorEvent$1(wat) {
488
+ return isBuiltin(wat, 'ErrorEvent');
524
489
  }
525
490
 
526
- // This is an explicit list of packages where we want to include the (major) version number.
527
- var PACKAGES_TO_INCLUDE_VERSION = ["react", "@angular/core", "vue", "ember-source", "svelte", "@sveltejs/kit", "webpack", "vite", "gatsby", "next", "remix", "rollup", "esbuild"];
528
- function getDependencies(packageJson) {
529
- var _packageJson$devDepen, _packageJson$dependen;
530
- var dependencies = Object.assign({}, (_packageJson$devDepen = packageJson["devDependencies"]) !== null && _packageJson$devDepen !== void 0 ? _packageJson$devDepen : {}, (_packageJson$dependen = packageJson["dependencies"]) !== null && _packageJson$dependen !== void 0 ? _packageJson$dependen : {});
531
- var deps = Object.keys(dependencies).sort();
532
- var depsVersions = deps.reduce(function (depsVersions, depName) {
533
- if (PACKAGES_TO_INCLUDE_VERSION.includes(depName)) {
534
- var version = dependencies[depName];
535
- var majorVersion = parseMajorVersion(version);
536
- if (majorVersion) {
537
- depsVersions[depName] = majorVersion;
538
- }
539
- }
540
- return depsVersions;
541
- }, {});
542
- return {
543
- deps: deps,
544
- depsVersions: depsVersions
545
- };
491
+ /**
492
+ * Checks whether given value's type is a string
493
+ * {@link isString}.
494
+ *
495
+ * @param wat A value to be checked.
496
+ * @returns A boolean representing the result.
497
+ */
498
+ function isString(wat) {
499
+ return isBuiltin(wat, 'String');
546
500
  }
547
- function lookupPackageJson(cwd, stopAt) {
548
- var jsonPath = findUp__default["default"].sync(function (dirName) {
549
- // Stop if we reach this dir
550
- if (path__default["default"].normalize(dirName) === stopAt) {
551
- return findUp__default["default"].stop;
552
- }
553
- return findUp__default["default"].sync.exists(dirName + "/package.json") ? "package.json" : undefined;
554
- }, {
555
- cwd: cwd
556
- });
557
- if (!jsonPath) {
558
- return undefined;
559
- }
560
- try {
561
- var jsonStr = fs__default["default"].readFileSync(jsonPath, "utf8");
562
- var json = JSON.parse(jsonStr);
563
-
564
- // Ensure it is an actual package.json
565
- // This is very much not bulletproof, but should be good enough
566
- if ("name" in json || "private" in json) {
567
- return json;
568
- }
569
- } catch (error) {
570
- // Ignore and walk up
571
- }
572
501
 
573
- // Continue up the tree, if we find a fitting package.json
574
- var newCwd = path__default["default"].dirname(path__default["default"].resolve(jsonPath + "/.."));
575
- return lookupPackageJson(newCwd, stopAt);
502
+ /**
503
+ * Checks whether given string is parameterized
504
+ * {@link isParameterizedString}.
505
+ *
506
+ * @param wat A value to be checked.
507
+ * @returns A boolean representing the result.
508
+ */
509
+ function isParameterizedString(wat) {
510
+ return (
511
+ typeof wat === 'object' &&
512
+ wat !== null &&
513
+ '__sentry_template_string__' in wat &&
514
+ '__sentry_template_values__' in wat
515
+ );
576
516
  }
577
517
 
578
518
  /**
579
- * Deterministically hashes a string and turns the hash into a uuid.
519
+ * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)
520
+ * {@link isPrimitive}.
521
+ *
522
+ * @param wat A value to be checked.
523
+ * @returns A boolean representing the result.
580
524
  */
581
- function stringToUUID(str) {
582
- var sha256Hash = crypto__default["default"].createHash("sha256").update(str).digest("hex");
525
+ function isPrimitive(wat) {
526
+ return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');
527
+ }
583
528
 
584
- // Position 16 is fixed to either 8, 9, a, or b in the uuid v4 spec (10xx in binary)
585
- // RFC 4122 section 4.4
586
- var v4variant = ["8", "9", "a", "b"][sha256Hash.substring(16, 17).charCodeAt(0) % 4];
587
- return (sha256Hash.substring(0, 8) + "-" + sha256Hash.substring(8, 12) + "-4" + sha256Hash.substring(13, 16) + "-" + v4variant + sha256Hash.substring(17, 20) + "-" + sha256Hash.substring(20, 32)).toLowerCase();
529
+ /**
530
+ * Checks whether given value's type is an object literal, or a class instance.
531
+ * {@link isPlainObject}.
532
+ *
533
+ * @param wat A value to be checked.
534
+ * @returns A boolean representing the result.
535
+ */
536
+ function isPlainObject(wat) {
537
+ return isBuiltin(wat, 'Object');
588
538
  }
589
- function gitRevision() {
590
- var gitRevision;
591
- try {
592
- gitRevision = childProcess__default["default"].execSync("git rev-parse HEAD", {
593
- stdio: ["ignore", "pipe", "ignore"]
594
- }).toString().trim();
595
- } catch (e) {
596
- // noop
597
- }
598
- return gitRevision;
539
+
540
+ /**
541
+ * Checks whether given value's type is an Event instance
542
+ * {@link isEvent}.
543
+ *
544
+ * @param wat A value to be checked.
545
+ * @returns A boolean representing the result.
546
+ */
547
+ function isEvent(wat) {
548
+ return typeof Event !== 'undefined' && isInstanceOf(wat, Event);
599
549
  }
600
550
 
601
551
  /**
602
- * Tries to guess a release name based on environmental data.
552
+ * Checks whether given value's type is an Element instance
553
+ * {@link isElement}.
554
+ *
555
+ * @param wat A value to be checked.
556
+ * @returns A boolean representing the result.
603
557
  */
604
- function determineReleaseName() {
605
- // This list is in approximate alpha order, separated into 3 categories:
606
- // 1. Git providers
607
- // 2. CI providers with specific environment variables (has the provider name in the variable name)
608
- // 3. CI providers with generic environment variables (checked for last to prevent possible false positives)
609
-
610
- var possibleReleaseNameOfGitProvider =
611
- // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables
612
- process.env["GITHUB_SHA"] ||
613
- // GitLab CI - https://docs.gitlab.com/ee/ci/variables/predefined_variables.html
614
- process.env["CI_MERGE_REQUEST_SOURCE_BRANCH_SHA"] || process.env["CI_BUILD_REF"] || process.env["CI_COMMIT_SHA"] ||
615
- // Bitbucket - https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets/
616
- process.env["BITBUCKET_COMMIT"];
617
- var possibleReleaseNameOfCiProvidersWithSpecificEnvVar =
618
- // AppVeyor - https://www.appveyor.com/docs/environment-variables/
619
- process.env["APPVEYOR_PULL_REQUEST_HEAD_COMMIT"] || process.env["APPVEYOR_REPO_COMMIT"] ||
620
- // AWS CodeBuild - https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html
621
- process.env["CODEBUILD_RESOLVED_SOURCE_VERSION"] ||
622
- // AWS Amplify - https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html
623
- process.env["AWS_COMMIT_ID"] ||
624
- // Azure Pipelines - https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml
625
- process.env["BUILD_SOURCEVERSION"] ||
626
- // Bitrise - https://devcenter.bitrise.io/builds/available-environment-variables/
627
- process.env["GIT_CLONE_COMMIT_HASH"] ||
628
- // Buddy CI - https://buddy.works/docs/pipelines/environment-variables#default-environment-variables
629
- process.env["BUDDY_EXECUTION_REVISION"] ||
630
- // Builtkite - https://buildkite.com/docs/pipelines/environment-variables
631
- process.env["BUILDKITE_COMMIT"] ||
632
- // CircleCI - https://circleci.com/docs/variables/
633
- process.env["CIRCLE_SHA1"] ||
634
- // Cirrus CI - https://cirrus-ci.org/guide/writing-tasks/#environment-variables
635
- process.env["CIRRUS_CHANGE_IN_REPO"] ||
636
- // Codefresh - https://codefresh.io/docs/docs/codefresh-yaml/variables/
637
- process.env["CF_REVISION"] ||
638
- // Codemagic - https://docs.codemagic.io/yaml-basic-configuration/environment-variables/
639
- process.env["CM_COMMIT"] ||
640
- // Cloudflare Pages - https://developers.cloudflare.com/pages/platform/build-configuration/#environment-variables
641
- process.env["CF_PAGES_COMMIT_SHA"] ||
642
- // Drone - https://docs.drone.io/pipeline/environment/reference/
643
- process.env["DRONE_COMMIT_SHA"] ||
644
- // Flightcontrol - https://www.flightcontrol.dev/docs/guides/flightcontrol/environment-variables#built-in-environment-variables
645
- process.env["FC_GIT_COMMIT_SHA"] ||
646
- // Heroku #1 https://devcenter.heroku.com/articles/heroku-ci
647
- process.env["HEROKU_TEST_RUN_COMMIT_VERSION"] ||
648
- // Heroku #2 https://docs.sentry.io/product/integrations/deployment/heroku/#configure-releases
649
- process.env["HEROKU_SLUG_COMMIT"] ||
650
- // Railway - https://docs.railway.app/reference/variables#git-variables
651
- process.env["RAILWAY_GIT_COMMIT_SHA"] ||
652
- // Render - https://render.com/docs/environment-variables
653
- process.env["RENDER_GIT_COMMIT"] ||
654
- // Semaphore CI - https://docs.semaphoreci.com/ci-cd-environment/environment-variables
655
- process.env["SEMAPHORE_GIT_SHA"] ||
656
- // TravisCI - https://docs.travis-ci.com/user/environment-variables/#default-environment-variables
657
- process.env["TRAVIS_PULL_REQUEST_SHA"] ||
658
- // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables
659
- process.env["VERCEL_GIT_COMMIT_SHA"] || process.env["VERCEL_GITHUB_COMMIT_SHA"] || process.env["VERCEL_GITLAB_COMMIT_SHA"] || process.env["VERCEL_BITBUCKET_COMMIT_SHA"] ||
660
- // Zeit (now known as Vercel)
661
- process.env["ZEIT_GITHUB_COMMIT_SHA"] || process.env["ZEIT_GITLAB_COMMIT_SHA"] || process.env["ZEIT_BITBUCKET_COMMIT_SHA"];
662
- var possibleReleaseNameOfCiProvidersWithGenericEnvVar =
663
- // CloudBees CodeShip - https://docs.cloudbees.com/docs/cloudbees-codeship/latest/pro-builds-and-configuration/environment-variables
664
- process.env["CI_COMMIT_ID"] ||
665
- // Coolify - https://coolify.io/docs/knowledge-base/environment-variables
666
- process.env["SOURCE_COMMIT"] ||
667
- // Heroku #3 https://devcenter.heroku.com/changelog-items/630
668
- process.env["SOURCE_VERSION"] ||
669
- // Jenkins - https://plugins.jenkins.io/git/#environment-variables
670
- process.env["GIT_COMMIT"] ||
671
- // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata
672
- process.env["COMMIT_REF"] ||
673
- // TeamCity - https://www.jetbrains.com/help/teamcity/predefined-build-parameters.html
674
- process.env["BUILD_VCS_NUMBER"] ||
675
- // Woodpecker CI - https://woodpecker-ci.org/docs/usage/environment
676
- process.env["CI_COMMIT_SHA"];
677
- return possibleReleaseNameOfGitProvider || possibleReleaseNameOfCiProvidersWithSpecificEnvVar || possibleReleaseNameOfCiProvidersWithGenericEnvVar || gitRevision();
678
- }
558
+ function isElement(wat) {
559
+ return typeof Element !== 'undefined' && isInstanceOf(wat, Element);
560
+ }
679
561
 
680
562
  /**
681
- * Generates code for the global injector which is responsible for setting the global
682
- * `SENTRY_RELEASE` & `SENTRY_BUILD_INFO` variables.
563
+ * Checks whether given value has a then function.
564
+ * @param wat A value to be checked.
683
565
  */
684
- function generateGlobalInjectorCode(_ref2) {
685
- var release = _ref2.release,
686
- injectBuildInformation = _ref2.injectBuildInformation;
687
- // The code below is mostly ternary operators because it saves bundle size.
688
- // The checks are to support as many environments as possible. (Node.js, Browser, webworkers, etc.)
689
- var code = "{\n let _global =\n typeof window !== 'undefined' ?\n window :\n typeof global !== 'undefined' ?\n global :\n typeof globalThis !== 'undefined' ?\n globalThis :\n typeof self !== 'undefined' ?\n self :\n {};\n\n _global.SENTRY_RELEASE={id:".concat(JSON.stringify(release), "};");
690
- if (injectBuildInformation) {
691
- var buildInfo = getBuildInformation$1();
692
- code += "\n _global.SENTRY_BUILD_INFO=".concat(JSON.stringify(buildInfo), ";");
693
- }
694
- code += "}";
695
- return code;
696
- }
697
-
698
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
699
- function generateModuleMetadataInjectorCode(metadata) {
700
- // The code below is mostly ternary operators because it saves bundle size.
701
- // The checks are to support as many environments as possible. (Node.js, Browser, webworkers, etc.)
702
- // We are merging the metadata objects in case modules are bundled twice with the plugin
703
- return "{\n let _sentryModuleMetadataGlobal =\n typeof window !== \"undefined\"\n ? window\n : typeof global !== \"undefined\"\n ? global\n : typeof globalThis !== \"undefined\"\n ? globalThis\n : typeof self !== \"undefined\"\n ? self\n : {};\n\n _sentryModuleMetadataGlobal._sentryModuleMetadata =\n _sentryModuleMetadataGlobal._sentryModuleMetadata || {};\n\n _sentryModuleMetadataGlobal._sentryModuleMetadata[new _sentryModuleMetadataGlobal.Error().stack] =\n Object.assign(\n {},\n _sentryModuleMetadataGlobal._sentryModuleMetadata[new _sentryModuleMetadataGlobal.Error().stack],\n ".concat(JSON.stringify(metadata), "\n );\n}");
704
- }
705
- function getBuildInformation$1() {
706
- var packageJson = getPackageJson();
707
- var _ref3 = packageJson ? getDependencies(packageJson) : {
708
- deps: [],
709
- depsVersions: {}
710
- },
711
- deps = _ref3.deps,
712
- depsVersions = _ref3.depsVersions;
713
- return {
714
- deps: deps,
715
- depsVersions: depsVersions,
716
- nodeVersion: parseMajorVersion(process.version)
717
- };
718
- }
719
- function stripQueryAndHashFromPath(path) {
720
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
721
- return path.split("?")[0].split("#")[0];
722
- }
723
- function replaceBooleanFlagsInCode(code, replacementValues) {
724
- var ms = new MagicString__default["default"](code);
725
- Object.keys(replacementValues).forEach(function (key) {
726
- var value = replacementValues[key];
727
- if (typeof value === "boolean") {
728
- ms.replaceAll(key, JSON.stringify(value));
729
- }
730
- });
731
- if (ms.hasChanged()) {
732
- return {
733
- code: ms.toString(),
734
- map: ms.generateMap({
735
- hires: "boundary"
736
- })
737
- };
738
- }
739
- return null;
740
- }
741
-
742
- var SENTRY_SAAS_URL = "https://sentry.io";
743
- function normalizeUserOptions(userOptions) {
744
- var _userOptions$org, _userOptions$project, _userOptions$authToke, _ref, _userOptions$url, _userOptions$debug, _userOptions$silent, _userOptions$telemetr, _userOptions$disable, _ref2, _userOptions$release$, _userOptions$release, _userOptions$release$2, _userOptions$release2, _userOptions$release$3, _userOptions$release3, _userOptions$release$4, _userOptions$release4, _ref3, _userOptions$release$5, _userOptions$release5, _userOptions$release6, _userOptions$_metaOpt, _userOptions$_metaOpt2, _userOptions$_experim;
745
- var options = {
746
- org: (_userOptions$org = userOptions.org) !== null && _userOptions$org !== void 0 ? _userOptions$org : process.env["SENTRY_ORG"],
747
- project: (_userOptions$project = userOptions.project) !== null && _userOptions$project !== void 0 ? _userOptions$project : process.env["SENTRY_PROJECT"],
748
- authToken: (_userOptions$authToke = userOptions.authToken) !== null && _userOptions$authToke !== void 0 ? _userOptions$authToke : process.env["SENTRY_AUTH_TOKEN"],
749
- url: (_ref = (_userOptions$url = userOptions.url) !== null && _userOptions$url !== void 0 ? _userOptions$url : process.env["SENTRY_URL"]) !== null && _ref !== void 0 ? _ref : SENTRY_SAAS_URL,
750
- headers: userOptions.headers,
751
- debug: (_userOptions$debug = userOptions.debug) !== null && _userOptions$debug !== void 0 ? _userOptions$debug : false,
752
- silent: (_userOptions$silent = userOptions.silent) !== null && _userOptions$silent !== void 0 ? _userOptions$silent : false,
753
- errorHandler: userOptions.errorHandler,
754
- telemetry: (_userOptions$telemetr = userOptions.telemetry) !== null && _userOptions$telemetr !== void 0 ? _userOptions$telemetr : true,
755
- disable: (_userOptions$disable = userOptions.disable) !== null && _userOptions$disable !== void 0 ? _userOptions$disable : false,
756
- sourcemaps: userOptions.sourcemaps,
757
- release: _objectSpread2(_objectSpread2({}, userOptions.release), {}, {
758
- name: (_ref2 = (_userOptions$release$ = (_userOptions$release = userOptions.release) === null || _userOptions$release === void 0 ? void 0 : _userOptions$release.name) !== null && _userOptions$release$ !== void 0 ? _userOptions$release$ : process.env["SENTRY_RELEASE"]) !== null && _ref2 !== void 0 ? _ref2 : determineReleaseName(),
759
- inject: (_userOptions$release$2 = (_userOptions$release2 = userOptions.release) === null || _userOptions$release2 === void 0 ? void 0 : _userOptions$release2.inject) !== null && _userOptions$release$2 !== void 0 ? _userOptions$release$2 : true,
760
- create: (_userOptions$release$3 = (_userOptions$release3 = userOptions.release) === null || _userOptions$release3 === void 0 ? void 0 : _userOptions$release3.create) !== null && _userOptions$release$3 !== void 0 ? _userOptions$release$3 : true,
761
- finalize: (_userOptions$release$4 = (_userOptions$release4 = userOptions.release) === null || _userOptions$release4 === void 0 ? void 0 : _userOptions$release4.finalize) !== null && _userOptions$release$4 !== void 0 ? _userOptions$release$4 : true,
762
- vcsRemote: (_ref3 = (_userOptions$release$5 = (_userOptions$release5 = userOptions.release) === null || _userOptions$release5 === void 0 ? void 0 : _userOptions$release5.vcsRemote) !== null && _userOptions$release$5 !== void 0 ? _userOptions$release$5 : process.env["SENTRY_VSC_REMOTE"]) !== null && _ref3 !== void 0 ? _ref3 : "origin",
763
- setCommits: (_userOptions$release6 = userOptions.release) === null || _userOptions$release6 === void 0 ? void 0 : _userOptions$release6.setCommits
764
- }),
765
- bundleSizeOptimizations: userOptions.bundleSizeOptimizations,
766
- reactComponentAnnotation: userOptions.reactComponentAnnotation,
767
- _metaOptions: {
768
- telemetry: {
769
- metaFramework: (_userOptions$_metaOpt = userOptions._metaOptions) === null || _userOptions$_metaOpt === void 0 ? void 0 : (_userOptions$_metaOpt2 = _userOptions$_metaOpt.telemetry) === null || _userOptions$_metaOpt2 === void 0 ? void 0 : _userOptions$_metaOpt2.metaFramework
770
- }
771
- },
772
- applicationKey: userOptions.applicationKey,
773
- moduleMetadata: userOptions.moduleMetadata,
774
- _experiments: (_userOptions$_experim = userOptions._experiments) !== null && _userOptions$_experim !== void 0 ? _userOptions$_experim : {}
775
- };
776
- if (options.release.setCommits === undefined) {
777
- if (process.env["VERCEL"] && process.env["VERCEL_GIT_COMMIT_SHA"] && process.env["VERCEL_GIT_REPO_SLUG"] && process.env["VERCEL_GIT_REPO_OWNER"]) {
778
- options.release.setCommits = {
779
- shouldNotThrowOnFailure: true,
780
- commit: process.env["VERCEL_GIT_COMMIT_SHA"],
781
- previousCommit: process.env["VERCEL_GIT_PREVIOUS_SHA"],
782
- repo: "".concat(process.env["VERCEL_GIT_REPO_OWNER"], "/").concat(process.env["VERCEL_GIT_REPO_SLUG"]),
783
- ignoreEmpty: true,
784
- ignoreMissing: true
785
- };
786
- } else {
787
- options.release.setCommits = {
788
- shouldNotThrowOnFailure: true,
789
- auto: true,
790
- ignoreEmpty: true,
791
- ignoreMissing: true
792
- };
793
- }
794
- }
795
- if (options.release.deploy === undefined && process.env["VERCEL"] && process.env["VERCEL_TARGET_ENV"]) {
796
- options.release.deploy = {
797
- env: "vercel-".concat(process.env["VERCEL_TARGET_ENV"]),
798
- url: process.env["VERCEL_URL"] ? "https://".concat(process.env["VERCEL_URL"]) : undefined
799
- };
800
- }
801
- return options;
566
+ function isThenable(wat) {
567
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
568
+ return Boolean(wat && wat.then && typeof wat.then === 'function');
802
569
  }
803
570
 
804
571
  /**
805
- * Validates a few combinations of options that are not checked by Sentry CLI.
806
- *
807
- * For all other options, we can rely on Sentry CLI to validate them. In fact,
808
- * we can't validate them in the plugin because Sentry CLI might pick up options from
809
- * its config file.
810
- *
811
- * @param options the internal options
812
- * @param logger the logger
572
+ * Checks whether given value's type is a SyntheticEvent
573
+ * {@link isSyntheticEvent}.
813
574
  *
814
- * @returns `true` if the options are valid, `false` otherwise
575
+ * @param wat A value to be checked.
576
+ * @returns A boolean representing the result.
815
577
  */
816
- function validateOptions(options, logger) {
817
- var _options$release, _options$release2, _options$release3;
818
- var setCommits = (_options$release = options.release) === null || _options$release === void 0 ? void 0 : _options$release.setCommits;
819
- if (setCommits) {
820
- if (!setCommits.auto && !(setCommits.repo && setCommits.commit)) {
821
- logger.error("The `setCommits` option was specified but is missing required properties.", "Please set either `auto` or both, `repo` and `commit`.");
822
- return false;
823
- }
824
- if (setCommits.auto && setCommits.repo && setCommits) {
825
- logger.warn("The `setCommits` options includes `auto` but also `repo` and `commit`.", "Ignoring `repo` and `commit`.", "Please only set either `auto` or both, `repo` and `commit`.");
826
- }
827
- }
828
- if ((_options$release2 = options.release) !== null && _options$release2 !== void 0 && _options$release2.deploy && !((_options$release3 = options.release) !== null && _options$release3 !== void 0 && _options$release3.deploy.env)) {
829
- logger.error("The `deploy` option was specified but is missing the required `env` property.", "Please set the `env` property.");
830
- return false;
831
- }
832
- return true;
578
+ function isSyntheticEvent(wat) {
579
+ return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;
833
580
  }
834
581
 
835
- // eslint-disable-next-line @typescript-eslint/unbound-method
836
- const objectToString = Object.prototype.toString;
837
-
838
582
  /**
839
- * Checks whether given value's type is one of a few Error or Error-like
840
- * {@link isError}.
583
+ * Checks whether given value's type is an instance of provided constructor.
584
+ * {@link isInstanceOf}.
841
585
  *
842
586
  * @param wat A value to be checked.
587
+ * @param base A constructor to be used in a check.
843
588
  * @returns A boolean representing the result.
844
589
  */
845
- function isError(wat) {
846
- switch (objectToString.call(wat)) {
847
- case '[object Error]':
848
- case '[object Exception]':
849
- case '[object DOMException]':
850
- return true;
851
- default:
852
- return isInstanceOf(wat, Error);
590
+ function isInstanceOf(wat, base) {
591
+ try {
592
+ return wat instanceof base;
593
+ } catch (_e) {
594
+ return false;
853
595
  }
854
596
  }
597
+
855
598
  /**
856
- * Checks whether given value is an instance of the given built-in class.
599
+ * Checks whether given value's type is a Vue ViewModel.
857
600
  *
858
- * @param wat The value to be checked
859
- * @param className
601
+ * @param wat A value to be checked.
860
602
  * @returns A boolean representing the result.
861
603
  */
862
- function isBuiltin(wat, className) {
863
- return objectToString.call(wat) === `[object ${className}]`;
604
+ function isVueViewModel(wat) {
605
+ // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.
606
+ return !!(typeof wat === 'object' && wat !== null && ((wat ).__isVue || (wat )._isVue));
864
607
  }
865
608
 
866
609
  /**
867
- * Checks whether given value's type is ErrorEvent
868
- * {@link isErrorEvent}.
869
- *
870
- * @param wat A value to be checked.
871
- * @returns A boolean representing the result.
872
- */
873
- function isErrorEvent$1(wat) {
874
- return isBuiltin(wat, 'ErrorEvent');
875
- }
876
-
877
- /**
878
- * Checks whether given value's type is a string
879
- * {@link isString}.
880
- *
881
- * @param wat A value to be checked.
882
- * @returns A boolean representing the result.
883
- */
884
- function isString(wat) {
885
- return isBuiltin(wat, 'String');
886
- }
887
-
888
- /**
889
- * Checks whether given string is parameterized
890
- * {@link isParameterizedString}.
891
- *
892
- * @param wat A value to be checked.
893
- * @returns A boolean representing the result.
894
- */
895
- function isParameterizedString(wat) {
896
- return (
897
- typeof wat === 'object' &&
898
- wat !== null &&
899
- '__sentry_template_string__' in wat &&
900
- '__sentry_template_values__' in wat
901
- );
902
- }
903
-
904
- /**
905
- * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)
906
- * {@link isPrimitive}.
907
- *
908
- * @param wat A value to be checked.
909
- * @returns A boolean representing the result.
910
- */
911
- function isPrimitive(wat) {
912
- return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');
913
- }
914
-
915
- /**
916
- * Checks whether given value's type is an object literal, or a class instance.
917
- * {@link isPlainObject}.
918
- *
919
- * @param wat A value to be checked.
920
- * @returns A boolean representing the result.
921
- */
922
- function isPlainObject(wat) {
923
- return isBuiltin(wat, 'Object');
924
- }
925
-
926
- /**
927
- * Checks whether given value's type is an Event instance
928
- * {@link isEvent}.
929
- *
930
- * @param wat A value to be checked.
931
- * @returns A boolean representing the result.
932
- */
933
- function isEvent(wat) {
934
- return typeof Event !== 'undefined' && isInstanceOf(wat, Event);
935
- }
936
-
937
- /**
938
- * Checks whether given value's type is an Element instance
939
- * {@link isElement}.
940
- *
941
- * @param wat A value to be checked.
942
- * @returns A boolean representing the result.
943
- */
944
- function isElement(wat) {
945
- return typeof Element !== 'undefined' && isInstanceOf(wat, Element);
946
- }
947
-
948
- /**
949
- * Checks whether given value has a then function.
950
- * @param wat A value to be checked.
951
- */
952
- function isThenable(wat) {
953
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
954
- return Boolean(wat && wat.then && typeof wat.then === 'function');
955
- }
956
-
957
- /**
958
- * Checks whether given value's type is a SyntheticEvent
959
- * {@link isSyntheticEvent}.
960
- *
961
- * @param wat A value to be checked.
962
- * @returns A boolean representing the result.
963
- */
964
- function isSyntheticEvent(wat) {
965
- return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;
966
- }
967
-
968
- /**
969
- * Checks whether given value's type is an instance of provided constructor.
970
- * {@link isInstanceOf}.
971
- *
972
- * @param wat A value to be checked.
973
- * @param base A constructor to be used in a check.
974
- * @returns A boolean representing the result.
975
- */
976
- function isInstanceOf(wat, base) {
977
- try {
978
- return wat instanceof base;
979
- } catch (_e) {
980
- return false;
981
- }
982
- }
983
-
984
- /**
985
- * Checks whether given value's type is a Vue ViewModel.
986
- *
987
- * @param wat A value to be checked.
988
- * @returns A boolean representing the result.
989
- */
990
- function isVueViewModel(wat) {
991
- // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.
992
- return !!(typeof wat === 'object' && wat !== null && ((wat ).__isVue || (wat )._isVue));
993
- }
994
-
995
- /**
996
- * Truncates given string to the maximum characters count
610
+ * Truncates given string to the maximum characters count
997
611
  *
998
612
  * @param str An object that contains serializable values
999
613
  * @param max Maximum number of characters in truncated string (0 = unlimited)
@@ -2105,7 +1719,7 @@ function checkOrSetAlreadyCaught(exception) {
2105
1719
  * @param maybeArray Input to turn into an array, if necessary
2106
1720
  * @returns The input, if already an array, or an array with the input as the only element, if not
2107
1721
  */
2108
- function arrayify(maybeArray) {
1722
+ function arrayify$1(maybeArray) {
2109
1723
  return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
2110
1724
  }
2111
1725
 
@@ -6225,7 +5839,7 @@ function applySpanToEvent(event, span) {
6225
5839
  */
6226
5840
  function applyFingerprintToEvent(event, fingerprint) {
6227
5841
  // Make sure it's an array first and we actually have something in place
6228
- event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];
5842
+ event.fingerprint = event.fingerprint ? arrayify$1(event.fingerprint) : [];
6229
5843
 
6230
5844
  // If we have something on the scope, then merge it with event
6231
5845
  if (fingerprint) {
@@ -7952,48 +7566,490 @@ function createTransport(
7952
7566
  );
7953
7567
  }
7954
7568
 
7955
- return {
7956
- send,
7957
- flush,
7958
- };
7569
+ return {
7570
+ send,
7571
+ flush,
7572
+ };
7573
+ }
7574
+
7575
+ function getEventForEnvelopeItem(item, type) {
7576
+ if (type !== 'event' && type !== 'transaction') {
7577
+ return undefined;
7578
+ }
7579
+
7580
+ return Array.isArray(item) ? (item )[1] : undefined;
7581
+ }
7582
+
7583
+ /**
7584
+ * A builder for the SDK metadata in the options for the SDK initialization.
7585
+ *
7586
+ * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.
7587
+ * We don't extract it for bundle size reasons.
7588
+ * @see https://github.com/getsentry/sentry-javascript/pull/7404
7589
+ * @see https://github.com/getsentry/sentry-javascript/pull/4196
7590
+ *
7591
+ * If you make changes to this function consider updating the others as well.
7592
+ *
7593
+ * @param options SDK options object that gets mutated
7594
+ * @param names list of package names
7595
+ */
7596
+ function applySdkMetadata(options, name, names = [name], source = 'npm') {
7597
+ const metadata = options._metadata || {};
7598
+
7599
+ if (!metadata.sdk) {
7600
+ metadata.sdk = {
7601
+ name: `sentry.javascript.${name}`,
7602
+ packages: names.map(name => ({
7603
+ name: `${source}:@sentry/${name}`,
7604
+ version: SDK_VERSION,
7605
+ })),
7606
+ version: SDK_VERSION,
7607
+ };
7608
+ }
7609
+
7610
+ options._metadata = metadata;
7611
+ }
7612
+
7613
+ /**
7614
+ * Checks whether the given input is already an array, and if it isn't, wraps it in one.
7615
+ *
7616
+ * @param maybeArray Input to turn into an array, if necessary
7617
+ * @returns The input, if already an array, or an array with the input as the only element, if not
7618
+ */
7619
+ function arrayify(maybeArray) {
7620
+ return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
7621
+ }
7622
+ /**
7623
+ * Get the closes package.json from a given starting point upwards.
7624
+ * This handles a few edge cases:
7625
+ * * Check if a given file package.json appears to be an actual NPM package.json file
7626
+ * * Stop at the home dir, to avoid looking too deeply
7627
+ */
7628
+ function getPackageJson() {
7629
+ var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
7630
+ cwd = _ref.cwd,
7631
+ stopAt = _ref.stopAt;
7632
+ return lookupPackageJson(cwd !== null && cwd !== void 0 ? cwd : process.cwd(), path__default["default"].normalize(stopAt !== null && stopAt !== void 0 ? stopAt : os__default["default"].homedir()));
7633
+ }
7634
+ function parseMajorVersion(version) {
7635
+ // if it has a `v` prefix, remove it
7636
+ if (version.startsWith("v")) {
7637
+ version = version.slice(1);
7638
+ }
7639
+
7640
+ // First, try simple lookup of exact, ~ and ^ versions
7641
+ var regex = /^[\^~]?(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
7642
+ var match = version.match(regex);
7643
+ if (match) {
7644
+ return parseInt(match[1], 10);
7645
+ }
7646
+
7647
+ // Try to parse e.g. 1.x
7648
+ var coerced = parseInt(version, 10);
7649
+ if (!Number.isNaN(coerced)) {
7650
+ return coerced;
7651
+ }
7652
+
7653
+ // Match <= and >= ranges.
7654
+ var gteLteRegex = /^[<>]=\s*(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
7655
+ var gteLteMatch = version.match(gteLteRegex);
7656
+ if (gteLteMatch) {
7657
+ return parseInt(gteLteMatch[1], 10);
7658
+ }
7659
+
7660
+ // match < ranges
7661
+ var ltRegex = /^<\s*(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
7662
+ var ltMatch = version.match(ltRegex);
7663
+ if (ltMatch) {
7664
+ // Two scenarios:
7665
+ // a) < 2.0.0 --> return 1
7666
+ // b) < 2.1.0 --> return 2
7667
+
7668
+ var major = parseInt(ltMatch[1], 10);
7669
+ if (
7670
+ // minor version > 0
7671
+ typeof ltMatch[2] === "string" && parseInt(ltMatch[2].slice(1), 10) > 0 ||
7672
+ // patch version > 0
7673
+ typeof ltMatch[3] === "string" && parseInt(ltMatch[3].slice(1), 10) > 0) {
7674
+ return major;
7675
+ }
7676
+ return major - 1;
7677
+ }
7678
+
7679
+ // match > ranges
7680
+ var gtRegex = /^>\s*(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
7681
+ var gtMatch = version.match(gtRegex);
7682
+ if (gtMatch) {
7683
+ // We always return the version here, even though it _may_ be incorrect
7684
+ // E.g. if given > 2.0.0, it should be 2 if there exists any 2.x.x version, else 3
7685
+ // Since there is no way for us to know this, we're going to assume any kind of patch/feature release probably exists
7686
+ return parseInt(gtMatch[1], 10);
7687
+ }
7688
+ return undefined;
7689
+ }
7690
+
7691
+ // This is an explicit list of packages where we want to include the (major) version number.
7692
+ var PACKAGES_TO_INCLUDE_VERSION = ["react", "@angular/core", "vue", "ember-source", "svelte", "@sveltejs/kit", "webpack", "vite", "gatsby", "next", "remix", "rollup", "esbuild"];
7693
+ function getDependencies(packageJson) {
7694
+ var _packageJson$devDepen, _packageJson$dependen;
7695
+ var dependencies = Object.assign({}, (_packageJson$devDepen = packageJson["devDependencies"]) !== null && _packageJson$devDepen !== void 0 ? _packageJson$devDepen : {}, (_packageJson$dependen = packageJson["dependencies"]) !== null && _packageJson$dependen !== void 0 ? _packageJson$dependen : {});
7696
+ var deps = Object.keys(dependencies).sort();
7697
+ var depsVersions = deps.reduce(function (depsVersions, depName) {
7698
+ if (PACKAGES_TO_INCLUDE_VERSION.includes(depName)) {
7699
+ var version = dependencies[depName];
7700
+ var majorVersion = parseMajorVersion(version);
7701
+ if (majorVersion) {
7702
+ depsVersions[depName] = majorVersion;
7703
+ }
7704
+ }
7705
+ return depsVersions;
7706
+ }, {});
7707
+ return {
7708
+ deps: deps,
7709
+ depsVersions: depsVersions
7710
+ };
7711
+ }
7712
+ function lookupPackageJson(cwd, stopAt) {
7713
+ var jsonPath = findUp__default["default"].sync(function (dirName) {
7714
+ // Stop if we reach this dir
7715
+ if (path__default["default"].normalize(dirName) === stopAt) {
7716
+ return findUp__default["default"].stop;
7717
+ }
7718
+ return findUp__default["default"].sync.exists(dirName + "/package.json") ? "package.json" : undefined;
7719
+ }, {
7720
+ cwd: cwd
7721
+ });
7722
+ if (!jsonPath) {
7723
+ return undefined;
7724
+ }
7725
+ try {
7726
+ var jsonStr = fs__default["default"].readFileSync(jsonPath, "utf8");
7727
+ var json = JSON.parse(jsonStr);
7728
+
7729
+ // Ensure it is an actual package.json
7730
+ // This is very much not bulletproof, but should be good enough
7731
+ if ("name" in json || "private" in json) {
7732
+ return json;
7733
+ }
7734
+ } catch (error) {
7735
+ // Ignore and walk up
7736
+ }
7737
+
7738
+ // Continue up the tree, if we find a fitting package.json
7739
+ var newCwd = path__default["default"].dirname(path__default["default"].resolve(jsonPath + "/.."));
7740
+ return lookupPackageJson(newCwd, stopAt);
7741
+ }
7742
+
7743
+ /**
7744
+ * Deterministically hashes a string and turns the hash into a uuid.
7745
+ */
7746
+ function stringToUUID(str) {
7747
+ var sha256Hash = crypto__default["default"].createHash("sha256").update(str).digest("hex");
7748
+
7749
+ // Position 16 is fixed to either 8, 9, a, or b in the uuid v4 spec (10xx in binary)
7750
+ // RFC 4122 section 4.4
7751
+ var v4variant = ["8", "9", "a", "b"][sha256Hash.substring(16, 17).charCodeAt(0) % 4];
7752
+ return (sha256Hash.substring(0, 8) + "-" + sha256Hash.substring(8, 12) + "-4" + sha256Hash.substring(13, 16) + "-" + v4variant + sha256Hash.substring(17, 20) + "-" + sha256Hash.substring(20, 32)).toLowerCase();
7753
+ }
7754
+ function gitRevision() {
7755
+ var gitRevision;
7756
+ try {
7757
+ gitRevision = childProcess__default["default"].execSync("git rev-parse HEAD", {
7758
+ stdio: ["ignore", "pipe", "ignore"]
7759
+ }).toString().trim();
7760
+ } catch (e) {
7761
+ // noop
7762
+ }
7763
+ return gitRevision;
7764
+ }
7765
+
7766
+ /**
7767
+ * Tries to guess a release name based on environmental data.
7768
+ */
7769
+ function determineReleaseName() {
7770
+ // This list is in approximate alpha order, separated into 3 categories:
7771
+ // 1. Git providers
7772
+ // 2. CI providers with specific environment variables (has the provider name in the variable name)
7773
+ // 3. CI providers with generic environment variables (checked for last to prevent possible false positives)
7774
+
7775
+ var possibleReleaseNameOfGitProvider =
7776
+ // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables
7777
+ process.env["GITHUB_SHA"] ||
7778
+ // GitLab CI - https://docs.gitlab.com/ee/ci/variables/predefined_variables.html
7779
+ process.env["CI_MERGE_REQUEST_SOURCE_BRANCH_SHA"] || process.env["CI_BUILD_REF"] || process.env["CI_COMMIT_SHA"] ||
7780
+ // Bitbucket - https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets/
7781
+ process.env["BITBUCKET_COMMIT"];
7782
+ var possibleReleaseNameOfCiProvidersWithSpecificEnvVar =
7783
+ // AppVeyor - https://www.appveyor.com/docs/environment-variables/
7784
+ process.env["APPVEYOR_PULL_REQUEST_HEAD_COMMIT"] || process.env["APPVEYOR_REPO_COMMIT"] ||
7785
+ // AWS CodeBuild - https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html
7786
+ process.env["CODEBUILD_RESOLVED_SOURCE_VERSION"] ||
7787
+ // AWS Amplify - https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html
7788
+ process.env["AWS_COMMIT_ID"] ||
7789
+ // Azure Pipelines - https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml
7790
+ process.env["BUILD_SOURCEVERSION"] ||
7791
+ // Bitrise - https://devcenter.bitrise.io/builds/available-environment-variables/
7792
+ process.env["GIT_CLONE_COMMIT_HASH"] ||
7793
+ // Buddy CI - https://buddy.works/docs/pipelines/environment-variables#default-environment-variables
7794
+ process.env["BUDDY_EXECUTION_REVISION"] ||
7795
+ // Builtkite - https://buildkite.com/docs/pipelines/environment-variables
7796
+ process.env["BUILDKITE_COMMIT"] ||
7797
+ // CircleCI - https://circleci.com/docs/variables/
7798
+ process.env["CIRCLE_SHA1"] ||
7799
+ // Cirrus CI - https://cirrus-ci.org/guide/writing-tasks/#environment-variables
7800
+ process.env["CIRRUS_CHANGE_IN_REPO"] ||
7801
+ // Codefresh - https://codefresh.io/docs/docs/codefresh-yaml/variables/
7802
+ process.env["CF_REVISION"] ||
7803
+ // Codemagic - https://docs.codemagic.io/yaml-basic-configuration/environment-variables/
7804
+ process.env["CM_COMMIT"] ||
7805
+ // Cloudflare Pages - https://developers.cloudflare.com/pages/platform/build-configuration/#environment-variables
7806
+ process.env["CF_PAGES_COMMIT_SHA"] ||
7807
+ // Drone - https://docs.drone.io/pipeline/environment/reference/
7808
+ process.env["DRONE_COMMIT_SHA"] ||
7809
+ // Flightcontrol - https://www.flightcontrol.dev/docs/guides/flightcontrol/environment-variables#built-in-environment-variables
7810
+ process.env["FC_GIT_COMMIT_SHA"] ||
7811
+ // Heroku #1 https://devcenter.heroku.com/articles/heroku-ci
7812
+ process.env["HEROKU_TEST_RUN_COMMIT_VERSION"] ||
7813
+ // Heroku #2 https://docs.sentry.io/product/integrations/deployment/heroku/#configure-releases
7814
+ process.env["HEROKU_SLUG_COMMIT"] ||
7815
+ // Railway - https://docs.railway.app/reference/variables#git-variables
7816
+ process.env["RAILWAY_GIT_COMMIT_SHA"] ||
7817
+ // Render - https://render.com/docs/environment-variables
7818
+ process.env["RENDER_GIT_COMMIT"] ||
7819
+ // Semaphore CI - https://docs.semaphoreci.com/ci-cd-environment/environment-variables
7820
+ process.env["SEMAPHORE_GIT_SHA"] ||
7821
+ // TravisCI - https://docs.travis-ci.com/user/environment-variables/#default-environment-variables
7822
+ process.env["TRAVIS_PULL_REQUEST_SHA"] ||
7823
+ // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables
7824
+ process.env["VERCEL_GIT_COMMIT_SHA"] || process.env["VERCEL_GITHUB_COMMIT_SHA"] || process.env["VERCEL_GITLAB_COMMIT_SHA"] || process.env["VERCEL_BITBUCKET_COMMIT_SHA"] ||
7825
+ // Zeit (now known as Vercel)
7826
+ process.env["ZEIT_GITHUB_COMMIT_SHA"] || process.env["ZEIT_GITLAB_COMMIT_SHA"] || process.env["ZEIT_BITBUCKET_COMMIT_SHA"];
7827
+ var possibleReleaseNameOfCiProvidersWithGenericEnvVar =
7828
+ // CloudBees CodeShip - https://docs.cloudbees.com/docs/cloudbees-codeship/latest/pro-builds-and-configuration/environment-variables
7829
+ process.env["CI_COMMIT_ID"] ||
7830
+ // Coolify - https://coolify.io/docs/knowledge-base/environment-variables
7831
+ process.env["SOURCE_COMMIT"] ||
7832
+ // Heroku #3 https://devcenter.heroku.com/changelog-items/630
7833
+ process.env["SOURCE_VERSION"] ||
7834
+ // Jenkins - https://plugins.jenkins.io/git/#environment-variables
7835
+ process.env["GIT_COMMIT"] ||
7836
+ // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata
7837
+ process.env["COMMIT_REF"] ||
7838
+ // TeamCity - https://www.jetbrains.com/help/teamcity/predefined-build-parameters.html
7839
+ process.env["BUILD_VCS_NUMBER"] ||
7840
+ // Woodpecker CI - https://woodpecker-ci.org/docs/usage/environment
7841
+ process.env["CI_COMMIT_SHA"];
7842
+ return possibleReleaseNameOfGitProvider || possibleReleaseNameOfCiProvidersWithSpecificEnvVar || possibleReleaseNameOfCiProvidersWithGenericEnvVar || gitRevision();
7843
+ }
7844
+
7845
+ /**
7846
+ * Generates code for the global injector which is responsible for setting the global
7847
+ * `SENTRY_RELEASE` & `SENTRY_BUILD_INFO` variables.
7848
+ */
7849
+ function generateGlobalInjectorCode(_ref2) {
7850
+ var release = _ref2.release,
7851
+ injectBuildInformation = _ref2.injectBuildInformation;
7852
+ // The code below is mostly ternary operators because it saves bundle size.
7853
+ // The checks are to support as many environments as possible. (Node.js, Browser, webworkers, etc.)
7854
+ var code = "{\n let _global =\n typeof window !== 'undefined' ?\n window :\n typeof global !== 'undefined' ?\n global :\n typeof globalThis !== 'undefined' ?\n globalThis :\n typeof self !== 'undefined' ?\n self :\n {};\n\n _global.SENTRY_RELEASE={id:".concat(JSON.stringify(release), "};");
7855
+ if (injectBuildInformation) {
7856
+ var buildInfo = getBuildInformation$1();
7857
+ code += "\n _global.SENTRY_BUILD_INFO=".concat(JSON.stringify(buildInfo), ";");
7858
+ }
7859
+ code += "}";
7860
+ return code;
7861
+ }
7862
+
7863
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
7864
+ function generateModuleMetadataInjectorCode(metadata) {
7865
+ // The code below is mostly ternary operators because it saves bundle size.
7866
+ // The checks are to support as many environments as possible. (Node.js, Browser, webworkers, etc.)
7867
+ // We are merging the metadata objects in case modules are bundled twice with the plugin
7868
+ return "{\n let _sentryModuleMetadataGlobal =\n typeof window !== \"undefined\"\n ? window\n : typeof global !== \"undefined\"\n ? global\n : typeof globalThis !== \"undefined\"\n ? globalThis\n : typeof self !== \"undefined\"\n ? self\n : {};\n\n _sentryModuleMetadataGlobal._sentryModuleMetadata =\n _sentryModuleMetadataGlobal._sentryModuleMetadata || {};\n\n _sentryModuleMetadataGlobal._sentryModuleMetadata[new _sentryModuleMetadataGlobal.Error().stack] =\n Object.assign(\n {},\n _sentryModuleMetadataGlobal._sentryModuleMetadata[new _sentryModuleMetadataGlobal.Error().stack],\n ".concat(JSON.stringify(metadata), "\n );\n}");
7869
+ }
7870
+ function getBuildInformation$1() {
7871
+ var packageJson = getPackageJson();
7872
+ var _ref3 = packageJson ? getDependencies(packageJson) : {
7873
+ deps: [],
7874
+ depsVersions: {}
7875
+ },
7876
+ deps = _ref3.deps,
7877
+ depsVersions = _ref3.depsVersions;
7878
+ return {
7879
+ deps: deps,
7880
+ depsVersions: depsVersions,
7881
+ nodeVersion: parseMajorVersion(process.version)
7882
+ };
7883
+ }
7884
+ function stripQueryAndHashFromPath(path) {
7885
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
7886
+ return path.split("?")[0].split("#")[0];
7887
+ }
7888
+ function replaceBooleanFlagsInCode(code, replacementValues) {
7889
+ var ms = new MagicString__default["default"](code);
7890
+ Object.keys(replacementValues).forEach(function (key) {
7891
+ var value = replacementValues[key];
7892
+ if (typeof value === "boolean") {
7893
+ ms.replaceAll(key, JSON.stringify(value));
7894
+ }
7895
+ });
7896
+ if (ms.hasChanged()) {
7897
+ return {
7898
+ code: ms.toString(),
7899
+ map: ms.generateMap({
7900
+ hires: "boundary"
7901
+ })
7902
+ };
7903
+ }
7904
+ return null;
7905
+ }
7906
+
7907
+ // https://turbo.build/repo/docs/reference/system-environment-variables#environment-variables-in-tasks
7908
+ function getTurborepoEnvPassthroughWarning(envVarName) {
7909
+ return process.env["TURBO_HASH"] ? "\nYou seem to be using Turborepo, did you forget to put ".concat(envVarName, " in `passThroughEnv`? https://turbo.build/repo/docs/reference/configuration#passthroughenv") : "";
7959
7910
  }
7960
7911
 
7961
- function getEventForEnvelopeItem(item, type) {
7962
- if (type !== 'event' && type !== 'transaction') {
7963
- return undefined;
7912
+ var SENTRY_SAAS_URL = "https://sentry.io";
7913
+ function normalizeUserOptions(userOptions) {
7914
+ var _userOptions$org, _userOptions$project, _userOptions$authToke, _ref, _userOptions$url, _userOptions$debug, _userOptions$silent, _userOptions$telemetr, _userOptions$disable, _ref2, _userOptions$release$, _userOptions$release, _userOptions$release$2, _userOptions$release2, _userOptions$release$3, _userOptions$release3, _userOptions$release$4, _userOptions$release4, _ref3, _userOptions$release$5, _userOptions$release5, _userOptions$release6, _userOptions$_metaOpt, _userOptions$_metaOpt2, _userOptions$_experim;
7915
+ var options = {
7916
+ org: (_userOptions$org = userOptions.org) !== null && _userOptions$org !== void 0 ? _userOptions$org : process.env["SENTRY_ORG"],
7917
+ project: (_userOptions$project = userOptions.project) !== null && _userOptions$project !== void 0 ? _userOptions$project : process.env["SENTRY_PROJECT"],
7918
+ authToken: (_userOptions$authToke = userOptions.authToken) !== null && _userOptions$authToke !== void 0 ? _userOptions$authToke : process.env["SENTRY_AUTH_TOKEN"],
7919
+ url: (_ref = (_userOptions$url = userOptions.url) !== null && _userOptions$url !== void 0 ? _userOptions$url : process.env["SENTRY_URL"]) !== null && _ref !== void 0 ? _ref : SENTRY_SAAS_URL,
7920
+ headers: userOptions.headers,
7921
+ debug: (_userOptions$debug = userOptions.debug) !== null && _userOptions$debug !== void 0 ? _userOptions$debug : false,
7922
+ silent: (_userOptions$silent = userOptions.silent) !== null && _userOptions$silent !== void 0 ? _userOptions$silent : false,
7923
+ errorHandler: userOptions.errorHandler,
7924
+ telemetry: (_userOptions$telemetr = userOptions.telemetry) !== null && _userOptions$telemetr !== void 0 ? _userOptions$telemetr : true,
7925
+ disable: (_userOptions$disable = userOptions.disable) !== null && _userOptions$disable !== void 0 ? _userOptions$disable : false,
7926
+ sourcemaps: userOptions.sourcemaps,
7927
+ release: _objectSpread2(_objectSpread2({}, userOptions.release), {}, {
7928
+ name: (_ref2 = (_userOptions$release$ = (_userOptions$release = userOptions.release) === null || _userOptions$release === void 0 ? void 0 : _userOptions$release.name) !== null && _userOptions$release$ !== void 0 ? _userOptions$release$ : process.env["SENTRY_RELEASE"]) !== null && _ref2 !== void 0 ? _ref2 : determineReleaseName(),
7929
+ inject: (_userOptions$release$2 = (_userOptions$release2 = userOptions.release) === null || _userOptions$release2 === void 0 ? void 0 : _userOptions$release2.inject) !== null && _userOptions$release$2 !== void 0 ? _userOptions$release$2 : true,
7930
+ create: (_userOptions$release$3 = (_userOptions$release3 = userOptions.release) === null || _userOptions$release3 === void 0 ? void 0 : _userOptions$release3.create) !== null && _userOptions$release$3 !== void 0 ? _userOptions$release$3 : true,
7931
+ finalize: (_userOptions$release$4 = (_userOptions$release4 = userOptions.release) === null || _userOptions$release4 === void 0 ? void 0 : _userOptions$release4.finalize) !== null && _userOptions$release$4 !== void 0 ? _userOptions$release$4 : true,
7932
+ vcsRemote: (_ref3 = (_userOptions$release$5 = (_userOptions$release5 = userOptions.release) === null || _userOptions$release5 === void 0 ? void 0 : _userOptions$release5.vcsRemote) !== null && _userOptions$release$5 !== void 0 ? _userOptions$release$5 : process.env["SENTRY_VSC_REMOTE"]) !== null && _ref3 !== void 0 ? _ref3 : "origin",
7933
+ setCommits: (_userOptions$release6 = userOptions.release) === null || _userOptions$release6 === void 0 ? void 0 : _userOptions$release6.setCommits
7934
+ }),
7935
+ bundleSizeOptimizations: userOptions.bundleSizeOptimizations,
7936
+ reactComponentAnnotation: userOptions.reactComponentAnnotation,
7937
+ _metaOptions: {
7938
+ telemetry: {
7939
+ metaFramework: (_userOptions$_metaOpt = userOptions._metaOptions) === null || _userOptions$_metaOpt === void 0 ? void 0 : (_userOptions$_metaOpt2 = _userOptions$_metaOpt.telemetry) === null || _userOptions$_metaOpt2 === void 0 ? void 0 : _userOptions$_metaOpt2.metaFramework
7940
+ }
7941
+ },
7942
+ applicationKey: userOptions.applicationKey,
7943
+ moduleMetadata: userOptions.moduleMetadata,
7944
+ _experiments: (_userOptions$_experim = userOptions._experiments) !== null && _userOptions$_experim !== void 0 ? _userOptions$_experim : {}
7945
+ };
7946
+ if (options.release.setCommits === undefined) {
7947
+ if (process.env["VERCEL"] && process.env["VERCEL_GIT_COMMIT_SHA"] && process.env["VERCEL_GIT_REPO_SLUG"] && process.env["VERCEL_GIT_REPO_OWNER"] &&
7948
+ // We only want to set commits for the production env because Sentry becomes extremely noisy (eg on slack) for
7949
+ // preview environments because the previous commit is always the "stem" commit of the preview/PR causing Sentry
7950
+ // to notify you for other people creating PRs.
7951
+ process.env["VERCEL_TARGET_ENV"] === "production") {
7952
+ options.release.setCommits = {
7953
+ shouldNotThrowOnFailure: true,
7954
+ commit: process.env["VERCEL_GIT_COMMIT_SHA"],
7955
+ previousCommit: process.env["VERCEL_GIT_PREVIOUS_SHA"],
7956
+ repo: "".concat(process.env["VERCEL_GIT_REPO_OWNER"], "/").concat(process.env["VERCEL_GIT_REPO_SLUG"]),
7957
+ ignoreEmpty: true,
7958
+ ignoreMissing: true
7959
+ };
7960
+ } else {
7961
+ options.release.setCommits = {
7962
+ shouldNotThrowOnFailure: true,
7963
+ auto: true,
7964
+ ignoreEmpty: true,
7965
+ ignoreMissing: true
7966
+ };
7967
+ }
7964
7968
  }
7965
-
7966
- return Array.isArray(item) ? (item )[1] : undefined;
7969
+ if (options.release.deploy === undefined && process.env["VERCEL"] && process.env["VERCEL_TARGET_ENV"]) {
7970
+ options.release.deploy = {
7971
+ env: "vercel-".concat(process.env["VERCEL_TARGET_ENV"]),
7972
+ url: process.env["VERCEL_URL"] ? "https://".concat(process.env["VERCEL_URL"]) : undefined
7973
+ };
7974
+ }
7975
+ return options;
7967
7976
  }
7968
7977
 
7969
7978
  /**
7970
- * A builder for the SDK metadata in the options for the SDK initialization.
7979
+ * Validates a few combinations of options that are not checked by Sentry CLI.
7971
7980
  *
7972
- * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.
7973
- * We don't extract it for bundle size reasons.
7974
- * @see https://github.com/getsentry/sentry-javascript/pull/7404
7975
- * @see https://github.com/getsentry/sentry-javascript/pull/4196
7981
+ * For all other options, we can rely on Sentry CLI to validate them. In fact,
7982
+ * we can't validate them in the plugin because Sentry CLI might pick up options from
7983
+ * its config file.
7976
7984
  *
7977
- * If you make changes to this function consider updating the others as well.
7985
+ * @param options the internal options
7986
+ * @param logger the logger
7978
7987
  *
7979
- * @param options SDK options object that gets mutated
7980
- * @param names list of package names
7988
+ * @returns `true` if the options are valid, `false` otherwise
7981
7989
  */
7982
- function applySdkMetadata(options, name, names = [name], source = 'npm') {
7983
- const metadata = options._metadata || {};
7984
-
7985
- if (!metadata.sdk) {
7986
- metadata.sdk = {
7987
- name: `sentry.javascript.${name}`,
7988
- packages: names.map(name => ({
7989
- name: `${source}:@sentry/${name}`,
7990
- version: SDK_VERSION,
7991
- })),
7992
- version: SDK_VERSION,
7993
- };
7990
+ function validateOptions(options, logger) {
7991
+ var _options$release, _options$release2, _options$release3;
7992
+ var setCommits = (_options$release = options.release) === null || _options$release === void 0 ? void 0 : _options$release.setCommits;
7993
+ if (setCommits) {
7994
+ if (!setCommits.auto && !(setCommits.repo && setCommits.commit)) {
7995
+ logger.error("The `setCommits` option was specified but is missing required properties.", "Please set either `auto` or both, `repo` and `commit`.");
7996
+ return false;
7997
+ }
7998
+ if (setCommits.auto && setCommits.repo && setCommits) {
7999
+ logger.warn("The `setCommits` options includes `auto` but also `repo` and `commit`.", "Ignoring `repo` and `commit`.", "Please only set either `auto` or both, `repo` and `commit`.");
8000
+ }
7994
8001
  }
8002
+ if ((_options$release2 = options.release) !== null && _options$release2 !== void 0 && _options$release2.deploy && !((_options$release3 = options.release) !== null && _options$release3 !== void 0 && _options$release3.deploy.env)) {
8003
+ logger.error("The `deploy` option was specified but is missing the required `env` property.", "Please set the `env` property.");
8004
+ return false;
8005
+ }
8006
+ return true;
8007
+ }
7995
8008
 
7996
- options._metadata = metadata;
8009
+ // Logging everything to stderr not to interfere with stdout
8010
+ function createLogger(options) {
8011
+ return {
8012
+ info: function info(message) {
8013
+ if (!options.silent) {
8014
+ var _console;
8015
+ for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
8016
+ params[_key - 1] = arguments[_key];
8017
+ }
8018
+ // eslint-disable-next-line no-console
8019
+ (_console = console).info.apply(_console, ["".concat(options.prefix, " Info: ").concat(message)].concat(params));
8020
+ }
8021
+ },
8022
+ warn: function warn(message) {
8023
+ if (!options.silent) {
8024
+ var _console2;
8025
+ for (var _len2 = arguments.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
8026
+ params[_key2 - 1] = arguments[_key2];
8027
+ }
8028
+ // eslint-disable-next-line no-console
8029
+ (_console2 = console).warn.apply(_console2, ["".concat(options.prefix, " Warning: ").concat(message)].concat(params));
8030
+ }
8031
+ },
8032
+ error: function error(message) {
8033
+ if (!options.silent) {
8034
+ var _console3;
8035
+ for (var _len3 = arguments.length, params = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
8036
+ params[_key3 - 1] = arguments[_key3];
8037
+ }
8038
+ // eslint-disable-next-line no-console
8039
+ (_console3 = console).error.apply(_console3, ["".concat(options.prefix, " Error: ").concat(message)].concat(params));
8040
+ }
8041
+ },
8042
+ debug: function debug(message) {
8043
+ if (!options.silent && options.debug) {
8044
+ var _console4;
8045
+ for (var _len4 = arguments.length, params = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
8046
+ params[_key4 - 1] = arguments[_key4];
8047
+ }
8048
+ // eslint-disable-next-line no-console
8049
+ (_console4 = console).debug.apply(_console4, ["".concat(options.prefix, " Debug: ").concat(message)].concat(params));
8050
+ }
8051
+ }
8052
+ };
7997
8053
  }
7998
8054
 
7999
8055
  // Estimated maximum size for reasonable standalone event
@@ -8127,7 +8183,7 @@ function makeOptionallyEnabledNodeTransport(shouldSendTelemetry) {
8127
8183
 
8128
8184
  var SENTRY_SAAS_HOSTNAME = "sentry.io";
8129
8185
  var stackParser = createStackParser(nodeStackLineParser());
8130
- function createSentryInstance(options, shouldSendTelemetry, bundler) {
8186
+ function createSentryInstance(options, shouldSendTelemetry, buildTool) {
8131
8187
  var clientOptions = {
8132
8188
  platform: "node",
8133
8189
  runtime: {
@@ -8137,7 +8193,7 @@ function createSentryInstance(options, shouldSendTelemetry, bundler) {
8137
8193
  dsn: "https://4c2bae7d9fbc413e8f7385f55c515d51@o1.ingest.sentry.io/6690737",
8138
8194
  tracesSampleRate: 1,
8139
8195
  sampleRate: 1,
8140
- release: "3.2.4",
8196
+ release: "3.3.0-alpha.0",
8141
8197
  integrations: [],
8142
8198
  tracePropagationTargets: ["sentry.io/api"],
8143
8199
  stackParser: stackParser,
@@ -8161,13 +8217,13 @@ function createSentryInstance(options, shouldSendTelemetry, bundler) {
8161
8217
  var client = new ServerRuntimeClient(clientOptions);
8162
8218
  var scope = new Scope();
8163
8219
  scope.setClient(client);
8164
- setTelemetryDataOnScope(options, scope, bundler);
8220
+ setTelemetryDataOnScope(options, scope, buildTool);
8165
8221
  return {
8166
8222
  sentryScope: scope,
8167
8223
  sentryClient: client
8168
8224
  };
8169
8225
  }
8170
- function setTelemetryDataOnScope(options, scope, bundler) {
8226
+ function setTelemetryDataOnScope(options, scope, buildTool) {
8171
8227
  var _options$_metaOptions;
8172
8228
  var org = options.org,
8173
8229
  project = options.project,
@@ -8205,7 +8261,7 @@ function setTelemetryDataOnScope(options, scope, bundler) {
8205
8261
  scope.setTags({
8206
8262
  organization: org,
8207
8263
  project: project,
8208
- bundler: bundler
8264
+ bundler: buildTool
8209
8265
  });
8210
8266
  scope.setUser({
8211
8267
  id: org
@@ -8302,297 +8358,26 @@ function _safeFlushTelemetry() {
8302
8358
  }
8303
8359
 
8304
8360
  function createDebugIdUploadFunction(_ref) {
8305
- var assets = _ref.assets,
8306
- ignore = _ref.ignore,
8307
- logger = _ref.logger,
8308
- releaseName = _ref.releaseName,
8309
- dist = _ref.dist,
8310
- handleRecoverableError = _ref.handleRecoverableError,
8311
- sentryScope = _ref.sentryScope,
8312
- sentryClient = _ref.sentryClient,
8313
- sentryCliOptions = _ref.sentryCliOptions,
8314
- rewriteSourcesHook = _ref.rewriteSourcesHook,
8315
- createDependencyOnSourcemapFiles = _ref.createDependencyOnSourcemapFiles;
8316
- var freeGlobalDependencyOnSourcemapFiles = createDependencyOnSourcemapFiles();
8361
+ var sentryBuildPluginManager = _ref.sentryBuildPluginManager;
8317
8362
  return /*#__PURE__*/function () {
8318
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(buildArtifactPaths) {
8319
- return _regeneratorRuntime().wrap(function _callee9$(_context9) {
8320
- while (1) switch (_context9.prev = _context9.next) {
8363
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(buildArtifactPaths) {
8364
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
8365
+ while (1) switch (_context.prev = _context.next) {
8321
8366
  case 0:
8322
- _context9.next = 2;
8323
- return startSpan(
8324
- // This is `forceTransaction`ed because this span is used in dashboards in the form of indexed transactions.
8325
- {
8326
- name: "debug-id-sourcemap-upload",
8327
- scope: sentryScope,
8328
- forceTransaction: true
8329
- }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
8330
- var folderToCleanUp, freeUploadDependencyOnSourcemapFiles, tmpUploadFolder, globAssets, globResult, debugIdChunkFilePaths;
8331
- return _regeneratorRuntime().wrap(function _callee8$(_context8) {
8332
- while (1) switch (_context8.prev = _context8.next) {
8333
- case 0:
8334
- // It is possible that this writeBundle hook (which calls this function) is called multiple times in one build (for example when reusing the plugin, or when using build tooling like `@vitejs/plugin-legacy`)
8335
- // Therefore we need to actually register the execution of this hook as dependency on the sourcemap files.
8336
- freeUploadDependencyOnSourcemapFiles = createDependencyOnSourcemapFiles();
8337
- _context8.prev = 1;
8338
- _context8.next = 4;
8339
- return startSpan({
8340
- name: "mkdtemp",
8341
- scope: sentryScope
8342
- }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
8343
- return _regeneratorRuntime().wrap(function _callee$(_context) {
8344
- while (1) switch (_context.prev = _context.next) {
8345
- case 0:
8346
- _context.next = 2;
8347
- return fs__default["default"].promises.mkdtemp(path__default["default"].join(os__default["default"].tmpdir(), "sentry-bundler-plugin-upload-"));
8348
- case 2:
8349
- return _context.abrupt("return", _context.sent);
8350
- case 3:
8351
- case "end":
8352
- return _context.stop();
8353
- }
8354
- }, _callee);
8355
- })));
8356
- case 4:
8357
- tmpUploadFolder = _context8.sent;
8358
- folderToCleanUp = tmpUploadFolder;
8359
- if (assets) {
8360
- globAssets = assets;
8361
- } else {
8362
- logger.debug("No `sourcemaps.assets` option provided, falling back to uploading detected build artifacts.");
8363
- globAssets = buildArtifactPaths;
8364
- }
8365
- _context8.next = 9;
8366
- return startSpan({
8367
- name: "glob",
8368
- scope: sentryScope
8369
- }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
8370
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
8371
- while (1) switch (_context2.prev = _context2.next) {
8372
- case 0:
8373
- _context2.next = 2;
8374
- return glob.glob(globAssets, {
8375
- absolute: true,
8376
- nodir: true,
8377
- ignore: ignore
8378
- });
8379
- case 2:
8380
- return _context2.abrupt("return", _context2.sent);
8381
- case 3:
8382
- case "end":
8383
- return _context2.stop();
8384
- }
8385
- }, _callee2);
8386
- })));
8387
- case 9:
8388
- globResult = _context8.sent;
8389
- debugIdChunkFilePaths = globResult.filter(function (debugIdChunkFilePath) {
8390
- return !!stripQueryAndHashFromPath(debugIdChunkFilePath).match(/\.(js|mjs|cjs)$/);
8391
- }); // The order of the files output by glob() is not deterministic
8392
- // Ensure order within the files so that {debug-id}-{chunkIndex} coupling is consistent
8393
- debugIdChunkFilePaths.sort();
8394
- if (!(Array.isArray(assets) && assets.length === 0)) {
8395
- _context8.next = 16;
8396
- break;
8397
- }
8398
- logger.debug("Empty `sourcemaps.assets` option provided. Will not upload sourcemaps with debug ID.");
8399
- _context8.next = 23;
8400
- break;
8401
- case 16:
8402
- if (!(debugIdChunkFilePaths.length === 0)) {
8403
- _context8.next = 20;
8404
- break;
8405
- }
8406
- logger.warn("Didn't find any matching sources for debug ID upload. Please check the `sourcemaps.assets` option.");
8407
- _context8.next = 23;
8408
- break;
8409
- case 20:
8410
- _context8.next = 22;
8411
- return startSpan({
8412
- name: "prepare-bundles",
8413
- scope: sentryScope
8414
- }, /*#__PURE__*/function () {
8415
- var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(prepBundlesSpan) {
8416
- var preparationTasks, workers, worker, workerIndex, files, stats, uploadSize;
8417
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
8418
- while (1) switch (_context6.prev = _context6.next) {
8419
- case 0:
8420
- // Preparing the bundles can be a lot of work and doing it all at once has the potential of nuking the heap so
8421
- // instead we do it with a maximum of 16 concurrent workers
8422
- preparationTasks = debugIdChunkFilePaths.map(function (chunkFilePath, chunkIndex) {
8423
- return /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
8424
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
8425
- while (1) switch (_context3.prev = _context3.next) {
8426
- case 0:
8427
- _context3.next = 2;
8428
- return prepareBundleForDebugIdUpload(chunkFilePath, tmpUploadFolder, chunkIndex, logger, rewriteSourcesHook !== null && rewriteSourcesHook !== void 0 ? rewriteSourcesHook : defaultRewriteSourcesHook);
8429
- case 2:
8430
- case "end":
8431
- return _context3.stop();
8432
- }
8433
- }, _callee3);
8434
- }));
8435
- });
8436
- workers = [];
8437
- worker = /*#__PURE__*/function () {
8438
- var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
8439
- var task;
8440
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
8441
- while (1) switch (_context4.prev = _context4.next) {
8442
- case 0:
8443
- if (!(preparationTasks.length > 0)) {
8444
- _context4.next = 7;
8445
- break;
8446
- }
8447
- task = preparationTasks.shift();
8448
- if (!task) {
8449
- _context4.next = 5;
8450
- break;
8451
- }
8452
- _context4.next = 5;
8453
- return task();
8454
- case 5:
8455
- _context4.next = 0;
8456
- break;
8457
- case 7:
8458
- case "end":
8459
- return _context4.stop();
8460
- }
8461
- }, _callee4);
8462
- }));
8463
- return function worker() {
8464
- return _ref8.apply(this, arguments);
8465
- };
8466
- }();
8467
- for (workerIndex = 0; workerIndex < 16; workerIndex++) {
8468
- workers.push(worker());
8469
- }
8470
- _context6.next = 6;
8471
- return Promise.all(workers);
8472
- case 6:
8473
- _context6.next = 8;
8474
- return fs__default["default"].promises.readdir(tmpUploadFolder);
8475
- case 8:
8476
- files = _context6.sent;
8477
- stats = files.map(function (file) {
8478
- return fs__default["default"].promises.stat(path__default["default"].join(tmpUploadFolder, file));
8479
- });
8480
- _context6.next = 12;
8481
- return Promise.all(stats);
8482
- case 12:
8483
- uploadSize = _context6.sent.reduce(function (accumulator, _ref9) {
8484
- var size = _ref9.size;
8485
- return accumulator + size;
8486
- }, 0);
8487
- setMeasurement("files", files.length, "none", prepBundlesSpan);
8488
- setMeasurement("upload_size", uploadSize, "byte", prepBundlesSpan);
8489
- _context6.next = 17;
8490
- return startSpan({
8491
- name: "upload",
8492
- scope: sentryScope
8493
- }, /*#__PURE__*/function () {
8494
- var _ref10 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(uploadSpan) {
8495
- var cliInstance;
8496
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
8497
- while (1) switch (_context5.prev = _context5.next) {
8498
- case 0:
8499
- cliInstance = new SentryCli__default["default"](null, _objectSpread2(_objectSpread2({}, sentryCliOptions), {}, {
8500
- headers: _objectSpread2({
8501
- "sentry-trace": spanToTraceHeader(uploadSpan),
8502
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
8503
- baggage: dynamicSamplingContextToSentryBaggageHeader(getDynamicSamplingContextFromSpan(uploadSpan))
8504
- }, sentryCliOptions.headers)
8505
- }));
8506
- _context5.next = 3;
8507
- return cliInstance.releases.uploadSourceMaps(releaseName !== null && releaseName !== void 0 ? releaseName : "undefined",
8508
- // unfortunately this needs a value for now but it will not matter since debug IDs overpower releases anyhow
8509
- {
8510
- include: [{
8511
- paths: [tmpUploadFolder],
8512
- rewrite: false,
8513
- dist: dist
8514
- }]
8515
- });
8516
- case 3:
8517
- case "end":
8518
- return _context5.stop();
8519
- }
8520
- }, _callee5);
8521
- }));
8522
- return function (_x3) {
8523
- return _ref10.apply(this, arguments);
8524
- };
8525
- }());
8526
- case 17:
8527
- case "end":
8528
- return _context6.stop();
8529
- }
8530
- }, _callee6);
8531
- }));
8532
- return function (_x2) {
8533
- return _ref6.apply(this, arguments);
8534
- };
8535
- }());
8536
- case 22:
8537
- logger.info("Successfully uploaded source maps to Sentry");
8538
- case 23:
8539
- _context8.next = 29;
8540
- break;
8541
- case 25:
8542
- _context8.prev = 25;
8543
- _context8.t0 = _context8["catch"](1);
8544
- sentryScope.captureException('Error in "debugIdUploadPlugin" writeBundle hook');
8545
- handleRecoverableError(_context8.t0, false);
8546
- case 29:
8547
- _context8.prev = 29;
8548
- if (folderToCleanUp) {
8549
- void startSpan({
8550
- name: "cleanup",
8551
- scope: sentryScope
8552
- }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
8553
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
8554
- while (1) switch (_context7.prev = _context7.next) {
8555
- case 0:
8556
- if (!folderToCleanUp) {
8557
- _context7.next = 3;
8558
- break;
8559
- }
8560
- _context7.next = 3;
8561
- return fs__default["default"].promises.rm(folderToCleanUp, {
8562
- recursive: true,
8563
- force: true
8564
- });
8565
- case 3:
8566
- case "end":
8567
- return _context7.stop();
8568
- }
8569
- }, _callee7);
8570
- })));
8571
- }
8572
- freeGlobalDependencyOnSourcemapFiles();
8573
- freeUploadDependencyOnSourcemapFiles();
8574
- _context8.next = 35;
8575
- return safeFlushTelemetry(sentryClient);
8576
- case 35:
8577
- return _context8.finish(29);
8578
- case 36:
8579
- case "end":
8580
- return _context8.stop();
8581
- }
8582
- }, _callee8, null, [[1, 25, 29, 36]]);
8583
- })));
8367
+ _context.next = 2;
8368
+ return sentryBuildPluginManager.uploadSourcemaps(buildArtifactPaths);
8584
8369
  case 2:
8585
8370
  case "end":
8586
- return _context9.stop();
8371
+ return _context.stop();
8587
8372
  }
8588
- }, _callee9);
8373
+ }, _callee);
8589
8374
  }));
8590
8375
  return function (_x) {
8591
8376
  return _ref2.apply(this, arguments);
8592
8377
  };
8593
8378
  }();
8594
8379
  }
8595
- function prepareBundleForDebugIdUpload(_x4, _x5, _x6, _x7, _x8) {
8380
+ function prepareBundleForDebugIdUpload(_x2, _x3, _x4, _x5, _x6) {
8596
8381
  return _prepareBundleForDebugIdUpload.apply(this, arguments);
8597
8382
  }
8598
8383
 
@@ -8603,66 +8388,66 @@ function prepareBundleForDebugIdUpload(_x4, _x5, _x6, _x7, _x8) {
8603
8388
  * The string pattern is injected via the debug ID injection snipped.
8604
8389
  */
8605
8390
  function _prepareBundleForDebugIdUpload() {
8606
- _prepareBundleForDebugIdUpload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(bundleFilePath, uploadFolder, chunkIndex, logger, rewriteSourcesHook) {
8391
+ _prepareBundleForDebugIdUpload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(bundleFilePath, uploadFolder, chunkIndex, logger, rewriteSourcesHook) {
8607
8392
  var bundleContent, debugId, uniqueUploadName, writeSourceFilePromise, writeSourceMapFilePromise;
8608
- return _regeneratorRuntime().wrap(function _callee11$(_context11) {
8609
- while (1) switch (_context11.prev = _context11.next) {
8393
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
8394
+ while (1) switch (_context3.prev = _context3.next) {
8610
8395
  case 0:
8611
- _context11.prev = 0;
8612
- _context11.next = 3;
8396
+ _context3.prev = 0;
8397
+ _context3.next = 3;
8613
8398
  return util.promisify(fs__default["default"].readFile)(bundleFilePath, "utf8");
8614
8399
  case 3:
8615
- bundleContent = _context11.sent;
8616
- _context11.next = 10;
8400
+ bundleContent = _context3.sent;
8401
+ _context3.next = 10;
8617
8402
  break;
8618
8403
  case 6:
8619
- _context11.prev = 6;
8620
- _context11.t0 = _context11["catch"](0);
8621
- logger.error("Could not read bundle to determine debug ID and source map: ".concat(bundleFilePath), _context11.t0);
8622
- return _context11.abrupt("return");
8404
+ _context3.prev = 6;
8405
+ _context3.t0 = _context3["catch"](0);
8406
+ logger.error("Could not read bundle to determine debug ID and source map: ".concat(bundleFilePath), _context3.t0);
8407
+ return _context3.abrupt("return");
8623
8408
  case 10:
8624
8409
  debugId = determineDebugIdFromBundleSource(bundleContent);
8625
8410
  if (!(debugId === undefined)) {
8626
- _context11.next = 14;
8411
+ _context3.next = 14;
8627
8412
  break;
8628
8413
  }
8629
8414
  logger.debug("Could not determine debug ID from bundle. This can happen if you did not clean your output folder before installing the Sentry plugin. File will not be source mapped: ".concat(bundleFilePath));
8630
- return _context11.abrupt("return");
8415
+ return _context3.abrupt("return");
8631
8416
  case 14:
8632
8417
  uniqueUploadName = "".concat(debugId, "-").concat(chunkIndex);
8633
8418
  bundleContent += "\n//# debugId=".concat(debugId);
8634
8419
  writeSourceFilePromise = fs__default["default"].promises.writeFile(path__default["default"].join(uploadFolder, "".concat(uniqueUploadName, ".js")), bundleContent, "utf-8");
8635
8420
  writeSourceMapFilePromise = determineSourceMapPathFromBundle(bundleFilePath, bundleContent, logger).then( /*#__PURE__*/function () {
8636
- var _ref12 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(sourceMapPath) {
8637
- return _regeneratorRuntime().wrap(function _callee10$(_context10) {
8638
- while (1) switch (_context10.prev = _context10.next) {
8421
+ var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(sourceMapPath) {
8422
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
8423
+ while (1) switch (_context2.prev = _context2.next) {
8639
8424
  case 0:
8640
8425
  if (!sourceMapPath) {
8641
- _context10.next = 3;
8426
+ _context2.next = 3;
8642
8427
  break;
8643
8428
  }
8644
- _context10.next = 3;
8429
+ _context2.next = 3;
8645
8430
  return prepareSourceMapForDebugIdUpload(sourceMapPath, path__default["default"].join(uploadFolder, "".concat(uniqueUploadName, ".js.map")), debugId, rewriteSourcesHook, logger);
8646
8431
  case 3:
8647
8432
  case "end":
8648
- return _context10.stop();
8433
+ return _context2.stop();
8649
8434
  }
8650
- }, _callee10);
8435
+ }, _callee2);
8651
8436
  }));
8652
- return function (_x17) {
8653
- return _ref12.apply(this, arguments);
8437
+ return function (_x15) {
8438
+ return _ref3.apply(this, arguments);
8654
8439
  };
8655
8440
  }());
8656
- _context11.next = 20;
8441
+ _context3.next = 20;
8657
8442
  return writeSourceFilePromise;
8658
8443
  case 20:
8659
- _context11.next = 22;
8444
+ _context3.next = 22;
8660
8445
  return writeSourceMapFilePromise;
8661
8446
  case 22:
8662
8447
  case "end":
8663
- return _context11.stop();
8448
+ return _context3.stop();
8664
8449
  }
8665
- }, _callee11, null, [[0, 6]]);
8450
+ }, _callee3, null, [[0, 6]]);
8666
8451
  }));
8667
8452
  return _prepareBundleForDebugIdUpload.apply(this, arguments);
8668
8453
  }
@@ -8680,22 +8465,22 @@ function determineDebugIdFromBundleSource(code) {
8680
8465
  *
8681
8466
  * @returns the path to the bundle's source map or `undefined` if none could be found.
8682
8467
  */
8683
- function determineSourceMapPathFromBundle(_x9, _x10, _x11) {
8468
+ function determineSourceMapPathFromBundle(_x7, _x8, _x9) {
8684
8469
  return _determineSourceMapPathFromBundle.apply(this, arguments);
8685
8470
  }
8686
8471
  /**
8687
8472
  * Reads a source map, injects debug ID fields, and writes the source map to the target path.
8688
8473
  */
8689
8474
  function _determineSourceMapPathFromBundle() {
8690
- _determineSourceMapPathFromBundle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(bundlePath, bundleSource, logger) {
8475
+ _determineSourceMapPathFromBundle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(bundlePath, bundleSource, logger) {
8691
8476
  var sourceMappingUrlMatch, sourceMappingUrl, isUrl, isSupportedUrl, url, absoluteSourceMapPath, adjacentSourceMapFilePath;
8692
- return _regeneratorRuntime().wrap(function _callee12$(_context12) {
8693
- while (1) switch (_context12.prev = _context12.next) {
8477
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
8478
+ while (1) switch (_context4.prev = _context4.next) {
8694
8479
  case 0:
8695
8480
  // 1. try to find source map at `sourceMappingURL` location
8696
8481
  sourceMappingUrlMatch = bundleSource.match(/^\s*\/\/# sourceMappingURL=(.*)$/m);
8697
8482
  if (!sourceMappingUrlMatch) {
8698
- _context12.next = 14;
8483
+ _context4.next = 14;
8699
8484
  break;
8700
8485
  }
8701
8486
  sourceMappingUrl = path__default["default"].normalize(sourceMappingUrlMatch[1]);
@@ -8715,99 +8500,99 @@ function _determineSourceMapPathFromBundle() {
8715
8500
  absoluteSourceMapPath = path__default["default"].join(path__default["default"].dirname(bundlePath), sourceMappingUrl);
8716
8501
  }
8717
8502
  if (!absoluteSourceMapPath) {
8718
- _context12.next = 14;
8503
+ _context4.next = 14;
8719
8504
  break;
8720
8505
  }
8721
- _context12.prev = 6;
8722
- _context12.next = 9;
8506
+ _context4.prev = 6;
8507
+ _context4.next = 9;
8723
8508
  return util__namespace.promisify(fs__default["default"].access)(absoluteSourceMapPath);
8724
8509
  case 9:
8725
- return _context12.abrupt("return", absoluteSourceMapPath);
8510
+ return _context4.abrupt("return", absoluteSourceMapPath);
8726
8511
  case 12:
8727
- _context12.prev = 12;
8728
- _context12.t0 = _context12["catch"](6);
8512
+ _context4.prev = 12;
8513
+ _context4.t0 = _context4["catch"](6);
8729
8514
  case 14:
8730
- _context12.prev = 14;
8515
+ _context4.prev = 14;
8731
8516
  adjacentSourceMapFilePath = bundlePath + ".map";
8732
- _context12.next = 18;
8517
+ _context4.next = 18;
8733
8518
  return util__namespace.promisify(fs__default["default"].access)(adjacentSourceMapFilePath);
8734
8519
  case 18:
8735
- return _context12.abrupt("return", adjacentSourceMapFilePath);
8520
+ return _context4.abrupt("return", adjacentSourceMapFilePath);
8736
8521
  case 21:
8737
- _context12.prev = 21;
8738
- _context12.t1 = _context12["catch"](14);
8522
+ _context4.prev = 21;
8523
+ _context4.t1 = _context4["catch"](14);
8739
8524
  case 23:
8740
8525
  // This is just a debug message because it can be quite spammy for some frameworks
8741
8526
  logger.debug("Could not determine source map path for bundle: ".concat(bundlePath, " - Did you turn on source map generation in your bundler?"));
8742
- return _context12.abrupt("return", undefined);
8527
+ return _context4.abrupt("return", undefined);
8743
8528
  case 25:
8744
8529
  case "end":
8745
- return _context12.stop();
8530
+ return _context4.stop();
8746
8531
  }
8747
- }, _callee12, null, [[6, 12], [14, 21]]);
8532
+ }, _callee4, null, [[6, 12], [14, 21]]);
8748
8533
  }));
8749
8534
  return _determineSourceMapPathFromBundle.apply(this, arguments);
8750
8535
  }
8751
- function prepareSourceMapForDebugIdUpload(_x12, _x13, _x14, _x15, _x16) {
8536
+ function prepareSourceMapForDebugIdUpload(_x10, _x11, _x12, _x13, _x14) {
8752
8537
  return _prepareSourceMapForDebugIdUpload.apply(this, arguments);
8753
8538
  }
8754
8539
  function _prepareSourceMapForDebugIdUpload() {
8755
- _prepareSourceMapForDebugIdUpload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(sourceMapPath, targetPath, debugId, rewriteSourcesHook, logger) {
8540
+ _prepareSourceMapForDebugIdUpload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(sourceMapPath, targetPath, debugId, rewriteSourcesHook, logger) {
8756
8541
  var sourceMapFileContent, map;
8757
- return _regeneratorRuntime().wrap(function _callee13$(_context13) {
8758
- while (1) switch (_context13.prev = _context13.next) {
8542
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
8543
+ while (1) switch (_context5.prev = _context5.next) {
8759
8544
  case 0:
8760
- _context13.prev = 0;
8761
- _context13.next = 3;
8545
+ _context5.prev = 0;
8546
+ _context5.next = 3;
8762
8547
  return util__namespace.promisify(fs__default["default"].readFile)(sourceMapPath, {
8763
8548
  encoding: "utf8"
8764
8549
  });
8765
8550
  case 3:
8766
- sourceMapFileContent = _context13.sent;
8767
- _context13.next = 10;
8551
+ sourceMapFileContent = _context5.sent;
8552
+ _context5.next = 10;
8768
8553
  break;
8769
8554
  case 6:
8770
- _context13.prev = 6;
8771
- _context13.t0 = _context13["catch"](0);
8772
- logger.error("Failed to read source map for debug ID upload: ".concat(sourceMapPath), _context13.t0);
8773
- return _context13.abrupt("return");
8555
+ _context5.prev = 6;
8556
+ _context5.t0 = _context5["catch"](0);
8557
+ logger.error("Failed to read source map for debug ID upload: ".concat(sourceMapPath), _context5.t0);
8558
+ return _context5.abrupt("return");
8774
8559
  case 10:
8775
- _context13.prev = 10;
8560
+ _context5.prev = 10;
8776
8561
  map = JSON.parse(sourceMapFileContent);
8777
8562
  // For now we write both fields until we know what will become the standard - if ever.
8778
8563
  map["debug_id"] = debugId;
8779
8564
  map["debugId"] = debugId;
8780
- _context13.next = 20;
8565
+ _context5.next = 20;
8781
8566
  break;
8782
8567
  case 16:
8783
- _context13.prev = 16;
8784
- _context13.t1 = _context13["catch"](10);
8568
+ _context5.prev = 16;
8569
+ _context5.t1 = _context5["catch"](10);
8785
8570
  logger.error("Failed to parse source map for debug ID upload: ".concat(sourceMapPath));
8786
- return _context13.abrupt("return");
8571
+ return _context5.abrupt("return");
8787
8572
  case 20:
8788
8573
  if (map["sources"] && Array.isArray(map["sources"])) {
8789
8574
  map["sources"] = map["sources"].map(function (source) {
8790
8575
  return rewriteSourcesHook(source, map);
8791
8576
  });
8792
8577
  }
8793
- _context13.prev = 21;
8794
- _context13.next = 24;
8578
+ _context5.prev = 21;
8579
+ _context5.next = 24;
8795
8580
  return util__namespace.promisify(fs__default["default"].writeFile)(targetPath, JSON.stringify(map), {
8796
8581
  encoding: "utf8"
8797
8582
  });
8798
8583
  case 24:
8799
- _context13.next = 30;
8584
+ _context5.next = 30;
8800
8585
  break;
8801
8586
  case 26:
8802
- _context13.prev = 26;
8803
- _context13.t2 = _context13["catch"](21);
8804
- logger.error("Failed to prepare source map for debug ID upload: ".concat(sourceMapPath), _context13.t2);
8805
- return _context13.abrupt("return");
8587
+ _context5.prev = 26;
8588
+ _context5.t2 = _context5["catch"](21);
8589
+ logger.error("Failed to prepare source map for debug ID upload: ".concat(sourceMapPath), _context5.t2);
8590
+ return _context5.abrupt("return");
8806
8591
  case 30:
8807
8592
  case "end":
8808
- return _context13.stop();
8593
+ return _context5.stop();
8809
8594
  }
8810
- }, _callee13, null, [[0, 6], [10, 16], [21, 26]]);
8595
+ }, _callee5, null, [[0, 6], [10, 16], [21, 26]]);
8811
8596
  }));
8812
8597
  return _prepareSourceMapForDebugIdUpload.apply(this, arguments);
8813
8598
  }
@@ -8821,50 +8606,329 @@ function defaultRewriteSourcesHook(source) {
8821
8606
  }
8822
8607
 
8823
8608
  /**
8824
- * Creates a plugin that creates releases, sets commits, deploys and finalizes releases.
8609
+ * Creates a build plugin manager that exposes primitives for everything that a Sentry JavaScript SDK or build tooling may do during a build.
8825
8610
  *
8826
- * Additionally, if legacy upload options are set, it uploads source maps in the legacy (non-debugId) way.
8827
- */
8828
- function releaseManagementPlugin(_ref) {
8829
- var logger = _ref.logger,
8830
- releaseName = _ref.releaseName,
8831
- include = _ref.include,
8832
- dist = _ref.dist,
8833
- setCommitsOption = _ref.setCommitsOption,
8834
- shouldCreateRelease = _ref.shouldCreateRelease,
8835
- shouldFinalizeRelease = _ref.shouldFinalizeRelease,
8836
- deployOptions = _ref.deployOptions,
8837
- handleRecoverableError = _ref.handleRecoverableError,
8838
- sentryScope = _ref.sentryScope,
8839
- sentryClient = _ref.sentryClient,
8840
- sentryCliOptions = _ref.sentryCliOptions,
8841
- createDependencyOnSourcemapFiles = _ref.createDependencyOnSourcemapFiles;
8842
- var freeGlobalDependencyOnSourcemapFiles = createDependencyOnSourcemapFiles();
8611
+ * The build plugin manager's behavior strongly depends on the options that are passed in.
8612
+ */
8613
+ function createSentryBuildPluginManager(userOptions, bundlerPluginMetaContext) {
8614
+ var _userOptions$silent, _userOptions$debug;
8615
+ var logger = createLogger({
8616
+ prefix: bundlerPluginMetaContext.loggerPrefix,
8617
+ silent: (_userOptions$silent = userOptions.silent) !== null && _userOptions$silent !== void 0 ? _userOptions$silent : false,
8618
+ debug: (_userOptions$debug = userOptions.debug) !== null && _userOptions$debug !== void 0 ? _userOptions$debug : false
8619
+ });
8620
+ try {
8621
+ var dotenvFile = fs__namespace.readFileSync(path__namespace.join(process.cwd(), ".env.sentry-build-plugin"), "utf-8");
8622
+ // NOTE: Do not use the dotenv.config API directly to read the dotenv file! For some ungodly reason, it falls back to reading `${process.cwd()}/.env` which is absolutely not what we want.
8623
+ var dotenvResult = dotenv__namespace.parse(dotenvFile);
8624
+
8625
+ // Vite has a bug/behaviour where spreading into process.env will cause it to crash
8626
+ // https://github.com/vitest-dev/vitest/issues/1870#issuecomment-1501140251
8627
+ Object.assign(process.env, dotenvResult);
8628
+ logger.info('Using environment variables configured in ".env.sentry-build-plugin".');
8629
+ } catch (e) {
8630
+ // Ignore "file not found" errors but throw all others
8631
+ if (_typeof(e) === "object" && e && "code" in e && e.code !== "ENOENT") {
8632
+ throw e;
8633
+ }
8634
+ }
8635
+ var options = normalizeUserOptions(userOptions);
8636
+ var shouldSendTelemetry = allowedToSendTelemetry(options);
8637
+ var _createSentryInstance = createSentryInstance(options, shouldSendTelemetry, bundlerPluginMetaContext.buildTool),
8638
+ sentryScope = _createSentryInstance.sentryScope,
8639
+ sentryClient = _createSentryInstance.sentryClient;
8640
+ var _sentryClient$getOpti = sentryClient.getOptions(),
8641
+ release = _sentryClient$getOpti.release,
8642
+ _sentryClient$getOpti2 = _sentryClient$getOpti.environment,
8643
+ environment = _sentryClient$getOpti2 === void 0 ? DEFAULT_ENVIRONMENT : _sentryClient$getOpti2;
8644
+ var sentrySession = makeSession({
8645
+ release: release,
8646
+ environment: environment
8647
+ });
8648
+ sentryScope.setSession(sentrySession);
8649
+ // Send the start of the session
8650
+ sentryClient.captureSession(sentrySession);
8651
+ var sessionHasEnded = false; // Just to prevent infinite loops with beforeExit, which is called whenever the event loop empties out
8652
+
8653
+ function endSession() {
8654
+ if (sessionHasEnded) {
8655
+ return;
8656
+ }
8657
+ closeSession(sentrySession);
8658
+ sentryClient.captureSession(sentrySession);
8659
+ sessionHasEnded = true;
8660
+ }
8661
+
8662
+ // We also need to manually end sessions on errors because beforeExit is not called on crashes
8663
+ process.on("beforeExit", function () {
8664
+ endSession();
8665
+ });
8666
+
8667
+ // Set the User-Agent that Sentry CLI will use when interacting with Sentry
8668
+ process.env["SENTRY_PIPELINE"] = "".concat(bundlerPluginMetaContext.buildTool, "-plugin/", "3.3.0-alpha.0");
8669
+
8670
+ // Not a bulletproof check but should be good enough to at least sometimes determine
8671
+ // if the plugin is called in dev/watch mode or for a prod build. The important part
8672
+ // here is to avoid a false positive. False negatives are okay.
8673
+ var isDevMode = process.env["NODE_ENV"] === "development";
8674
+
8675
+ /**
8676
+ * Handles errors caught and emitted in various areas of the plugin.
8677
+ *
8678
+ * Also sets the sentry session status according to the error handling.
8679
+ *
8680
+ * If users specify their custom `errorHandler` we'll leave the decision to throw
8681
+ * or continue up to them. By default, @param throwByDefault controls if the plugin
8682
+ * should throw an error (which causes a build fail in most bundlers) or continue.
8683
+ */
8684
+ function handleRecoverableError(unknownError, throwByDefault) {
8685
+ sentrySession.status = "abnormal";
8686
+ try {
8687
+ if (options.errorHandler) {
8688
+ try {
8689
+ if (unknownError instanceof Error) {
8690
+ options.errorHandler(unknownError);
8691
+ } else {
8692
+ options.errorHandler(new Error("An unknown error occurred"));
8693
+ }
8694
+ } catch (e) {
8695
+ sentrySession.status = "crashed";
8696
+ throw e;
8697
+ }
8698
+ } else {
8699
+ // setting the session to "crashed" b/c from a plugin perspective this run failed.
8700
+ // However, we're intentionally not rethrowing the error to avoid breaking the user build.
8701
+ sentrySession.status = "crashed";
8702
+ if (throwByDefault) {
8703
+ throw unknownError;
8704
+ }
8705
+ logger.error("An error occurred. Couldn't finish all operations:", unknownError);
8706
+ }
8707
+ } finally {
8708
+ endSession();
8709
+ }
8710
+ }
8711
+ if (!validateOptions(options, logger)) {
8712
+ // Throwing by default to avoid a misconfigured plugin going unnoticed.
8713
+ handleRecoverableError(new Error("Options were not set correctly. See output above for more details."), true);
8714
+ }
8715
+
8716
+ // We have multiple plugins depending on generated source map files. (debug ID upload, legacy upload)
8717
+ // Additionally, we also want to have the functionality to delete files after uploading sourcemaps.
8718
+ // All of these plugins and the delete functionality need to run in the same hook (`writeBundle`).
8719
+ // Since the plugins among themselves are not aware of when they run and finish, we need a system to
8720
+ // track their dependencies on the generated files, so that we can initiate the file deletion only after
8721
+ // nothing depends on the files anymore.
8722
+ var dependenciesOnBuildArtifacts = new Set();
8723
+ var buildArtifactsDependencySubscribers = [];
8724
+ function notifyBuildArtifactDependencySubscribers() {
8725
+ buildArtifactsDependencySubscribers.forEach(function (subscriber) {
8726
+ subscriber();
8727
+ });
8728
+ }
8729
+ function createDependencyOnBuildArtifacts() {
8730
+ var dependencyIdentifier = Symbol();
8731
+ dependenciesOnBuildArtifacts.add(dependencyIdentifier);
8732
+ return function freeDependencyOnBuildArtifacts() {
8733
+ dependenciesOnBuildArtifacts["delete"](dependencyIdentifier);
8734
+ notifyBuildArtifactDependencySubscribers();
8735
+ };
8736
+ }
8737
+
8738
+ /**
8739
+ * Returns a Promise that resolves when all the currently active dependencies are freed again.
8740
+ *
8741
+ * It is very important that this function is called as late as possible before wanting to await the Promise to give
8742
+ * the dependency producers as much time as possible to register themselves.
8743
+ */
8744
+ function waitUntilBuildArtifactDependenciesAreFreed() {
8745
+ return new Promise(function (resolve) {
8746
+ buildArtifactsDependencySubscribers.push(function () {
8747
+ if (dependenciesOnBuildArtifacts.size === 0) {
8748
+ resolve();
8749
+ }
8750
+ });
8751
+ if (dependenciesOnBuildArtifacts.size === 0) {
8752
+ resolve();
8753
+ }
8754
+ });
8755
+ }
8756
+ var bundleSizeOptimizationReplacementValues = {};
8757
+ if (options.bundleSizeOptimizations) {
8758
+ var bundleSizeOptimizations = options.bundleSizeOptimizations;
8759
+ if (bundleSizeOptimizations.excludeDebugStatements) {
8760
+ bundleSizeOptimizationReplacementValues["__SENTRY_DEBUG__"] = false;
8761
+ }
8762
+ if (bundleSizeOptimizations.excludeTracing) {
8763
+ bundleSizeOptimizationReplacementValues["__SENTRY_TRACING__"] = false;
8764
+ }
8765
+ if (bundleSizeOptimizations.excludeReplayCanvas) {
8766
+ bundleSizeOptimizationReplacementValues["__RRWEB_EXCLUDE_CANVAS__"] = true;
8767
+ }
8768
+ if (bundleSizeOptimizations.excludeReplayIframe) {
8769
+ bundleSizeOptimizationReplacementValues["__RRWEB_EXCLUDE_IFRAME__"] = true;
8770
+ }
8771
+ if (bundleSizeOptimizations.excludeReplayShadowDom) {
8772
+ bundleSizeOptimizationReplacementValues["__RRWEB_EXCLUDE_SHADOW_DOM__"] = true;
8773
+ }
8774
+ if (bundleSizeOptimizations.excludeReplayWorker) {
8775
+ bundleSizeOptimizationReplacementValues["__SENTRY_EXCLUDE_REPLAY_WORKER__"] = true;
8776
+ }
8777
+ }
8778
+ var bundleMetadata = {};
8779
+ if (options.moduleMetadata || options.applicationKey) {
8780
+ if (options.applicationKey) {
8781
+ // We use different keys so that if user-code receives multiple bundling passes, we will store the application keys of all the passes.
8782
+ // It is a bit unfortunate that we have to inject the metadata snippet at the top, because after multiple
8783
+ // injections, the first injection will always "win" because it comes last in the code. We would generally be
8784
+ // fine with making the last bundling pass win. But because it cannot win, we have to use a workaround of storing
8785
+ // the app keys in different object keys.
8786
+ // We can simply use the `_sentryBundlerPluginAppKey:` to filter for app keys in the SDK.
8787
+ bundleMetadata["_sentryBundlerPluginAppKey:".concat(options.applicationKey)] = true;
8788
+ }
8789
+ if (typeof options.moduleMetadata === "function") {
8790
+ var args = {
8791
+ org: options.org,
8792
+ project: options.project,
8793
+ release: options.release.name
8794
+ };
8795
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
8796
+ bundleMetadata = _objectSpread2(_objectSpread2({}, bundleMetadata), options.moduleMetadata(args));
8797
+ } else {
8798
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
8799
+ bundleMetadata = _objectSpread2(_objectSpread2({}, bundleMetadata), options.moduleMetadata);
8800
+ }
8801
+ }
8843
8802
  return {
8844
- name: "sentry-release-management-plugin",
8845
- writeBundle: function writeBundle() {
8846
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
8803
+ /**
8804
+ * A logger instance that takes the options passed to the build plugin manager into account. (for silencing and log level etc.)
8805
+ */
8806
+ logger: logger,
8807
+ /**
8808
+ * Options after normalization. Includes things like the inferred release name.
8809
+ */
8810
+ normalizedOptions: options,
8811
+ /**
8812
+ * Magic strings and their replacement values that can be used for bundle size optimizations. This already takes
8813
+ * into account the options passed to the build plugin manager.
8814
+ */
8815
+ bundleSizeOptimizationReplacementValues: bundleSizeOptimizationReplacementValues,
8816
+ /**
8817
+ * Metadata that should be injected into bundles if possible. Takes into account options passed to the build plugin manager.
8818
+ */
8819
+ // See `generateModuleMetadataInjectorCode` for how this should be used exactly
8820
+ bundleMetadata: bundleMetadata,
8821
+ /**
8822
+ * Contains utility functions for emitting telemetry via the build plugin manager.
8823
+ */
8824
+ telemetry: {
8825
+ /**
8826
+ * Emits a `Sentry Bundler Plugin execution` signal.
8827
+ */
8828
+ emitBundlerPluginExecutionSignal: function emitBundlerPluginExecutionSignal() {
8829
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
8830
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
8831
+ while (1) switch (_context.prev = _context.next) {
8832
+ case 0:
8833
+ _context.next = 2;
8834
+ return shouldSendTelemetry;
8835
+ case 2:
8836
+ if (!_context.sent) {
8837
+ _context.next = 7;
8838
+ break;
8839
+ }
8840
+ logger.info("Sending telemetry data on issues and performance to Sentry. To disable telemetry, set `options.telemetry` to `false`.");
8841
+ startSpan({
8842
+ name: "Sentry Bundler Plugin execution",
8843
+ scope: sentryScope
8844
+ }, function () {
8845
+ //
8846
+ });
8847
+ _context.next = 7;
8848
+ return safeFlushTelemetry(sentryClient);
8849
+ case 7:
8850
+ case "end":
8851
+ return _context.stop();
8852
+ }
8853
+ }, _callee);
8854
+ }))();
8855
+ }
8856
+ },
8857
+ /**
8858
+ * Will potentially create a release based on the build plugin manager options.
8859
+ *
8860
+ * Also
8861
+ * - finalizes the release
8862
+ * - sets commits
8863
+ * - uploads legacy sourcemaps
8864
+ * - adds deploy information
8865
+ */
8866
+ createRelease: function createRelease() {
8867
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
8847
8868
  var freeWriteBundleInvocationDependencyOnSourcemapFiles, cliInstance, normalizedInclude;
8848
- return _regeneratorRuntime().wrap(function _callee$(_context) {
8849
- while (1) switch (_context.prev = _context.next) {
8869
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
8870
+ while (1) switch (_context2.prev = _context2.next) {
8850
8871
  case 0:
8872
+ if (options.release.name) {
8873
+ _context2.next = 5;
8874
+ break;
8875
+ }
8876
+ logger.debug("No release name provided. Will not create release. Please set the `release.name` option to identify your release.");
8877
+ return _context2.abrupt("return");
8878
+ case 5:
8879
+ if (!isDevMode) {
8880
+ _context2.next = 10;
8881
+ break;
8882
+ }
8883
+ logger.debug("Running in development mode. Will not create release.");
8884
+ return _context2.abrupt("return");
8885
+ case 10:
8886
+ if (options.authToken) {
8887
+ _context2.next = 15;
8888
+ break;
8889
+ }
8890
+ logger.warn("No auth token provided. Will not create release. Please set the `authToken` option. You can find information on how to generate a Sentry auth token here: https://docs.sentry.io/api/auth/" + getTurborepoEnvPassthroughWarning("SENTRY_AUTH_TOKEN"));
8891
+ return _context2.abrupt("return");
8892
+ case 15:
8893
+ if (!(!options.org && !options.authToken.startsWith("sntrys_"))) {
8894
+ _context2.next = 20;
8895
+ break;
8896
+ }
8897
+ logger.warn("No organization slug provided. Will not create release. Please set the `org` option to your Sentry organization slug." + getTurborepoEnvPassthroughWarning("SENTRY_ORG"));
8898
+ return _context2.abrupt("return");
8899
+ case 20:
8900
+ if (options.project) {
8901
+ _context2.next = 23;
8902
+ break;
8903
+ }
8904
+ logger.warn("No project provided. Will not create release. Please set the `project` option to your Sentry project slug." + getTurborepoEnvPassthroughWarning("SENTRY_PROJECT"));
8905
+ return _context2.abrupt("return");
8906
+ case 23:
8851
8907
  // It is possible that this writeBundle hook is called multiple times in one build (for example when reusing the plugin, or when using build tooling like `@vitejs/plugin-legacy`)
8852
8908
  // Therefore we need to actually register the execution of this hook as dependency on the sourcemap files.
8853
- freeWriteBundleInvocationDependencyOnSourcemapFiles = createDependencyOnSourcemapFiles();
8854
- _context.prev = 1;
8855
- cliInstance = new SentryCli__default["default"](null, sentryCliOptions);
8856
- if (!shouldCreateRelease) {
8857
- _context.next = 6;
8909
+ freeWriteBundleInvocationDependencyOnSourcemapFiles = createDependencyOnBuildArtifacts();
8910
+ _context2.prev = 24;
8911
+ cliInstance = new SentryCli__default["default"](null, {
8912
+ authToken: options.authToken,
8913
+ org: options.org,
8914
+ project: options.project,
8915
+ silent: options.silent,
8916
+ url: options.url,
8917
+ vcsRemote: options.release.vcsRemote,
8918
+ headers: options.headers
8919
+ });
8920
+ if (!options.release.create) {
8921
+ _context2.next = 29;
8858
8922
  break;
8859
8923
  }
8860
- _context.next = 6;
8861
- return cliInstance.releases["new"](releaseName);
8862
- case 6:
8863
- if (!include) {
8864
- _context.next = 10;
8924
+ _context2.next = 29;
8925
+ return cliInstance.releases["new"](options.release.name);
8926
+ case 29:
8927
+ if (!options.release.uploadLegacySourcemaps) {
8928
+ _context2.next = 33;
8865
8929
  break;
8866
8930
  }
8867
- normalizedInclude = arrayify$1(include).map(function (includeItem) {
8931
+ normalizedInclude = arrayify(options.release.uploadLegacySourcemaps).map(function (includeItem) {
8868
8932
  return typeof includeItem === "string" ? {
8869
8933
  paths: [includeItem]
8870
8934
  } : includeItem;
@@ -8875,202 +8939,409 @@ function releaseManagementPlugin(_ref) {
8875
8939
  ext: includeEntry.ext ? includeEntry.ext.map(function (extension) {
8876
8940
  return ".".concat(extension.replace(/^\./, ""));
8877
8941
  }) : [".js", ".map", ".jsbundle", ".bundle"],
8878
- ignore: includeEntry.ignore ? arrayify$1(includeEntry.ignore) : undefined
8942
+ ignore: includeEntry.ignore ? arrayify(includeEntry.ignore) : undefined
8879
8943
  });
8880
8944
  });
8881
- _context.next = 10;
8882
- return cliInstance.releases.uploadSourceMaps(releaseName, {
8945
+ _context2.next = 33;
8946
+ return cliInstance.releases.uploadSourceMaps(options.release.name, {
8883
8947
  include: normalizedInclude,
8884
- dist: dist
8948
+ dist: options.release.dist
8885
8949
  });
8886
- case 10:
8887
- if (!(setCommitsOption !== false)) {
8888
- _context.next = 23;
8950
+ case 33:
8951
+ if (!(options.release.setCommits !== false)) {
8952
+ _context2.next = 46;
8889
8953
  break;
8890
8954
  }
8891
- _context.prev = 11;
8892
- _context.next = 14;
8893
- return cliInstance.releases.setCommits(releaseName, setCommitsOption);
8894
- case 14:
8895
- _context.next = 23;
8955
+ _context2.prev = 34;
8956
+ _context2.next = 37;
8957
+ return cliInstance.releases.setCommits(options.release.name,
8958
+ // set commits always exists due to the normalize function
8959
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
8960
+ options.release.setCommits);
8961
+ case 37:
8962
+ _context2.next = 46;
8896
8963
  break;
8897
- case 16:
8898
- _context.prev = 16;
8899
- _context.t0 = _context["catch"](11);
8900
- if (!("shouldNotThrowOnFailure" in setCommitsOption && setCommitsOption.shouldNotThrowOnFailure)) {
8901
- _context.next = 22;
8964
+ case 39:
8965
+ _context2.prev = 39;
8966
+ _context2.t0 = _context2["catch"](34);
8967
+ if (!(options.release.setCommits && "shouldNotThrowOnFailure" in options.release.setCommits && options.release.setCommits.shouldNotThrowOnFailure)) {
8968
+ _context2.next = 45;
8902
8969
  break;
8903
8970
  }
8904
- logger.debug("An error occurred setting commits on release (this message can be ignored unless you commits on release are desired):", _context.t0);
8905
- _context.next = 23;
8971
+ logger.debug("An error occurred setting commits on release (this message can be ignored unless you commits on release are desired):", _context2.t0);
8972
+ _context2.next = 46;
8906
8973
  break;
8907
- case 22:
8908
- throw _context.t0;
8909
- case 23:
8910
- if (!shouldFinalizeRelease) {
8911
- _context.next = 26;
8974
+ case 45:
8975
+ throw _context2.t0;
8976
+ case 46:
8977
+ if (!options.release.finalize) {
8978
+ _context2.next = 49;
8912
8979
  break;
8913
8980
  }
8914
- _context.next = 26;
8915
- return cliInstance.releases.finalize(releaseName);
8916
- case 26:
8917
- if (!deployOptions) {
8918
- _context.next = 29;
8981
+ _context2.next = 49;
8982
+ return cliInstance.releases.finalize(options.release.name);
8983
+ case 49:
8984
+ if (!options.release.deploy) {
8985
+ _context2.next = 52;
8919
8986
  break;
8920
8987
  }
8921
- _context.next = 29;
8922
- return cliInstance.releases.newDeploy(releaseName, deployOptions);
8923
- case 29:
8924
- _context.next = 37;
8988
+ _context2.next = 52;
8989
+ return cliInstance.releases.newDeploy(options.release.name, options.release.deploy);
8990
+ case 52:
8991
+ _context2.next = 60;
8925
8992
  break;
8926
- case 31:
8927
- _context.prev = 31;
8928
- _context.t1 = _context["catch"](1);
8993
+ case 54:
8994
+ _context2.prev = 54;
8995
+ _context2.t1 = _context2["catch"](24);
8929
8996
  sentryScope.captureException('Error in "releaseManagementPlugin" writeBundle hook');
8930
- _context.next = 36;
8997
+ _context2.next = 59;
8931
8998
  return safeFlushTelemetry(sentryClient);
8932
- case 36:
8933
- handleRecoverableError(_context.t1, false);
8934
- case 37:
8935
- _context.prev = 37;
8936
- freeGlobalDependencyOnSourcemapFiles();
8999
+ case 59:
9000
+ handleRecoverableError(_context2.t1, false);
9001
+ case 60:
9002
+ _context2.prev = 60;
8937
9003
  freeWriteBundleInvocationDependencyOnSourcemapFiles();
8938
- return _context.finish(37);
8939
- case 41:
9004
+ return _context2.finish(60);
9005
+ case 63:
8940
9006
  case "end":
8941
- return _context.stop();
9007
+ return _context2.stop();
8942
9008
  }
8943
- }, _callee, null, [[1, 31, 37, 41], [11, 16]]);
9009
+ }, _callee2, null, [[24, 54, 60, 63], [34, 39]]);
8944
9010
  }))();
8945
- }
8946
- };
8947
- }
8948
-
8949
- function telemetryPlugin(_ref) {
8950
- var sentryClient = _ref.sentryClient,
8951
- sentryScope = _ref.sentryScope,
8952
- shouldSendTelemetry = _ref.shouldSendTelemetry,
8953
- logger = _ref.logger;
8954
- return {
8955
- name: "sentry-telemetry-plugin",
8956
- buildStart: function buildStart() {
8957
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
8958
- return _regeneratorRuntime().wrap(function _callee$(_context) {
8959
- while (1) switch (_context.prev = _context.next) {
9011
+ },
9012
+ /**
9013
+ * Uploads sourcemaps using the "Debug ID" method. This function takes a list of build artifact paths that will be uploaded
9014
+ */
9015
+ uploadSourcemaps: function uploadSourcemaps(buildArtifactPaths) {
9016
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() {
9017
+ var _options$sourcemaps;
9018
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
9019
+ while (1) switch (_context11.prev = _context11.next) {
8960
9020
  case 0:
8961
- _context.next = 2;
8962
- return shouldSendTelemetry;
8963
- case 2:
8964
- if (!_context.sent) {
8965
- _context.next = 7;
8966
- break;
9021
+ if ((_options$sourcemaps = options.sourcemaps) !== null && _options$sourcemaps !== void 0 && _options$sourcemaps.disable) {
9022
+ logger.debug("Source map upload was disabled. Will not upload sourcemaps using debug ID process.");
9023
+ } else if (isDevMode) {
9024
+ logger.debug("Running in development mode. Will not upload sourcemaps.");
9025
+ } else if (!options.authToken) {
9026
+ logger.warn("No auth token provided. Will not upload source maps. Please set the `authToken` option. You can find information on how to generate a Sentry auth token here: https://docs.sentry.io/api/auth/" + getTurborepoEnvPassthroughWarning("SENTRY_AUTH_TOKEN"));
9027
+ } else if (!options.org && !options.authToken.startsWith("sntrys_")) {
9028
+ logger.warn("No org provided. Will not upload source maps. Please set the `org` option to your Sentry organization slug." + getTurborepoEnvPassthroughWarning("SENTRY_ORG"));
9029
+ } else if (!options.project) {
9030
+ logger.warn("No project provided. Will not upload source maps. Please set the `project` option to your Sentry project slug." + getTurborepoEnvPassthroughWarning("SENTRY_PROJECT"));
8967
9031
  }
8968
- logger.info("Sending telemetry data on issues and performance to Sentry. To disable telemetry, set `options.telemetry` to `false`.");
8969
- startSpan({
8970
- name: "Sentry Bundler Plugin execution",
8971
- scope: sentryScope
8972
- }, function () {
8973
- //
8974
- });
8975
- _context.next = 7;
8976
- return safeFlushTelemetry(sentryClient);
8977
- case 7:
9032
+ _context11.next = 3;
9033
+ return startSpan(
9034
+ // This is `forceTransaction`ed because this span is used in dashboards in the form of indexed transactions.
9035
+ {
9036
+ name: "debug-id-sourcemap-upload",
9037
+ scope: sentryScope,
9038
+ forceTransaction: true
9039
+ }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10() {
9040
+ var folderToCleanUp, freeUploadDependencyOnBuildArtifacts, _options$sourcemaps2, tmpUploadFolder, assets, globAssets, globResult, debugIdChunkFilePaths;
9041
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
9042
+ while (1) switch (_context10.prev = _context10.next) {
9043
+ case 0:
9044
+ // It is possible that this writeBundle hook (which calls this function) is called multiple times in one build (for example when reusing the plugin, or when using build tooling like `@vitejs/plugin-legacy`)
9045
+ // Therefore we need to actually register the execution of this hook as dependency on the sourcemap files.
9046
+ freeUploadDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();
9047
+ _context10.prev = 1;
9048
+ _context10.next = 4;
9049
+ return startSpan({
9050
+ name: "mkdtemp",
9051
+ scope: sentryScope
9052
+ }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
9053
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
9054
+ while (1) switch (_context3.prev = _context3.next) {
9055
+ case 0:
9056
+ _context3.next = 2;
9057
+ return fs__namespace.promises.mkdtemp(path__namespace.join(os__namespace.tmpdir(), "sentry-bundler-plugin-upload-"));
9058
+ case 2:
9059
+ return _context3.abrupt("return", _context3.sent);
9060
+ case 3:
9061
+ case "end":
9062
+ return _context3.stop();
9063
+ }
9064
+ }, _callee3);
9065
+ })));
9066
+ case 4:
9067
+ tmpUploadFolder = _context10.sent;
9068
+ folderToCleanUp = tmpUploadFolder;
9069
+ assets = (_options$sourcemaps2 = options.sourcemaps) === null || _options$sourcemaps2 === void 0 ? void 0 : _options$sourcemaps2.assets;
9070
+ if (assets) {
9071
+ globAssets = assets;
9072
+ } else {
9073
+ logger.debug("No `sourcemaps.assets` option provided, falling back to uploading detected build artifacts.");
9074
+ globAssets = buildArtifactPaths;
9075
+ }
9076
+ _context10.next = 10;
9077
+ return startSpan({
9078
+ name: "glob",
9079
+ scope: sentryScope
9080
+ }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
9081
+ var _options$sourcemaps3;
9082
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
9083
+ while (1) switch (_context4.prev = _context4.next) {
9084
+ case 0:
9085
+ _context4.next = 2;
9086
+ return glob.glob(globAssets, {
9087
+ absolute: true,
9088
+ nodir: true,
9089
+ ignore: (_options$sourcemaps3 = options.sourcemaps) === null || _options$sourcemaps3 === void 0 ? void 0 : _options$sourcemaps3.ignore
9090
+ });
9091
+ case 2:
9092
+ return _context4.abrupt("return", _context4.sent);
9093
+ case 3:
9094
+ case "end":
9095
+ return _context4.stop();
9096
+ }
9097
+ }, _callee4);
9098
+ })));
9099
+ case 10:
9100
+ globResult = _context10.sent;
9101
+ debugIdChunkFilePaths = globResult.filter(function (debugIdChunkFilePath) {
9102
+ return !!stripQueryAndHashFromPath(debugIdChunkFilePath).match(/\.(js|mjs|cjs)$/);
9103
+ }); // The order of the files output by glob() is not deterministic
9104
+ // Ensure order within the files so that {debug-id}-{chunkIndex} coupling is consistent
9105
+ debugIdChunkFilePaths.sort();
9106
+ if (!(Array.isArray(assets) && assets.length === 0)) {
9107
+ _context10.next = 17;
9108
+ break;
9109
+ }
9110
+ logger.debug("Empty `sourcemaps.assets` option provided. Will not upload sourcemaps with debug ID.");
9111
+ _context10.next = 24;
9112
+ break;
9113
+ case 17:
9114
+ if (!(debugIdChunkFilePaths.length === 0)) {
9115
+ _context10.next = 21;
9116
+ break;
9117
+ }
9118
+ logger.warn("Didn't find any matching sources for debug ID upload. Please check the `sourcemaps.assets` option.");
9119
+ _context10.next = 24;
9120
+ break;
9121
+ case 21:
9122
+ _context10.next = 23;
9123
+ return startSpan({
9124
+ name: "prepare-bundles",
9125
+ scope: sentryScope
9126
+ }, /*#__PURE__*/function () {
9127
+ var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(prepBundlesSpan) {
9128
+ var preparationTasks, workers, worker, workerIndex, files, stats, uploadSize;
9129
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
9130
+ while (1) switch (_context8.prev = _context8.next) {
9131
+ case 0:
9132
+ // Preparing the bundles can be a lot of work and doing it all at once has the potential of nuking the heap so
9133
+ // instead we do it with a maximum of 16 concurrent workers
9134
+ preparationTasks = debugIdChunkFilePaths.map(function (chunkFilePath, chunkIndex) {
9135
+ return /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
9136
+ var _options$sourcemaps$r, _options$sourcemaps4;
9137
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
9138
+ while (1) switch (_context5.prev = _context5.next) {
9139
+ case 0:
9140
+ _context5.next = 2;
9141
+ return prepareBundleForDebugIdUpload(chunkFilePath, tmpUploadFolder, chunkIndex, logger, (_options$sourcemaps$r = (_options$sourcemaps4 = options.sourcemaps) === null || _options$sourcemaps4 === void 0 ? void 0 : _options$sourcemaps4.rewriteSources) !== null && _options$sourcemaps$r !== void 0 ? _options$sourcemaps$r : defaultRewriteSourcesHook);
9142
+ case 2:
9143
+ case "end":
9144
+ return _context5.stop();
9145
+ }
9146
+ }, _callee5);
9147
+ }));
9148
+ });
9149
+ workers = [];
9150
+ worker = /*#__PURE__*/function () {
9151
+ var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
9152
+ var task;
9153
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
9154
+ while (1) switch (_context6.prev = _context6.next) {
9155
+ case 0:
9156
+ if (!(preparationTasks.length > 0)) {
9157
+ _context6.next = 7;
9158
+ break;
9159
+ }
9160
+ task = preparationTasks.shift();
9161
+ if (!task) {
9162
+ _context6.next = 5;
9163
+ break;
9164
+ }
9165
+ _context6.next = 5;
9166
+ return task();
9167
+ case 5:
9168
+ _context6.next = 0;
9169
+ break;
9170
+ case 7:
9171
+ case "end":
9172
+ return _context6.stop();
9173
+ }
9174
+ }, _callee6);
9175
+ }));
9176
+ return function worker() {
9177
+ return _ref6.apply(this, arguments);
9178
+ };
9179
+ }();
9180
+ for (workerIndex = 0; workerIndex < 16; workerIndex++) {
9181
+ workers.push(worker());
9182
+ }
9183
+ _context8.next = 6;
9184
+ return Promise.all(workers);
9185
+ case 6:
9186
+ _context8.next = 8;
9187
+ return fs__namespace.promises.readdir(tmpUploadFolder);
9188
+ case 8:
9189
+ files = _context8.sent;
9190
+ stats = files.map(function (file) {
9191
+ return fs__namespace.promises.stat(path__namespace.join(tmpUploadFolder, file));
9192
+ });
9193
+ _context8.next = 12;
9194
+ return Promise.all(stats);
9195
+ case 12:
9196
+ uploadSize = _context8.sent.reduce(function (accumulator, _ref7) {
9197
+ var size = _ref7.size;
9198
+ return accumulator + size;
9199
+ }, 0);
9200
+ setMeasurement("files", files.length, "none", prepBundlesSpan);
9201
+ setMeasurement("upload_size", uploadSize, "byte", prepBundlesSpan);
9202
+ _context8.next = 17;
9203
+ return startSpan({
9204
+ name: "upload",
9205
+ scope: sentryScope
9206
+ }, /*#__PURE__*/function () {
9207
+ var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(uploadSpan) {
9208
+ var _options$release$name;
9209
+ var cliInstance;
9210
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
9211
+ while (1) switch (_context7.prev = _context7.next) {
9212
+ case 0:
9213
+ cliInstance = new SentryCli__default["default"](null, {
9214
+ authToken: options.authToken,
9215
+ org: options.org,
9216
+ project: options.project,
9217
+ silent: options.silent,
9218
+ url: options.url,
9219
+ vcsRemote: options.release.vcsRemote,
9220
+ headers: _objectSpread2({
9221
+ "sentry-trace": spanToTraceHeader(uploadSpan),
9222
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
9223
+ baggage: dynamicSamplingContextToSentryBaggageHeader(getDynamicSamplingContextFromSpan(uploadSpan))
9224
+ }, options.headers)
9225
+ });
9226
+ _context7.next = 3;
9227
+ return cliInstance.releases.uploadSourceMaps((_options$release$name = options.release.name) !== null && _options$release$name !== void 0 ? _options$release$name : "undefined",
9228
+ // unfortunately this needs a value for now but it will not matter since debug IDs overpower releases anyhow
9229
+ {
9230
+ include: [{
9231
+ paths: [tmpUploadFolder],
9232
+ rewrite: false,
9233
+ dist: options.release.dist
9234
+ }]
9235
+ });
9236
+ case 3:
9237
+ case "end":
9238
+ return _context7.stop();
9239
+ }
9240
+ }, _callee7);
9241
+ }));
9242
+ return function (_x2) {
9243
+ return _ref8.apply(this, arguments);
9244
+ };
9245
+ }());
9246
+ case 17:
9247
+ case "end":
9248
+ return _context8.stop();
9249
+ }
9250
+ }, _callee8);
9251
+ }));
9252
+ return function (_x) {
9253
+ return _ref4.apply(this, arguments);
9254
+ };
9255
+ }());
9256
+ case 23:
9257
+ logger.info("Successfully uploaded source maps to Sentry");
9258
+ case 24:
9259
+ _context10.next = 30;
9260
+ break;
9261
+ case 26:
9262
+ _context10.prev = 26;
9263
+ _context10.t0 = _context10["catch"](1);
9264
+ sentryScope.captureException('Error in "debugIdUploadPlugin" writeBundle hook');
9265
+ handleRecoverableError(_context10.t0, false);
9266
+ case 30:
9267
+ _context10.prev = 30;
9268
+ if (folderToCleanUp) {
9269
+ void startSpan({
9270
+ name: "cleanup",
9271
+ scope: sentryScope
9272
+ }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9() {
9273
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
9274
+ while (1) switch (_context9.prev = _context9.next) {
9275
+ case 0:
9276
+ if (!folderToCleanUp) {
9277
+ _context9.next = 3;
9278
+ break;
9279
+ }
9280
+ _context9.next = 3;
9281
+ return fs__namespace.promises.rm(folderToCleanUp, {
9282
+ recursive: true,
9283
+ force: true
9284
+ });
9285
+ case 3:
9286
+ case "end":
9287
+ return _context9.stop();
9288
+ }
9289
+ }, _callee9);
9290
+ })));
9291
+ }
9292
+ freeUploadDependencyOnBuildArtifacts();
9293
+ _context10.next = 35;
9294
+ return safeFlushTelemetry(sentryClient);
9295
+ case 35:
9296
+ return _context10.finish(30);
9297
+ case 36:
9298
+ case "end":
9299
+ return _context10.stop();
9300
+ }
9301
+ }, _callee10, null, [[1, 26, 30, 36]]);
9302
+ })));
9303
+ case 3:
8978
9304
  case "end":
8979
- return _context.stop();
9305
+ return _context11.stop();
8980
9306
  }
8981
- }, _callee);
9307
+ }, _callee11);
8982
9308
  }))();
8983
- }
8984
- };
8985
- }
8986
-
8987
- // Logging everything to stderr not to interfere with stdout
8988
- function createLogger(options) {
8989
- return {
8990
- info: function info(message) {
8991
- if (!options.silent) {
8992
- var _console;
8993
- for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
8994
- params[_key - 1] = arguments[_key];
8995
- }
8996
- // eslint-disable-next-line no-console
8997
- (_console = console).info.apply(_console, ["".concat(options.prefix, " Info: ").concat(message)].concat(params));
8998
- }
8999
- },
9000
- warn: function warn(message) {
9001
- if (!options.silent) {
9002
- var _console2;
9003
- for (var _len2 = arguments.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
9004
- params[_key2 - 1] = arguments[_key2];
9005
- }
9006
- // eslint-disable-next-line no-console
9007
- (_console2 = console).warn.apply(_console2, ["".concat(options.prefix, " Warning: ").concat(message)].concat(params));
9008
- }
9009
- },
9010
- error: function error(message) {
9011
- if (!options.silent) {
9012
- var _console3;
9013
- for (var _len3 = arguments.length, params = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
9014
- params[_key3 - 1] = arguments[_key3];
9015
- }
9016
- // eslint-disable-next-line no-console
9017
- (_console3 = console).error.apply(_console3, ["".concat(options.prefix, " Error: ").concat(message)].concat(params));
9018
- }
9019
9309
  },
9020
- debug: function debug(message) {
9021
- if (!options.silent && options.debug) {
9022
- var _console4;
9023
- for (var _len4 = arguments.length, params = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
9024
- params[_key4 - 1] = arguments[_key4];
9025
- }
9026
- // eslint-disable-next-line no-console
9027
- (_console4 = console).debug.apply(_console4, ["".concat(options.prefix, " Debug: ").concat(message)].concat(params));
9028
- }
9029
- }
9030
- };
9031
- }
9032
-
9033
- function fileDeletionPlugin(_ref) {
9034
- var handleRecoverableError = _ref.handleRecoverableError,
9035
- sentryScope = _ref.sentryScope,
9036
- sentryClient = _ref.sentryClient,
9037
- filesToDeleteAfterUpload = _ref.filesToDeleteAfterUpload,
9038
- waitUntilSourcemapFileDependenciesAreFreed = _ref.waitUntilSourcemapFileDependenciesAreFreed,
9039
- logger = _ref.logger;
9040
- return {
9041
- name: "sentry-file-deletion-plugin",
9042
- writeBundle: function writeBundle() {
9043
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
9044
- var filesToDelete, filePathsToDelete;
9045
- return _regeneratorRuntime().wrap(function _callee$(_context) {
9046
- while (1) switch (_context.prev = _context.next) {
9310
+ /**
9311
+ * Will delete artifacts based on the passed `sourcemaps.filesToDeleteAfterUpload` option.
9312
+ */
9313
+ deleteArtifacts: function deleteArtifacts() {
9314
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
9315
+ var _options$sourcemaps5, filesToDelete, filePathsToDelete;
9316
+ return _regeneratorRuntime().wrap(function _callee12$(_context12) {
9317
+ while (1) switch (_context12.prev = _context12.next) {
9047
9318
  case 0:
9048
- _context.prev = 0;
9049
- _context.next = 3;
9050
- return filesToDeleteAfterUpload;
9319
+ _context12.prev = 0;
9320
+ _context12.next = 3;
9321
+ return (_options$sourcemaps5 = options.sourcemaps) === null || _options$sourcemaps5 === void 0 ? void 0 : _options$sourcemaps5.filesToDeleteAfterUpload;
9051
9322
  case 3:
9052
- filesToDelete = _context.sent;
9323
+ filesToDelete = _context12.sent;
9053
9324
  if (!(filesToDelete !== undefined)) {
9054
- _context.next = 14;
9325
+ _context12.next = 14;
9055
9326
  break;
9056
9327
  }
9057
- _context.next = 7;
9328
+ _context12.next = 7;
9058
9329
  return glob.glob(filesToDelete, {
9059
9330
  absolute: true,
9060
9331
  nodir: true
9061
9332
  });
9062
9333
  case 7:
9063
- filePathsToDelete = _context.sent;
9334
+ filePathsToDelete = _context12.sent;
9064
9335
  logger.debug("Waiting for dependencies on generated files to be freed before deleting...");
9065
- _context.next = 11;
9066
- return waitUntilSourcemapFileDependenciesAreFreed();
9336
+ _context12.next = 11;
9337
+ return waitUntilBuildArtifactDependenciesAreFreed();
9067
9338
  case 11:
9068
9339
  filePathsToDelete.forEach(function (filePathToDelete) {
9069
9340
  logger.debug("Deleting asset after upload: ".concat(filePathToDelete));
9070
9341
  });
9071
- _context.next = 14;
9342
+ _context12.next = 14;
9072
9343
  return Promise.all(filePathsToDelete.map(function (filePathToDelete) {
9073
- return fs__default["default"].promises.rm(filePathToDelete, {
9344
+ return fs__namespace.promises.rm(filePathToDelete, {
9074
9345
  force: true
9075
9346
  })["catch"](function (e) {
9076
9347
  // This is allowed to fail - we just don't do anything
@@ -9078,53 +9349,31 @@ function fileDeletionPlugin(_ref) {
9078
9349
  });
9079
9350
  }));
9080
9351
  case 14:
9081
- _context.next = 22;
9352
+ _context12.next = 22;
9082
9353
  break;
9083
9354
  case 16:
9084
- _context.prev = 16;
9085
- _context.t0 = _context["catch"](0);
9355
+ _context12.prev = 16;
9356
+ _context12.t0 = _context12["catch"](0);
9086
9357
  sentryScope.captureException('Error in "sentry-file-deletion-plugin" buildEnd hook');
9087
- _context.next = 21;
9358
+ _context12.next = 21;
9088
9359
  return safeFlushTelemetry(sentryClient);
9089
9360
  case 21:
9090
9361
  // We throw by default if we get here b/c not being able to delete
9091
9362
  // source maps could leak them to production
9092
- handleRecoverableError(_context.t0, true);
9363
+ handleRecoverableError(_context12.t0, true);
9093
9364
  case 22:
9094
9365
  case "end":
9095
- return _context.stop();
9366
+ return _context12.stop();
9096
9367
  }
9097
- }, _callee, null, [[0, 16]]);
9368
+ }, _callee12, null, [[0, 16]]);
9098
9369
  }))();
9099
- }
9370
+ },
9371
+ createDependencyOnBuildArtifacts: createDependencyOnBuildArtifacts
9100
9372
  };
9101
9373
  }
9102
9374
 
9103
9375
  /**
9104
- * The sentry bundler plugin concerns itself with two things:
9105
- * - Release injection
9106
- * - Sourcemaps upload
9107
- *
9108
- * Release injection:
9109
- * Per default the sentry bundler plugin will inject a global `SENTRY_RELEASE` into each JavaScript/TypeScript module
9110
- * that is part of the bundle. On a technical level this is done by appending an import (`import "sentry-release-injector";`)
9111
- * to all entrypoint files of the user code (see `transformInclude` and `transform` hooks). This import is then resolved
9112
- * by the sentry plugin to a virtual module that sets the global variable (see `resolveId` and `load` hooks).
9113
- * If a user wants to inject the release into a particular set of modules they can use the `releaseInjectionTargets` option.
9114
- *
9115
- * Source maps upload:
9116
- *
9117
- * The sentry bundler plugin will also take care of uploading source maps to Sentry. This
9118
- * is all done in the `writeBundle` hook. In this hook the sentry plugin will execute the
9119
- * release creation pipeline:
9120
- *
9121
- * 1. Create a new release
9122
- * 2. Upload sourcemaps based on `include` and source-map-specific options
9123
- * 3. Associate a range of commits with the release (if `setCommits` is specified)
9124
- * 4. Finalize the release (unless `finalize` is disabled)
9125
- * 5. Add deploy information to the release (if `deploy` is specified)
9126
- *
9127
- * This release creation pipeline relies on Sentry CLI to execute the different steps.
9376
+ * Creates an unplugin instance used to create Sentry plugins for Vite, Rollup, esbuild, and Webpack.
9128
9377
  */
9129
9378
  function sentryUnpluginFactory(_ref) {
9130
9379
  var releaseInjectionPlugin = _ref.releaseInjectionPlugin,
@@ -9134,189 +9383,46 @@ function sentryUnpluginFactory(_ref) {
9134
9383
  debugIdUploadPlugin = _ref.debugIdUploadPlugin,
9135
9384
  bundleSizeOptimizationsPlugin = _ref.bundleSizeOptimizationsPlugin;
9136
9385
  return unplugin.createUnplugin(function () {
9137
- var _userOptions$_metaOpt, _userOptions$_metaOpt2, _userOptions$silent, _userOptions$debug, _options$sourcemaps, _options$sourcemaps2, _options$sourcemaps6;
9386
+ var _userOptions$_metaOpt, _userOptions$_metaOpt2, _options$sourcemaps;
9138
9387
  var userOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
9139
9388
  var unpluginMetaContext = arguments.length > 1 ? arguments[1] : undefined;
9140
- var logger = createLogger({
9141
- prefix: (_userOptions$_metaOpt = (_userOptions$_metaOpt2 = userOptions._metaOptions) === null || _userOptions$_metaOpt2 === void 0 ? void 0 : _userOptions$_metaOpt2.loggerPrefixOverride) !== null && _userOptions$_metaOpt !== void 0 ? _userOptions$_metaOpt : "[sentry-".concat(unpluginMetaContext.framework, "-plugin]"),
9142
- silent: (_userOptions$silent = userOptions.silent) !== null && _userOptions$silent !== void 0 ? _userOptions$silent : false,
9143
- debug: (_userOptions$debug = userOptions.debug) !== null && _userOptions$debug !== void 0 ? _userOptions$debug : false
9389
+ var sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {
9390
+ loggerPrefix: (_userOptions$_metaOpt = (_userOptions$_metaOpt2 = userOptions._metaOptions) === null || _userOptions$_metaOpt2 === void 0 ? void 0 : _userOptions$_metaOpt2.loggerPrefixOverride) !== null && _userOptions$_metaOpt !== void 0 ? _userOptions$_metaOpt : "[sentry-".concat(unpluginMetaContext.framework, "-plugin]"),
9391
+ buildTool: unpluginMetaContext.framework
9144
9392
  });
9145
-
9146
- // Not a bulletproof check but should be good enough to at least sometimes determine
9147
- // if the plugin is called in dev/watch mode or for a prod build. The important part
9148
- // here is to avoid a false positive. False negatives are okay.
9149
- var isDevMode = process.env["NODE_ENV"] === "development";
9150
- try {
9151
- var dotenvFile = fs__namespace.readFileSync(path__namespace.join(process.cwd(), ".env.sentry-build-plugin"), "utf-8");
9152
- // NOTE: Do not use the dotenv.config API directly to read the dotenv file! For some ungodly reason, it falls back to reading `${process.cwd()}/.env` which is absolutely not what we want.
9153
- var dotenvResult = dotenv__namespace.parse(dotenvFile);
9154
-
9155
- // Vite has a bug/behaviour where spreading into process.env will cause it to crash
9156
- // https://github.com/vitest-dev/vitest/issues/1870#issuecomment-1501140251
9157
- Object.assign(process.env, dotenvResult);
9158
- logger.info('Using environment variables configured in ".env.sentry-build-plugin".');
9159
- } catch (e) {
9160
- // Ignore "file not found" errors but throw all others
9161
- if (_typeof(e) === "object" && e && "code" in e && e.code !== "ENOENT") {
9162
- throw e;
9163
- }
9164
- }
9165
- var options = normalizeUserOptions(userOptions);
9393
+ var logger = sentryBuildPluginManager.logger,
9394
+ options = sentryBuildPluginManager.normalizedOptions,
9395
+ bundleSizeOptimizationReplacementValues = sentryBuildPluginManager.bundleSizeOptimizationReplacementValues;
9166
9396
  if (options.disable) {
9167
9397
  return [{
9168
9398
  name: "sentry-noop-plugin"
9169
9399
  }];
9170
9400
  }
9171
- var shouldSendTelemetry = allowedToSendTelemetry(options);
9172
- var _createSentryInstance = createSentryInstance(options, shouldSendTelemetry, unpluginMetaContext.framework),
9173
- sentryScope = _createSentryInstance.sentryScope,
9174
- sentryClient = _createSentryInstance.sentryClient;
9175
- var _sentryClient$getOpti = sentryClient.getOptions(),
9176
- release = _sentryClient$getOpti.release,
9177
- _sentryClient$getOpti2 = _sentryClient$getOpti.environment,
9178
- environment = _sentryClient$getOpti2 === void 0 ? DEFAULT_ENVIRONMENT : _sentryClient$getOpti2;
9179
- var sentrySession = makeSession({
9180
- release: release,
9181
- environment: environment
9182
- });
9183
- sentryScope.setSession(sentrySession);
9184
- // Send the start of the session
9185
- sentryClient.captureSession(sentrySession);
9186
- var sessionHasEnded = false; // Just to prevent infinite loops with beforeExit, which is called whenever the event loop empties out
9187
-
9188
- function endSession() {
9189
- if (sessionHasEnded) {
9190
- return;
9191
- }
9192
- closeSession(sentrySession);
9193
- sentryClient.captureSession(sentrySession);
9194
- sessionHasEnded = true;
9195
- }
9196
-
9197
- // We also need to manually end sessions on errors because beforeExit is not called on crashes
9198
- process.on("beforeExit", function () {
9199
- endSession();
9200
- });
9201
-
9202
- // Set the User-Agent that Sentry CLI will use when interacting with Sentry
9203
- process.env["SENTRY_PIPELINE"] = "".concat(unpluginMetaContext.framework, "-plugin/", "3.2.4");
9204
-
9205
- /**
9206
- * Handles errors caught and emitted in various areas of the plugin.
9207
- *
9208
- * Also sets the sentry session status according to the error handling.
9209
- *
9210
- * If users specify their custom `errorHandler` we'll leave the decision to throw
9211
- * or continue up to them. By default, @param throwByDefault controls if the plugin
9212
- * should throw an error (which causes a build fail in most bundlers) or continue.
9213
- */
9214
- function handleRecoverableError(unknownError, throwByDefault) {
9215
- sentrySession.status = "abnormal";
9216
- try {
9217
- if (options.errorHandler) {
9218
- try {
9219
- if (unknownError instanceof Error) {
9220
- options.errorHandler(unknownError);
9221
- } else {
9222
- options.errorHandler(new Error("An unknown error occured"));
9223
- }
9224
- } catch (e) {
9225
- sentrySession.status = "crashed";
9226
- throw e;
9227
- }
9228
- } else {
9229
- // setting the session to "crashed" b/c from a plugin perspective this run failed.
9230
- // However, we're intentionally not rethrowing the error to avoid breaking the user build.
9231
- sentrySession.status = "crashed";
9232
- if (throwByDefault) {
9233
- throw unknownError;
9234
- }
9235
- logger.error("An error occurred. Couldn't finish all operations:", unknownError);
9236
- }
9237
- } finally {
9238
- endSession();
9239
- }
9240
- }
9241
- if (!validateOptions(options, logger)) {
9242
- // Throwing by default to avoid a misconfigured plugin going unnoticed.
9243
- handleRecoverableError(new Error("Options were not set correctly. See output above for more details."), true);
9244
- }
9245
9401
  if (process.cwd().match(/\\node_modules\\|\/node_modules\//)) {
9246
9402
  logger.warn("Running Sentry plugin from within a `node_modules` folder. Some features may not work.");
9247
9403
  }
9248
9404
  var plugins = [];
9249
- plugins.push(telemetryPlugin({
9250
- sentryClient: sentryClient,
9251
- sentryScope: sentryScope,
9252
- logger: logger,
9253
- shouldSendTelemetry: shouldSendTelemetry
9254
- }));
9255
9405
 
9256
- // We have multiple plugins depending on generated source map files. (debug ID upload, legacy upload)
9257
- // Additionally, we also want to have the functionality to delete files after uploading sourcemaps.
9258
- // All of these plugins and the delete functionality need to run in the same hook (`writeBundle`).
9259
- // Since the plugins among themselves are not aware of when they run and finish, we need a system to
9260
- // track their dependencies on the generated files, so that we can initiate the file deletion only after
9261
- // nothing depends on the files anymore.
9262
- var dependenciesOnSourcemapFiles = new Set();
9263
- var sourcemapFileDependencySubscribers = [];
9264
- function notifySourcemapFileDependencySubscribers() {
9265
- sourcemapFileDependencySubscribers.forEach(function (subscriber) {
9266
- subscriber();
9267
- });
9268
- }
9269
- function createDependencyOnSourcemapFiles() {
9270
- var dependencyIdentifier = Symbol();
9271
- dependenciesOnSourcemapFiles.add(dependencyIdentifier);
9272
- return function freeDependencyOnSourcemapFiles() {
9273
- dependenciesOnSourcemapFiles["delete"](dependencyIdentifier);
9274
- notifySourcemapFileDependencySubscribers();
9275
- };
9276
- }
9277
-
9278
- /**
9279
- * Returns a Promise that resolves when all the currently active dependencies are freed again.
9280
- *
9281
- * It is very important that this function is called as late as possible before wanting to await the Promise to give
9282
- * the dependency producers as much time as possible to register themselves.
9283
- */
9284
- function waitUntilSourcemapFileDependenciesAreFreed() {
9285
- return new Promise(function (resolve) {
9286
- sourcemapFileDependencySubscribers.push(function () {
9287
- if (dependenciesOnSourcemapFiles.size === 0) {
9288
- resolve();
9289
- }
9290
- });
9291
- if (dependenciesOnSourcemapFiles.size === 0) {
9292
- resolve();
9293
- }
9294
- });
9295
- }
9296
- if (options.bundleSizeOptimizations) {
9297
- var bundleSizeOptimizations = options.bundleSizeOptimizations;
9298
- var replacementValues = {};
9299
- if (bundleSizeOptimizations.excludeDebugStatements) {
9300
- replacementValues["__SENTRY_DEBUG__"] = false;
9301
- }
9302
- if (bundleSizeOptimizations.excludeTracing) {
9303
- replacementValues["__SENTRY_TRACING__"] = false;
9304
- }
9305
- if (bundleSizeOptimizations.excludeReplayCanvas) {
9306
- replacementValues["__RRWEB_EXCLUDE_CANVAS__"] = true;
9307
- }
9308
- if (bundleSizeOptimizations.excludeReplayIframe) {
9309
- replacementValues["__RRWEB_EXCLUDE_IFRAME__"] = true;
9310
- }
9311
- if (bundleSizeOptimizations.excludeReplayShadowDom) {
9312
- replacementValues["__RRWEB_EXCLUDE_SHADOW_DOM__"] = true;
9313
- }
9314
- if (bundleSizeOptimizations.excludeReplayWorker) {
9315
- replacementValues["__SENTRY_EXCLUDE_REPLAY_WORKER__"] = true;
9316
- }
9317
- if (Object.keys(replacementValues).length > 0) {
9318
- plugins.push(bundleSizeOptimizationsPlugin(replacementValues));
9406
+ // Add plugin to emit a telemetry signal when the build starts
9407
+ plugins.push({
9408
+ name: "sentry-telemetry-plugin",
9409
+ buildStart: function buildStart() {
9410
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
9411
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
9412
+ while (1) switch (_context.prev = _context.next) {
9413
+ case 0:
9414
+ _context.next = 2;
9415
+ return sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal();
9416
+ case 2:
9417
+ case "end":
9418
+ return _context.stop();
9419
+ }
9420
+ }, _callee);
9421
+ }))();
9319
9422
  }
9423
+ });
9424
+ if (Object.keys(bundleSizeOptimizationReplacementValues).length > 0) {
9425
+ plugins.push(bundleSizeOptimizationsPlugin(bundleSizeOptimizationReplacementValues));
9320
9426
  }
9321
9427
  if (!options.release.inject) {
9322
9428
  logger.debug("Release injection disabled via `release.inject` option. Will not inject release.");
@@ -9329,113 +9435,44 @@ function sentryUnpluginFactory(_ref) {
9329
9435
  });
9330
9436
  plugins.push(releaseInjectionPlugin(_injectionCode));
9331
9437
  }
9332
- if (options.moduleMetadata || options.applicationKey) {
9333
- var metadata = {};
9334
- if (options.applicationKey) {
9335
- // We use different keys so that if user-code receives multiple bundling passes, we will store the application keys of all the passes.
9336
- // It is a bit unfortunate that we have to inject the metadata snippet at the top, because after multiple
9337
- // injections, the first injection will always "win" because it comes last in the code. We would generally be
9338
- // fine with making the last bundling pass win. But because it cannot win, we have to use a workaround of storing
9339
- // the app keys in different object keys.
9340
- // We can simply use the `_sentryBundlerPluginAppKey:` to filter for app keys in the SDK.
9341
- metadata["_sentryBundlerPluginAppKey:".concat(options.applicationKey)] = true;
9342
- }
9343
- if (typeof options.moduleMetadata === "function") {
9344
- var args = {
9345
- org: options.org,
9346
- project: options.project,
9347
- release: options.release.name
9348
- };
9349
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
9350
- metadata = _objectSpread2(_objectSpread2({}, metadata), options.moduleMetadata(args));
9351
- } else {
9352
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
9353
- metadata = _objectSpread2(_objectSpread2({}, metadata), options.moduleMetadata);
9354
- }
9355
- var _injectionCode2 = generateModuleMetadataInjectorCode(metadata);
9438
+ if (Object.keys(sentryBuildPluginManager.bundleMetadata).length > 0) {
9439
+ var _injectionCode2 = generateModuleMetadataInjectorCode(sentryBuildPluginManager.bundleMetadata);
9356
9440
  plugins.push(moduleMetadataInjectionPlugin(_injectionCode2));
9357
9441
  }
9358
- // https://turbo.build/repo/docs/reference/system-environment-variables#environment-variables-in-tasks
9359
- var isRunningInTurborepo = Boolean(process.env["TURBO_HASH"]);
9360
- var getTurborepoEnvPassthroughWarning = function getTurborepoEnvPassthroughWarning(envVarName) {
9361
- return isRunningInTurborepo ? "\nYou seem to be using Turborepo, did you forget to put ".concat(envVarName, " in `passThroughEnv`? https://turbo.build/repo/docs/reference/configuration#passthroughenv") : "";
9362
- };
9363
- if (!options.release.name) {
9364
- logger.debug("No release name provided. Will not create release. Please set the `release.name` option to identify your release.");
9365
- } else if (isDevMode) {
9366
- logger.debug("Running in development mode. Will not create release.");
9367
- } else if (!options.authToken) {
9368
- logger.warn("No auth token provided. Will not create release. Please set the `authToken` option. You can find information on how to generate a Sentry auth token here: https://docs.sentry.io/api/auth/" + getTurborepoEnvPassthroughWarning("SENTRY_AUTH_TOKEN"));
9369
- } else if (!options.org && !options.authToken.startsWith("sntrys_")) {
9370
- logger.warn("No organization slug provided. Will not create release. Please set the `org` option to your Sentry organization slug." + getTurborepoEnvPassthroughWarning("SENTRY_ORG"));
9371
- } else if (!options.project) {
9372
- logger.warn("No project provided. Will not create release. Please set the `project` option to your Sentry project slug." + getTurborepoEnvPassthroughWarning("SENTRY_PROJECT"));
9373
- } else {
9374
- plugins.push(releaseManagementPlugin({
9375
- logger: logger,
9376
- releaseName: options.release.name,
9377
- shouldCreateRelease: options.release.create,
9378
- shouldFinalizeRelease: options.release.finalize,
9379
- include: options.release.uploadLegacySourcemaps,
9380
- // setCommits has a default defined by the options mappings
9381
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
9382
- setCommitsOption: options.release.setCommits,
9383
- deployOptions: options.release.deploy,
9384
- dist: options.release.dist,
9385
- handleRecoverableError: handleRecoverableError,
9386
- sentryScope: sentryScope,
9387
- sentryClient: sentryClient,
9388
- sentryCliOptions: {
9389
- authToken: options.authToken,
9390
- org: options.org,
9391
- project: options.project,
9392
- silent: options.silent,
9393
- url: options.url,
9394
- vcsRemote: options.release.vcsRemote,
9395
- headers: options.headers
9396
- },
9397
- createDependencyOnSourcemapFiles: createDependencyOnSourcemapFiles
9398
- }));
9399
- }
9442
+
9443
+ // Add plugin to create and finalize releases, and also take care of adding commits and legacy sourcemaps
9444
+ var freeGlobalDependencyOnBuildArtifacts = sentryBuildPluginManager.createDependencyOnBuildArtifacts();
9445
+ plugins.push({
9446
+ name: "sentry-release-management-plugin",
9447
+ writeBundle: function writeBundle() {
9448
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
9449
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
9450
+ while (1) switch (_context2.prev = _context2.next) {
9451
+ case 0:
9452
+ _context2.prev = 0;
9453
+ _context2.next = 3;
9454
+ return sentryBuildPluginManager.createRelease();
9455
+ case 3:
9456
+ _context2.prev = 3;
9457
+ freeGlobalDependencyOnBuildArtifacts();
9458
+ return _context2.finish(3);
9459
+ case 6:
9460
+ case "end":
9461
+ return _context2.stop();
9462
+ }
9463
+ }, _callee2, null, [[0,, 3, 6]]);
9464
+ }))();
9465
+ }
9466
+ });
9400
9467
  if (!((_options$sourcemaps = options.sourcemaps) !== null && _options$sourcemaps !== void 0 && _options$sourcemaps.disable)) {
9401
9468
  plugins.push(debugIdInjectionPlugin(logger));
9402
9469
  }
9403
- if ((_options$sourcemaps2 = options.sourcemaps) !== null && _options$sourcemaps2 !== void 0 && _options$sourcemaps2.disable) {
9404
- logger.debug("Source map upload was disabled. Will not upload sourcemaps using debug ID process.");
9405
- } else if (isDevMode) {
9406
- logger.debug("Running in development mode. Will not upload sourcemaps.");
9407
- } else if (!options.authToken) {
9408
- logger.warn("No auth token provided. Will not upload source maps. Please set the `authToken` option. You can find information on how to generate a Sentry auth token here: https://docs.sentry.io/api/auth/" + getTurborepoEnvPassthroughWarning("SENTRY_AUTH_TOKEN"));
9409
- } else if (!options.org && !options.authToken.startsWith("sntrys_")) {
9410
- logger.warn("No org provided. Will not upload source maps. Please set the `org` option to your Sentry organization slug." + getTurborepoEnvPassthroughWarning("SENTRY_ORG"));
9411
- } else if (!options.project) {
9412
- logger.warn("No project provided. Will not upload source maps. Please set the `project` option to your Sentry project slug." + getTurborepoEnvPassthroughWarning("SENTRY_PROJECT"));
9413
- } else {
9414
- var _options$sourcemaps3, _options$sourcemaps4, _options$sourcemaps5;
9415
- // This option is only strongly typed for the webpack plugin, where it is used. It has no effect on other plugins
9416
- var _webpack_forceExitOnBuildComplete = typeof options._experiments["forceExitOnBuildCompletion"] === "boolean" ? options._experiments["forceExitOnBuildCompletion"] : undefined;
9417
- plugins.push(debugIdUploadPlugin(createDebugIdUploadFunction({
9418
- assets: (_options$sourcemaps3 = options.sourcemaps) === null || _options$sourcemaps3 === void 0 ? void 0 : _options$sourcemaps3.assets,
9419
- ignore: (_options$sourcemaps4 = options.sourcemaps) === null || _options$sourcemaps4 === void 0 ? void 0 : _options$sourcemaps4.ignore,
9420
- createDependencyOnSourcemapFiles: createDependencyOnSourcemapFiles,
9421
- dist: options.release.dist,
9422
- releaseName: options.release.name,
9423
- logger: logger,
9424
- handleRecoverableError: handleRecoverableError,
9425
- rewriteSourcesHook: (_options$sourcemaps5 = options.sourcemaps) === null || _options$sourcemaps5 === void 0 ? void 0 : _options$sourcemaps5.rewriteSources,
9426
- sentryScope: sentryScope,
9427
- sentryClient: sentryClient,
9428
- sentryCliOptions: {
9429
- authToken: options.authToken,
9430
- org: options.org,
9431
- project: options.project,
9432
- silent: options.silent,
9433
- url: options.url,
9434
- vcsRemote: options.release.vcsRemote,
9435
- headers: options.headers
9436
- }
9437
- }), logger, _webpack_forceExitOnBuildComplete));
9438
- }
9470
+
9471
+ // This option is only strongly typed for the webpack plugin, where it is used. It has no effect on other plugins
9472
+ var webpack_forceExitOnBuildComplete = typeof options._experiments["forceExitOnBuildCompletion"] === "boolean" ? options._experiments["forceExitOnBuildCompletion"] : undefined;
9473
+ plugins.push(debugIdUploadPlugin(createDebugIdUploadFunction({
9474
+ sentryBuildPluginManager: sentryBuildPluginManager
9475
+ }), logger, sentryBuildPluginManager.createDependencyOnBuildArtifacts, webpack_forceExitOnBuildComplete));
9439
9476
  if (options.reactComponentAnnotation) {
9440
9477
  if (!options.reactComponentAnnotation.enabled) {
9441
9478
  logger.debug("The component name annotate plugin is currently disabled. Skipping component name annotations.");
@@ -9445,17 +9482,33 @@ function sentryUnpluginFactory(_ref) {
9445
9482
  componentNameAnnotatePlugin && plugins.push(componentNameAnnotatePlugin(options.reactComponentAnnotation.ignoredComponents));
9446
9483
  }
9447
9484
  }
9448
- plugins.push(fileDeletionPlugin({
9449
- waitUntilSourcemapFileDependenciesAreFreed: waitUntilSourcemapFileDependenciesAreFreed,
9450
- filesToDeleteAfterUpload: (_options$sourcemaps6 = options.sourcemaps) === null || _options$sourcemaps6 === void 0 ? void 0 : _options$sourcemaps6.filesToDeleteAfterUpload,
9451
- logger: logger,
9452
- handleRecoverableError: handleRecoverableError,
9453
- sentryScope: sentryScope,
9454
- sentryClient: sentryClient
9455
- }));
9485
+
9486
+ // Add plugin to delete unwanted artifacts like source maps after the uploads have completed
9487
+ plugins.push({
9488
+ name: "sentry-file-deletion-plugin",
9489
+ writeBundle: function writeBundle() {
9490
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
9491
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
9492
+ while (1) switch (_context3.prev = _context3.next) {
9493
+ case 0:
9494
+ _context3.next = 2;
9495
+ return sentryBuildPluginManager.deleteArtifacts();
9496
+ case 2:
9497
+ case "end":
9498
+ return _context3.stop();
9499
+ }
9500
+ }, _callee3);
9501
+ }))();
9502
+ }
9503
+ });
9456
9504
  return plugins;
9457
9505
  });
9458
9506
  }
9507
+
9508
+ /**
9509
+ * @deprecated
9510
+ */
9511
+ // TODO(v4): Don't export this from the package
9459
9512
  function getBuildInformation() {
9460
9513
  var packageJson = getPackageJson();
9461
9514
  var _ref2 = packageJson ? getDependencies(packageJson) : {
@@ -9616,20 +9669,22 @@ function createRollupModuleMetadataInjectionHooks(injectionCode) {
9616
9669
  };
9617
9670
  }
9618
9671
 
9619
- function createRollupDebugIdUploadHooks(upload) {
9672
+ function createRollupDebugIdUploadHooks(upload, _logger, createDependencyOnBuildArtifacts) {
9673
+ var freeGlobalDependencyOnDebugIdSourcemapArtifacts = createDependencyOnBuildArtifacts();
9620
9674
  return {
9621
9675
  writeBundle: function writeBundle(outputOptions, bundle) {
9622
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
9676
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
9623
9677
  var outputDir, _buildArtifacts, _buildArtifacts2;
9624
- return _regeneratorRuntime().wrap(function _callee$(_context) {
9625
- while (1) switch (_context.prev = _context.next) {
9678
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
9679
+ while (1) switch (_context4.prev = _context4.next) {
9626
9680
  case 0:
9681
+ _context4.prev = 0;
9627
9682
  if (!outputOptions.dir) {
9628
- _context.next = 9;
9683
+ _context4.next = 10;
9629
9684
  break;
9630
9685
  }
9631
9686
  outputDir = outputOptions.dir;
9632
- _context.next = 4;
9687
+ _context4.next = 5;
9633
9688
  return glob.glob(["/**/*.js", "/**/*.mjs", "/**/*.cjs", "/**/*.js.map", "/**/*.mjs.map", "/**/*.cjs.map"].map(function (q) {
9634
9689
  return "".concat(q, "?(\\?*)?(#*)");
9635
9690
  }),
@@ -9639,34 +9694,38 @@ function createRollupDebugIdUploadHooks(upload) {
9639
9694
  absolute: true,
9640
9695
  nodir: true
9641
9696
  });
9642
- case 4:
9643
- _buildArtifacts = _context.sent;
9644
- _context.next = 7;
9697
+ case 5:
9698
+ _buildArtifacts = _context4.sent;
9699
+ _context4.next = 8;
9645
9700
  return upload(_buildArtifacts);
9646
- case 7:
9647
- _context.next = 17;
9701
+ case 8:
9702
+ _context4.next = 18;
9648
9703
  break;
9649
- case 9:
9704
+ case 10:
9650
9705
  if (!outputOptions.file) {
9651
- _context.next = 14;
9706
+ _context4.next = 15;
9652
9707
  break;
9653
9708
  }
9654
- _context.next = 12;
9709
+ _context4.next = 13;
9655
9710
  return upload([outputOptions.file]);
9656
- case 12:
9657
- _context.next = 17;
9711
+ case 13:
9712
+ _context4.next = 18;
9658
9713
  break;
9659
- case 14:
9714
+ case 15:
9660
9715
  _buildArtifacts2 = Object.keys(bundle).map(function (asset) {
9661
9716
  return path__namespace.join(path__namespace.resolve(), asset);
9662
9717
  });
9663
- _context.next = 17;
9718
+ _context4.next = 18;
9664
9719
  return upload(_buildArtifacts2);
9665
- case 17:
9720
+ case 18:
9721
+ _context4.prev = 18;
9722
+ freeGlobalDependencyOnDebugIdSourcemapArtifacts();
9723
+ return _context4.finish(18);
9724
+ case 21:
9666
9725
  case "end":
9667
- return _context.stop();
9726
+ return _context4.stop();
9668
9727
  }
9669
- }, _callee);
9728
+ }, _callee4, null, [[0,, 18, 21]]);
9670
9729
  }))();
9671
9730
  }
9672
9731
  };
@@ -9674,26 +9733,26 @@ function createRollupDebugIdUploadHooks(upload) {
9674
9733
  function createComponentNameAnnotateHooks(ignoredComponents) {
9675
9734
  return {
9676
9735
  transform: function transform(code, id) {
9677
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
9736
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
9678
9737
  var idWithoutQueryAndHash, parserPlugins, _result$code, result;
9679
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
9680
- while (1) switch (_context2.prev = _context2.next) {
9738
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
9739
+ while (1) switch (_context5.prev = _context5.next) {
9681
9740
  case 0:
9682
9741
  // id may contain query and hash which will trip up our file extension logic below
9683
9742
  idWithoutQueryAndHash = stripQueryAndHashFromPath(id);
9684
9743
  if (!idWithoutQueryAndHash.match(/\\node_modules\\|\/node_modules\//)) {
9685
- _context2.next = 3;
9744
+ _context5.next = 3;
9686
9745
  break;
9687
9746
  }
9688
- return _context2.abrupt("return", null);
9747
+ return _context5.abrupt("return", null);
9689
9748
  case 3:
9690
9749
  if ([".jsx", ".tsx"].some(function (ending) {
9691
9750
  return idWithoutQueryAndHash.endsWith(ending);
9692
9751
  })) {
9693
- _context2.next = 5;
9752
+ _context5.next = 5;
9694
9753
  break;
9695
9754
  }
9696
- return _context2.abrupt("return", null);
9755
+ return _context5.abrupt("return", null);
9697
9756
  case 5:
9698
9757
  parserPlugins = [];
9699
9758
  if (idWithoutQueryAndHash.endsWith(".jsx")) {
@@ -9701,8 +9760,8 @@ function createComponentNameAnnotateHooks(ignoredComponents) {
9701
9760
  } else if (idWithoutQueryAndHash.endsWith(".tsx")) {
9702
9761
  parserPlugins.push("jsx", "typescript");
9703
9762
  }
9704
- _context2.prev = 7;
9705
- _context2.next = 10;
9763
+ _context5.prev = 7;
9764
+ _context5.next = 10;
9706
9765
  return core.transformAsync(code, {
9707
9766
  plugins: [[componentNameAnnotatePlugin__default["default"], {
9708
9767
  ignoredComponents: ignoredComponents
@@ -9719,24 +9778,24 @@ function createComponentNameAnnotateHooks(ignoredComponents) {
9719
9778
  sourceMaps: true
9720
9779
  });
9721
9780
  case 10:
9722
- result = _context2.sent;
9723
- return _context2.abrupt("return", {
9781
+ result = _context5.sent;
9782
+ return _context5.abrupt("return", {
9724
9783
  code: (_result$code = result === null || result === void 0 ? void 0 : result.code) !== null && _result$code !== void 0 ? _result$code : code,
9725
9784
  map: result === null || result === void 0 ? void 0 : result.map
9726
9785
  });
9727
9786
  case 14:
9728
- _context2.prev = 14;
9729
- _context2.t0 = _context2["catch"](7);
9730
- logger.error("Failed to apply react annotate plugin", _context2.t0);
9787
+ _context5.prev = 14;
9788
+ _context5.t0 = _context5["catch"](7);
9789
+ logger.error("Failed to apply react annotate plugin", _context5.t0);
9731
9790
  case 17:
9732
- return _context2.abrupt("return", {
9791
+ return _context5.abrupt("return", {
9733
9792
  code: code
9734
9793
  });
9735
9794
  case 18:
9736
9795
  case "end":
9737
- return _context2.stop();
9796
+ return _context5.stop();
9738
9797
  }
9739
- }, _callee2, null, [[7, 14]]);
9798
+ }, _callee5, null, [[7, 14]]);
9740
9799
  }))();
9741
9800
  }
9742
9801
  };