@sentry/bundler-plugin-core 3.3.0-alpha.0 → 3.3.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');
5
6
  var core = require('@babel/core');
6
7
  var componentNameAnnotatePlugin = require('@sentry/babel-plugin-component-annotate');
7
- var SentryCli = require('@sentry/cli');
8
8
  var fs = require('fs');
9
- var glob = require('glob');
10
- var MagicString = require('magic-string');
11
9
  var path = require('path');
10
+ var MagicString = require('magic-string');
12
11
  var unplugin = require('unplugin');
13
- var dotenv = require('dotenv');
14
- var os = require('os');
15
12
  var findUp = require('find-up');
13
+ var os = require('os');
16
14
  var crypto = require('crypto');
17
15
  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 util = require('util');
21
+ var dotenv = require('dotenv');
22
22
 
23
23
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
24
24
 
@@ -40,21 +40,20 @@ function _interopNamespace(e) {
40
40
  return Object.freeze(n);
41
41
  }
42
42
 
43
- var componentNameAnnotatePlugin__default = /*#__PURE__*/_interopDefaultLegacy(componentNameAnnotatePlugin);
44
43
  var SentryCli__default = /*#__PURE__*/_interopDefaultLegacy(SentryCli);
44
+ var componentNameAnnotatePlugin__default = /*#__PURE__*/_interopDefaultLegacy(componentNameAnnotatePlugin);
45
45
  var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
46
46
  var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
47
- var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
48
47
  var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
49
48
  var path__namespace = /*#__PURE__*/_interopNamespace(path);
50
- var dotenv__namespace = /*#__PURE__*/_interopNamespace(dotenv);
51
- var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
52
- var os__namespace = /*#__PURE__*/_interopNamespace(os);
49
+ var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
53
50
  var findUp__default = /*#__PURE__*/_interopDefaultLegacy(findUp);
51
+ var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
54
52
  var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
55
53
  var childProcess__default = /*#__PURE__*/_interopDefaultLegacy(childProcess);
56
- var https__namespace = /*#__PURE__*/_interopNamespace(https);
57
54
  var util__namespace = /*#__PURE__*/_interopNamespace(util);
55
+ var https__namespace = /*#__PURE__*/_interopNamespace(https);
56
+ var dotenv__namespace = /*#__PURE__*/_interopNamespace(dotenv);
58
57
 
59
58
  function ownKeys(object, enumerableOnly) {
60
59
  var keys = Object.keys(object);
@@ -446,204 +445,595 @@ function _toPropertyKey(arg) {
446
445
  return typeof key === "symbol" ? key : String(key);
447
446
  }
448
447
 
449
- // eslint-disable-next-line @typescript-eslint/unbound-method
450
- const objectToString = Object.prototype.toString;
451
-
452
448
  /**
453
- * Checks whether given value's type is one of a few Error or Error-like
454
- * {@link isError}.
449
+ * Checks whether the given input is already an array, and if it isn't, wraps it in one.
455
450
  *
456
- * @param wat A value to be checked.
457
- * @returns A boolean representing the result.
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
458
453
  */
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
- }
454
+ function arrayify$1(maybeArray) {
455
+ return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
468
456
  }
469
457
  /**
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.
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
475
462
  */
476
- function isBuiltin(wat, className) {
477
- return objectToString.call(wat) === `[object ${className}]`;
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()));
478
468
  }
469
+ function parseMajorVersion(version) {
470
+ // if it has a `v` prefix, remove it
471
+ if (version.startsWith("v")) {
472
+ version = version.slice(1);
473
+ }
479
474
 
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');
489
- }
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
+ }
490
481
 
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');
500
- }
482
+ // Try to parse e.g. 1.x
483
+ var coerced = parseInt(version, 10);
484
+ if (!Number.isNaN(coerced)) {
485
+ return coerced;
486
+ }
501
487
 
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
- );
516
- }
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
+ }
517
494
 
518
- /**
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.
524
- */
525
- function isPrimitive(wat) {
526
- return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');
527
- }
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
528
502
 
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');
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;
538
524
  }
539
525
 
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);
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
+ };
549
546
  }
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);
550
563
 
551
- /**
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.
557
- */
558
- function isElement(wat) {
559
- return typeof Element !== 'undefined' && isInstanceOf(wat, Element);
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
+
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);
560
576
  }
561
577
 
562
578
  /**
563
- * Checks whether given value has a then function.
564
- * @param wat A value to be checked.
579
+ * Deterministically hashes a string and turns the hash into a uuid.
565
580
  */
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');
581
+ function stringToUUID(str) {
582
+ var sha256Hash = crypto__default["default"].createHash("sha256").update(str).digest("hex");
583
+
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();
588
+ }
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;
569
599
  }
570
600
 
571
601
  /**
572
- * Checks whether given value's type is a SyntheticEvent
573
- * {@link isSyntheticEvent}.
574
- *
575
- * @param wat A value to be checked.
576
- * @returns A boolean representing the result.
602
+ * Tries to guess a release name based on environmental data.
577
603
  */
578
- function isSyntheticEvent(wat) {
579
- return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;
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();
580
678
  }
581
679
 
582
680
  /**
583
- * Checks whether given value's type is an instance of provided constructor.
584
- * {@link isInstanceOf}.
585
- *
586
- * @param wat A value to be checked.
587
- * @param base A constructor to be used in a check.
588
- * @returns A boolean representing the result.
681
+ * Generates code for the global injector which is responsible for setting the global
682
+ * `SENTRY_RELEASE` & `SENTRY_BUILD_INFO` variables.
589
683
  */
590
- function isInstanceOf(wat, base) {
591
- try {
592
- return wat instanceof base;
593
- } catch (_e) {
594
- return false;
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), ";");
595
693
  }
694
+ code += "}";
695
+ return code;
596
696
  }
597
697
 
598
- /**
599
- * Checks whether given value's type is a Vue ViewModel.
600
- *
601
- * @param wat A value to be checked.
602
- * @returns A boolean representing the result.
603
- */
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));
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}");
607
704
  }
608
-
609
- /**
610
- * Truncates given string to the maximum characters count
611
- *
612
- * @param str An object that contains serializable values
613
- * @param max Maximum number of characters in truncated string (0 = unlimited)
614
- * @returns string Encoded
615
- */
616
- function truncate(str, max = 0) {
617
- if (typeof str !== 'string' || max === 0) {
618
- return str;
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
+ };
619
738
  }
620
- return str.length <= max ? str : `${str.slice(0, max)}...`;
739
+ return null;
621
740
  }
622
741
 
623
- const SDK_VERSION = '8.30.0';
624
-
625
- /** Get's the global object for the current JavaScript runtime */
626
- const GLOBAL_OBJ = globalThis ;
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
+ // We only want to set commits for the production env because Sentry becomes extremely noisy (eg on slack) for
779
+ // preview environments because the previous commit is always the "stem" commit of the preview/PR causing Sentry
780
+ // to notify you for other people creating PRs.
781
+ process.env["VERCEL_TARGET_ENV"] === "production") {
782
+ options.release.setCommits = {
783
+ shouldNotThrowOnFailure: true,
784
+ commit: process.env["VERCEL_GIT_COMMIT_SHA"],
785
+ previousCommit: process.env["VERCEL_GIT_PREVIOUS_SHA"],
786
+ repo: "".concat(process.env["VERCEL_GIT_REPO_OWNER"], "/").concat(process.env["VERCEL_GIT_REPO_SLUG"]),
787
+ ignoreEmpty: true,
788
+ ignoreMissing: true
789
+ };
790
+ } else {
791
+ options.release.setCommits = {
792
+ shouldNotThrowOnFailure: true,
793
+ auto: true,
794
+ ignoreEmpty: true,
795
+ ignoreMissing: true
796
+ };
797
+ }
798
+ }
799
+ if (options.release.deploy === undefined && process.env["VERCEL"] && process.env["VERCEL_TARGET_ENV"]) {
800
+ options.release.deploy = {
801
+ env: "vercel-".concat(process.env["VERCEL_TARGET_ENV"]),
802
+ url: process.env["VERCEL_URL"] ? "https://".concat(process.env["VERCEL_URL"]) : undefined
803
+ };
804
+ }
805
+ return options;
806
+ }
627
807
 
628
808
  /**
629
- * Returns a global singleton contained in the global `__SENTRY__[]` object.
809
+ * Validates a few combinations of options that are not checked by Sentry CLI.
630
810
  *
631
- * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory
632
- * function and added to the `__SENTRY__` object.
811
+ * For all other options, we can rely on Sentry CLI to validate them. In fact,
812
+ * we can't validate them in the plugin because Sentry CLI might pick up options from
813
+ * its config file.
633
814
  *
634
- * @param name name of the global singleton on __SENTRY__
635
- * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`
636
- * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value
637
- * @returns the singleton
815
+ * @param options the internal options
816
+ * @param logger the logger
817
+ *
818
+ * @returns `true` if the options are valid, `false` otherwise
638
819
  */
639
- function getGlobalSingleton(name, creator, obj) {
640
- const gbl = (obj || GLOBAL_OBJ) ;
641
- const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});
642
- const versionedCarrier = (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});
643
- return versionedCarrier[name] || (versionedCarrier[name] = creator());
644
- }
645
-
646
- const WINDOW = GLOBAL_OBJ ;
820
+ function validateOptions(options, logger) {
821
+ var _options$release, _options$release2, _options$release3;
822
+ var setCommits = (_options$release = options.release) === null || _options$release === void 0 ? void 0 : _options$release.setCommits;
823
+ if (setCommits) {
824
+ if (!setCommits.auto && !(setCommits.repo && setCommits.commit)) {
825
+ logger.error("The `setCommits` option was specified but is missing required properties.", "Please set either `auto` or both, `repo` and `commit`.");
826
+ return false;
827
+ }
828
+ if (setCommits.auto && setCommits.repo && setCommits) {
829
+ 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`.");
830
+ }
831
+ }
832
+ 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)) {
833
+ logger.error("The `deploy` option was specified but is missing the required `env` property.", "Please set the `env` property.");
834
+ return false;
835
+ }
836
+ return true;
837
+ }
838
+
839
+ // eslint-disable-next-line @typescript-eslint/unbound-method
840
+ const objectToString = Object.prototype.toString;
841
+
842
+ /**
843
+ * Checks whether given value's type is one of a few Error or Error-like
844
+ * {@link isError}.
845
+ *
846
+ * @param wat A value to be checked.
847
+ * @returns A boolean representing the result.
848
+ */
849
+ function isError(wat) {
850
+ switch (objectToString.call(wat)) {
851
+ case '[object Error]':
852
+ case '[object Exception]':
853
+ case '[object DOMException]':
854
+ return true;
855
+ default:
856
+ return isInstanceOf(wat, Error);
857
+ }
858
+ }
859
+ /**
860
+ * Checks whether given value is an instance of the given built-in class.
861
+ *
862
+ * @param wat The value to be checked
863
+ * @param className
864
+ * @returns A boolean representing the result.
865
+ */
866
+ function isBuiltin(wat, className) {
867
+ return objectToString.call(wat) === `[object ${className}]`;
868
+ }
869
+
870
+ /**
871
+ * Checks whether given value's type is ErrorEvent
872
+ * {@link isErrorEvent}.
873
+ *
874
+ * @param wat A value to be checked.
875
+ * @returns A boolean representing the result.
876
+ */
877
+ function isErrorEvent$1(wat) {
878
+ return isBuiltin(wat, 'ErrorEvent');
879
+ }
880
+
881
+ /**
882
+ * Checks whether given value's type is a string
883
+ * {@link isString}.
884
+ *
885
+ * @param wat A value to be checked.
886
+ * @returns A boolean representing the result.
887
+ */
888
+ function isString(wat) {
889
+ return isBuiltin(wat, 'String');
890
+ }
891
+
892
+ /**
893
+ * Checks whether given string is parameterized
894
+ * {@link isParameterizedString}.
895
+ *
896
+ * @param wat A value to be checked.
897
+ * @returns A boolean representing the result.
898
+ */
899
+ function isParameterizedString(wat) {
900
+ return (
901
+ typeof wat === 'object' &&
902
+ wat !== null &&
903
+ '__sentry_template_string__' in wat &&
904
+ '__sentry_template_values__' in wat
905
+ );
906
+ }
907
+
908
+ /**
909
+ * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)
910
+ * {@link isPrimitive}.
911
+ *
912
+ * @param wat A value to be checked.
913
+ * @returns A boolean representing the result.
914
+ */
915
+ function isPrimitive(wat) {
916
+ return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');
917
+ }
918
+
919
+ /**
920
+ * Checks whether given value's type is an object literal, or a class instance.
921
+ * {@link isPlainObject}.
922
+ *
923
+ * @param wat A value to be checked.
924
+ * @returns A boolean representing the result.
925
+ */
926
+ function isPlainObject(wat) {
927
+ return isBuiltin(wat, 'Object');
928
+ }
929
+
930
+ /**
931
+ * Checks whether given value's type is an Event instance
932
+ * {@link isEvent}.
933
+ *
934
+ * @param wat A value to be checked.
935
+ * @returns A boolean representing the result.
936
+ */
937
+ function isEvent(wat) {
938
+ return typeof Event !== 'undefined' && isInstanceOf(wat, Event);
939
+ }
940
+
941
+ /**
942
+ * Checks whether given value's type is an Element instance
943
+ * {@link isElement}.
944
+ *
945
+ * @param wat A value to be checked.
946
+ * @returns A boolean representing the result.
947
+ */
948
+ function isElement(wat) {
949
+ return typeof Element !== 'undefined' && isInstanceOf(wat, Element);
950
+ }
951
+
952
+ /**
953
+ * Checks whether given value has a then function.
954
+ * @param wat A value to be checked.
955
+ */
956
+ function isThenable(wat) {
957
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
958
+ return Boolean(wat && wat.then && typeof wat.then === 'function');
959
+ }
960
+
961
+ /**
962
+ * Checks whether given value's type is a SyntheticEvent
963
+ * {@link isSyntheticEvent}.
964
+ *
965
+ * @param wat A value to be checked.
966
+ * @returns A boolean representing the result.
967
+ */
968
+ function isSyntheticEvent(wat) {
969
+ return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;
970
+ }
971
+
972
+ /**
973
+ * Checks whether given value's type is an instance of provided constructor.
974
+ * {@link isInstanceOf}.
975
+ *
976
+ * @param wat A value to be checked.
977
+ * @param base A constructor to be used in a check.
978
+ * @returns A boolean representing the result.
979
+ */
980
+ function isInstanceOf(wat, base) {
981
+ try {
982
+ return wat instanceof base;
983
+ } catch (_e) {
984
+ return false;
985
+ }
986
+ }
987
+
988
+ /**
989
+ * Checks whether given value's type is a Vue ViewModel.
990
+ *
991
+ * @param wat A value to be checked.
992
+ * @returns A boolean representing the result.
993
+ */
994
+ function isVueViewModel(wat) {
995
+ // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.
996
+ return !!(typeof wat === 'object' && wat !== null && ((wat ).__isVue || (wat )._isVue));
997
+ }
998
+
999
+ /**
1000
+ * Truncates given string to the maximum characters count
1001
+ *
1002
+ * @param str An object that contains serializable values
1003
+ * @param max Maximum number of characters in truncated string (0 = unlimited)
1004
+ * @returns string Encoded
1005
+ */
1006
+ function truncate(str, max = 0) {
1007
+ if (typeof str !== 'string' || max === 0) {
1008
+ return str;
1009
+ }
1010
+ return str.length <= max ? str : `${str.slice(0, max)}...`;
1011
+ }
1012
+
1013
+ const SDK_VERSION = '8.30.0';
1014
+
1015
+ /** Get's the global object for the current JavaScript runtime */
1016
+ const GLOBAL_OBJ = globalThis ;
1017
+
1018
+ /**
1019
+ * Returns a global singleton contained in the global `__SENTRY__[]` object.
1020
+ *
1021
+ * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory
1022
+ * function and added to the `__SENTRY__` object.
1023
+ *
1024
+ * @param name name of the global singleton on __SENTRY__
1025
+ * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`
1026
+ * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value
1027
+ * @returns the singleton
1028
+ */
1029
+ function getGlobalSingleton(name, creator, obj) {
1030
+ const gbl = (obj || GLOBAL_OBJ) ;
1031
+ const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});
1032
+ const versionedCarrier = (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});
1033
+ return versionedCarrier[name] || (versionedCarrier[name] = creator());
1034
+ }
1035
+
1036
+ const WINDOW = GLOBAL_OBJ ;
647
1037
 
648
1038
  const DEFAULT_MAX_STRING_LENGTH = 80;
649
1039
 
@@ -1719,7 +2109,7 @@ function checkOrSetAlreadyCaught(exception) {
1719
2109
  * @param maybeArray Input to turn into an array, if necessary
1720
2110
  * @returns The input, if already an array, or an array with the input as the only element, if not
1721
2111
  */
1722
- function arrayify$1(maybeArray) {
2112
+ function arrayify(maybeArray) {
1723
2113
  return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
1724
2114
  }
1725
2115
 
@@ -5839,7 +6229,7 @@ function applySpanToEvent(event, span) {
5839
6229
  */
5840
6230
  function applyFingerprintToEvent(event, fingerprint) {
5841
6231
  // Make sure it's an array first and we actually have something in place
5842
- event.fingerprint = event.fingerprint ? arrayify$1(event.fingerprint) : [];
6232
+ event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];
5843
6233
 
5844
6234
  // If we have something on the scope, then merge it with event
5845
6235
  if (fingerprint) {
@@ -7554,502 +7944,60 @@ function createTransport(
7554
7944
 
7555
7945
  return buffer.add(requestTask).then(
7556
7946
  result => result,
7557
- error => {
7558
- if (error instanceof SentryError) {
7559
- DEBUG_BUILD && logger.error('Skipped sending event because buffer is full.');
7560
- recordEnvelopeLoss('queue_overflow');
7561
- return resolvedSyncPromise({});
7562
- } else {
7563
- throw error;
7564
- }
7565
- },
7566
- );
7567
- }
7568
-
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") : "";
7910
- }
7911
-
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
- }
7947
+ error => {
7948
+ if (error instanceof SentryError) {
7949
+ DEBUG_BUILD && logger.error('Skipped sending event because buffer is full.');
7950
+ recordEnvelopeLoss('queue_overflow');
7951
+ return resolvedSyncPromise({});
7952
+ } else {
7953
+ throw error;
7954
+ }
7955
+ },
7956
+ );
7968
7957
  }
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
- };
7958
+
7959
+ return {
7960
+ send,
7961
+ flush,
7962
+ };
7963
+ }
7964
+
7965
+ function getEventForEnvelopeItem(item, type) {
7966
+ if (type !== 'event' && type !== 'transaction') {
7967
+ return undefined;
7974
7968
  }
7975
- return options;
7969
+
7970
+ return Array.isArray(item) ? (item )[1] : undefined;
7976
7971
  }
7977
7972
 
7978
7973
  /**
7979
- * Validates a few combinations of options that are not checked by Sentry CLI.
7974
+ * A builder for the SDK metadata in the options for the SDK initialization.
7980
7975
  *
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
+ * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.
7977
+ * We don't extract it for bundle size reasons.
7978
+ * @see https://github.com/getsentry/sentry-javascript/pull/7404
7979
+ * @see https://github.com/getsentry/sentry-javascript/pull/4196
7984
7980
  *
7985
- * @param options the internal options
7986
- * @param logger the logger
7981
+ * If you make changes to this function consider updating the others as well.
7987
7982
  *
7988
- * @returns `true` if the options are valid, `false` otherwise
7983
+ * @param options SDK options object that gets mutated
7984
+ * @param names list of package names
7989
7985
  */
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
- }
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;
7986
+ function applySdkMetadata(options, name, names = [name], source = 'npm') {
7987
+ const metadata = options._metadata || {};
7988
+
7989
+ if (!metadata.sdk) {
7990
+ metadata.sdk = {
7991
+ name: `sentry.javascript.${name}`,
7992
+ packages: names.map(name => ({
7993
+ name: `${source}:@sentry/${name}`,
7994
+ version: SDK_VERSION,
7995
+ })),
7996
+ version: SDK_VERSION,
7997
+ };
8005
7998
  }
8006
- return true;
8007
- }
8008
7999
 
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
- };
8000
+ options._metadata = metadata;
8053
8001
  }
8054
8002
 
8055
8003
  // Estimated maximum size for reasonable standalone event
@@ -8183,7 +8131,7 @@ function makeOptionallyEnabledNodeTransport(shouldSendTelemetry) {
8183
8131
 
8184
8132
  var SENTRY_SAAS_HOSTNAME = "sentry.io";
8185
8133
  var stackParser = createStackParser(nodeStackLineParser());
8186
- function createSentryInstance(options, shouldSendTelemetry, buildTool) {
8134
+ function createSentryInstance(options, shouldSendTelemetry, bundler) {
8187
8135
  var clientOptions = {
8188
8136
  platform: "node",
8189
8137
  runtime: {
@@ -8193,7 +8141,7 @@ function createSentryInstance(options, shouldSendTelemetry, buildTool) {
8193
8141
  dsn: "https://4c2bae7d9fbc413e8f7385f55c515d51@o1.ingest.sentry.io/6690737",
8194
8142
  tracesSampleRate: 1,
8195
8143
  sampleRate: 1,
8196
- release: "3.3.0-alpha.0",
8144
+ release: "3.3.0",
8197
8145
  integrations: [],
8198
8146
  tracePropagationTargets: ["sentry.io/api"],
8199
8147
  stackParser: stackParser,
@@ -8217,13 +8165,13 @@ function createSentryInstance(options, shouldSendTelemetry, buildTool) {
8217
8165
  var client = new ServerRuntimeClient(clientOptions);
8218
8166
  var scope = new Scope();
8219
8167
  scope.setClient(client);
8220
- setTelemetryDataOnScope(options, scope, buildTool);
8168
+ setTelemetryDataOnScope(options, scope, bundler);
8221
8169
  return {
8222
8170
  sentryScope: scope,
8223
8171
  sentryClient: client
8224
8172
  };
8225
8173
  }
8226
- function setTelemetryDataOnScope(options, scope, buildTool) {
8174
+ function setTelemetryDataOnScope(options, scope, bundler) {
8227
8175
  var _options$_metaOptions;
8228
8176
  var org = options.org,
8229
8177
  project = options.project,
@@ -8261,7 +8209,7 @@ function setTelemetryDataOnScope(options, scope, buildTool) {
8261
8209
  scope.setTags({
8262
8210
  organization: org,
8263
8211
  project: project,
8264
- bundler: buildTool
8212
+ bundler: bundler
8265
8213
  });
8266
8214
  scope.setUser({
8267
8215
  id: org
@@ -8358,26 +8306,297 @@ function _safeFlushTelemetry() {
8358
8306
  }
8359
8307
 
8360
8308
  function createDebugIdUploadFunction(_ref) {
8361
- var sentryBuildPluginManager = _ref.sentryBuildPluginManager;
8309
+ var assets = _ref.assets,
8310
+ ignore = _ref.ignore,
8311
+ logger = _ref.logger,
8312
+ releaseName = _ref.releaseName,
8313
+ dist = _ref.dist,
8314
+ handleRecoverableError = _ref.handleRecoverableError,
8315
+ sentryScope = _ref.sentryScope,
8316
+ sentryClient = _ref.sentryClient,
8317
+ sentryCliOptions = _ref.sentryCliOptions,
8318
+ rewriteSourcesHook = _ref.rewriteSourcesHook,
8319
+ createDependencyOnSourcemapFiles = _ref.createDependencyOnSourcemapFiles;
8320
+ var freeGlobalDependencyOnSourcemapFiles = createDependencyOnSourcemapFiles();
8362
8321
  return /*#__PURE__*/function () {
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) {
8322
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(buildArtifactPaths) {
8323
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
8324
+ while (1) switch (_context9.prev = _context9.next) {
8366
8325
  case 0:
8367
- _context.next = 2;
8368
- return sentryBuildPluginManager.uploadSourcemaps(buildArtifactPaths);
8326
+ _context9.next = 2;
8327
+ return startSpan(
8328
+ // This is `forceTransaction`ed because this span is used in dashboards in the form of indexed transactions.
8329
+ {
8330
+ name: "debug-id-sourcemap-upload",
8331
+ scope: sentryScope,
8332
+ forceTransaction: true
8333
+ }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
8334
+ var folderToCleanUp, freeUploadDependencyOnSourcemapFiles, tmpUploadFolder, globAssets, globResult, debugIdChunkFilePaths;
8335
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
8336
+ while (1) switch (_context8.prev = _context8.next) {
8337
+ case 0:
8338
+ // 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`)
8339
+ // Therefore we need to actually register the execution of this hook as dependency on the sourcemap files.
8340
+ freeUploadDependencyOnSourcemapFiles = createDependencyOnSourcemapFiles();
8341
+ _context8.prev = 1;
8342
+ _context8.next = 4;
8343
+ return startSpan({
8344
+ name: "mkdtemp",
8345
+ scope: sentryScope
8346
+ }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
8347
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
8348
+ while (1) switch (_context.prev = _context.next) {
8349
+ case 0:
8350
+ _context.next = 2;
8351
+ return fs__default["default"].promises.mkdtemp(path__default["default"].join(os__default["default"].tmpdir(), "sentry-bundler-plugin-upload-"));
8352
+ case 2:
8353
+ return _context.abrupt("return", _context.sent);
8354
+ case 3:
8355
+ case "end":
8356
+ return _context.stop();
8357
+ }
8358
+ }, _callee);
8359
+ })));
8360
+ case 4:
8361
+ tmpUploadFolder = _context8.sent;
8362
+ folderToCleanUp = tmpUploadFolder;
8363
+ if (assets) {
8364
+ globAssets = assets;
8365
+ } else {
8366
+ logger.debug("No `sourcemaps.assets` option provided, falling back to uploading detected build artifacts.");
8367
+ globAssets = buildArtifactPaths;
8368
+ }
8369
+ _context8.next = 9;
8370
+ return startSpan({
8371
+ name: "glob",
8372
+ scope: sentryScope
8373
+ }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
8374
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
8375
+ while (1) switch (_context2.prev = _context2.next) {
8376
+ case 0:
8377
+ _context2.next = 2;
8378
+ return glob.glob(globAssets, {
8379
+ absolute: true,
8380
+ nodir: true,
8381
+ ignore: ignore
8382
+ });
8383
+ case 2:
8384
+ return _context2.abrupt("return", _context2.sent);
8385
+ case 3:
8386
+ case "end":
8387
+ return _context2.stop();
8388
+ }
8389
+ }, _callee2);
8390
+ })));
8391
+ case 9:
8392
+ globResult = _context8.sent;
8393
+ debugIdChunkFilePaths = globResult.filter(function (debugIdChunkFilePath) {
8394
+ return !!stripQueryAndHashFromPath(debugIdChunkFilePath).match(/\.(js|mjs|cjs)$/);
8395
+ }); // The order of the files output by glob() is not deterministic
8396
+ // Ensure order within the files so that {debug-id}-{chunkIndex} coupling is consistent
8397
+ debugIdChunkFilePaths.sort();
8398
+ if (!(Array.isArray(assets) && assets.length === 0)) {
8399
+ _context8.next = 16;
8400
+ break;
8401
+ }
8402
+ logger.debug("Empty `sourcemaps.assets` option provided. Will not upload sourcemaps with debug ID.");
8403
+ _context8.next = 23;
8404
+ break;
8405
+ case 16:
8406
+ if (!(debugIdChunkFilePaths.length === 0)) {
8407
+ _context8.next = 20;
8408
+ break;
8409
+ }
8410
+ logger.warn("Didn't find any matching sources for debug ID upload. Please check the `sourcemaps.assets` option.");
8411
+ _context8.next = 23;
8412
+ break;
8413
+ case 20:
8414
+ _context8.next = 22;
8415
+ return startSpan({
8416
+ name: "prepare-bundles",
8417
+ scope: sentryScope
8418
+ }, /*#__PURE__*/function () {
8419
+ var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(prepBundlesSpan) {
8420
+ var preparationTasks, workers, worker, workerIndex, files, stats, uploadSize;
8421
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
8422
+ while (1) switch (_context6.prev = _context6.next) {
8423
+ case 0:
8424
+ // Preparing the bundles can be a lot of work and doing it all at once has the potential of nuking the heap so
8425
+ // instead we do it with a maximum of 16 concurrent workers
8426
+ preparationTasks = debugIdChunkFilePaths.map(function (chunkFilePath, chunkIndex) {
8427
+ return /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
8428
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
8429
+ while (1) switch (_context3.prev = _context3.next) {
8430
+ case 0:
8431
+ _context3.next = 2;
8432
+ return prepareBundleForDebugIdUpload(chunkFilePath, tmpUploadFolder, chunkIndex, logger, rewriteSourcesHook !== null && rewriteSourcesHook !== void 0 ? rewriteSourcesHook : defaultRewriteSourcesHook);
8433
+ case 2:
8434
+ case "end":
8435
+ return _context3.stop();
8436
+ }
8437
+ }, _callee3);
8438
+ }));
8439
+ });
8440
+ workers = [];
8441
+ worker = /*#__PURE__*/function () {
8442
+ var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
8443
+ var task;
8444
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
8445
+ while (1) switch (_context4.prev = _context4.next) {
8446
+ case 0:
8447
+ if (!(preparationTasks.length > 0)) {
8448
+ _context4.next = 7;
8449
+ break;
8450
+ }
8451
+ task = preparationTasks.shift();
8452
+ if (!task) {
8453
+ _context4.next = 5;
8454
+ break;
8455
+ }
8456
+ _context4.next = 5;
8457
+ return task();
8458
+ case 5:
8459
+ _context4.next = 0;
8460
+ break;
8461
+ case 7:
8462
+ case "end":
8463
+ return _context4.stop();
8464
+ }
8465
+ }, _callee4);
8466
+ }));
8467
+ return function worker() {
8468
+ return _ref8.apply(this, arguments);
8469
+ };
8470
+ }();
8471
+ for (workerIndex = 0; workerIndex < 16; workerIndex++) {
8472
+ workers.push(worker());
8473
+ }
8474
+ _context6.next = 6;
8475
+ return Promise.all(workers);
8476
+ case 6:
8477
+ _context6.next = 8;
8478
+ return fs__default["default"].promises.readdir(tmpUploadFolder);
8479
+ case 8:
8480
+ files = _context6.sent;
8481
+ stats = files.map(function (file) {
8482
+ return fs__default["default"].promises.stat(path__default["default"].join(tmpUploadFolder, file));
8483
+ });
8484
+ _context6.next = 12;
8485
+ return Promise.all(stats);
8486
+ case 12:
8487
+ uploadSize = _context6.sent.reduce(function (accumulator, _ref9) {
8488
+ var size = _ref9.size;
8489
+ return accumulator + size;
8490
+ }, 0);
8491
+ setMeasurement("files", files.length, "none", prepBundlesSpan);
8492
+ setMeasurement("upload_size", uploadSize, "byte", prepBundlesSpan);
8493
+ _context6.next = 17;
8494
+ return startSpan({
8495
+ name: "upload",
8496
+ scope: sentryScope
8497
+ }, /*#__PURE__*/function () {
8498
+ var _ref10 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(uploadSpan) {
8499
+ var cliInstance;
8500
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
8501
+ while (1) switch (_context5.prev = _context5.next) {
8502
+ case 0:
8503
+ cliInstance = new SentryCli__default["default"](null, _objectSpread2(_objectSpread2({}, sentryCliOptions), {}, {
8504
+ headers: _objectSpread2({
8505
+ "sentry-trace": spanToTraceHeader(uploadSpan),
8506
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
8507
+ baggage: dynamicSamplingContextToSentryBaggageHeader(getDynamicSamplingContextFromSpan(uploadSpan))
8508
+ }, sentryCliOptions.headers)
8509
+ }));
8510
+ _context5.next = 3;
8511
+ return cliInstance.releases.uploadSourceMaps(releaseName !== null && releaseName !== void 0 ? releaseName : "undefined",
8512
+ // unfortunately this needs a value for now but it will not matter since debug IDs overpower releases anyhow
8513
+ {
8514
+ include: [{
8515
+ paths: [tmpUploadFolder],
8516
+ rewrite: false,
8517
+ dist: dist
8518
+ }]
8519
+ });
8520
+ case 3:
8521
+ case "end":
8522
+ return _context5.stop();
8523
+ }
8524
+ }, _callee5);
8525
+ }));
8526
+ return function (_x3) {
8527
+ return _ref10.apply(this, arguments);
8528
+ };
8529
+ }());
8530
+ case 17:
8531
+ case "end":
8532
+ return _context6.stop();
8533
+ }
8534
+ }, _callee6);
8535
+ }));
8536
+ return function (_x2) {
8537
+ return _ref6.apply(this, arguments);
8538
+ };
8539
+ }());
8540
+ case 22:
8541
+ logger.info("Successfully uploaded source maps to Sentry");
8542
+ case 23:
8543
+ _context8.next = 29;
8544
+ break;
8545
+ case 25:
8546
+ _context8.prev = 25;
8547
+ _context8.t0 = _context8["catch"](1);
8548
+ sentryScope.captureException('Error in "debugIdUploadPlugin" writeBundle hook');
8549
+ handleRecoverableError(_context8.t0, false);
8550
+ case 29:
8551
+ _context8.prev = 29;
8552
+ if (folderToCleanUp) {
8553
+ void startSpan({
8554
+ name: "cleanup",
8555
+ scope: sentryScope
8556
+ }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
8557
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
8558
+ while (1) switch (_context7.prev = _context7.next) {
8559
+ case 0:
8560
+ if (!folderToCleanUp) {
8561
+ _context7.next = 3;
8562
+ break;
8563
+ }
8564
+ _context7.next = 3;
8565
+ return fs__default["default"].promises.rm(folderToCleanUp, {
8566
+ recursive: true,
8567
+ force: true
8568
+ });
8569
+ case 3:
8570
+ case "end":
8571
+ return _context7.stop();
8572
+ }
8573
+ }, _callee7);
8574
+ })));
8575
+ }
8576
+ freeGlobalDependencyOnSourcemapFiles();
8577
+ freeUploadDependencyOnSourcemapFiles();
8578
+ _context8.next = 35;
8579
+ return safeFlushTelemetry(sentryClient);
8580
+ case 35:
8581
+ return _context8.finish(29);
8582
+ case 36:
8583
+ case "end":
8584
+ return _context8.stop();
8585
+ }
8586
+ }, _callee8, null, [[1, 25, 29, 36]]);
8587
+ })));
8369
8588
  case 2:
8370
8589
  case "end":
8371
- return _context.stop();
8590
+ return _context9.stop();
8372
8591
  }
8373
- }, _callee);
8592
+ }, _callee9);
8374
8593
  }));
8375
8594
  return function (_x) {
8376
8595
  return _ref2.apply(this, arguments);
8377
8596
  };
8378
8597
  }();
8379
8598
  }
8380
- function prepareBundleForDebugIdUpload(_x2, _x3, _x4, _x5, _x6) {
8599
+ function prepareBundleForDebugIdUpload(_x4, _x5, _x6, _x7, _x8) {
8381
8600
  return _prepareBundleForDebugIdUpload.apply(this, arguments);
8382
8601
  }
8383
8602
 
@@ -8388,66 +8607,66 @@ function prepareBundleForDebugIdUpload(_x2, _x3, _x4, _x5, _x6) {
8388
8607
  * The string pattern is injected via the debug ID injection snipped.
8389
8608
  */
8390
8609
  function _prepareBundleForDebugIdUpload() {
8391
- _prepareBundleForDebugIdUpload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(bundleFilePath, uploadFolder, chunkIndex, logger, rewriteSourcesHook) {
8610
+ _prepareBundleForDebugIdUpload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(bundleFilePath, uploadFolder, chunkIndex, logger, rewriteSourcesHook) {
8392
8611
  var bundleContent, debugId, uniqueUploadName, writeSourceFilePromise, writeSourceMapFilePromise;
8393
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
8394
- while (1) switch (_context3.prev = _context3.next) {
8612
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
8613
+ while (1) switch (_context11.prev = _context11.next) {
8395
8614
  case 0:
8396
- _context3.prev = 0;
8397
- _context3.next = 3;
8615
+ _context11.prev = 0;
8616
+ _context11.next = 3;
8398
8617
  return util.promisify(fs__default["default"].readFile)(bundleFilePath, "utf8");
8399
8618
  case 3:
8400
- bundleContent = _context3.sent;
8401
- _context3.next = 10;
8619
+ bundleContent = _context11.sent;
8620
+ _context11.next = 10;
8402
8621
  break;
8403
8622
  case 6:
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
+ _context11.prev = 6;
8624
+ _context11.t0 = _context11["catch"](0);
8625
+ logger.error("Could not read bundle to determine debug ID and source map: ".concat(bundleFilePath), _context11.t0);
8626
+ return _context11.abrupt("return");
8408
8627
  case 10:
8409
8628
  debugId = determineDebugIdFromBundleSource(bundleContent);
8410
8629
  if (!(debugId === undefined)) {
8411
- _context3.next = 14;
8630
+ _context11.next = 14;
8412
8631
  break;
8413
8632
  }
8414
8633
  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));
8415
- return _context3.abrupt("return");
8634
+ return _context11.abrupt("return");
8416
8635
  case 14:
8417
8636
  uniqueUploadName = "".concat(debugId, "-").concat(chunkIndex);
8418
8637
  bundleContent += "\n//# debugId=".concat(debugId);
8419
8638
  writeSourceFilePromise = fs__default["default"].promises.writeFile(path__default["default"].join(uploadFolder, "".concat(uniqueUploadName, ".js")), bundleContent, "utf-8");
8420
8639
  writeSourceMapFilePromise = determineSourceMapPathFromBundle(bundleFilePath, bundleContent, logger).then( /*#__PURE__*/function () {
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) {
8640
+ var _ref12 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(sourceMapPath) {
8641
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
8642
+ while (1) switch (_context10.prev = _context10.next) {
8424
8643
  case 0:
8425
8644
  if (!sourceMapPath) {
8426
- _context2.next = 3;
8645
+ _context10.next = 3;
8427
8646
  break;
8428
8647
  }
8429
- _context2.next = 3;
8648
+ _context10.next = 3;
8430
8649
  return prepareSourceMapForDebugIdUpload(sourceMapPath, path__default["default"].join(uploadFolder, "".concat(uniqueUploadName, ".js.map")), debugId, rewriteSourcesHook, logger);
8431
8650
  case 3:
8432
8651
  case "end":
8433
- return _context2.stop();
8652
+ return _context10.stop();
8434
8653
  }
8435
- }, _callee2);
8654
+ }, _callee10);
8436
8655
  }));
8437
- return function (_x15) {
8438
- return _ref3.apply(this, arguments);
8656
+ return function (_x17) {
8657
+ return _ref12.apply(this, arguments);
8439
8658
  };
8440
8659
  }());
8441
- _context3.next = 20;
8660
+ _context11.next = 20;
8442
8661
  return writeSourceFilePromise;
8443
8662
  case 20:
8444
- _context3.next = 22;
8663
+ _context11.next = 22;
8445
8664
  return writeSourceMapFilePromise;
8446
8665
  case 22:
8447
8666
  case "end":
8448
- return _context3.stop();
8667
+ return _context11.stop();
8449
8668
  }
8450
- }, _callee3, null, [[0, 6]]);
8669
+ }, _callee11, null, [[0, 6]]);
8451
8670
  }));
8452
8671
  return _prepareBundleForDebugIdUpload.apply(this, arguments);
8453
8672
  }
@@ -8465,22 +8684,22 @@ function determineDebugIdFromBundleSource(code) {
8465
8684
  *
8466
8685
  * @returns the path to the bundle's source map or `undefined` if none could be found.
8467
8686
  */
8468
- function determineSourceMapPathFromBundle(_x7, _x8, _x9) {
8687
+ function determineSourceMapPathFromBundle(_x9, _x10, _x11) {
8469
8688
  return _determineSourceMapPathFromBundle.apply(this, arguments);
8470
8689
  }
8471
8690
  /**
8472
8691
  * Reads a source map, injects debug ID fields, and writes the source map to the target path.
8473
8692
  */
8474
8693
  function _determineSourceMapPathFromBundle() {
8475
- _determineSourceMapPathFromBundle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(bundlePath, bundleSource, logger) {
8694
+ _determineSourceMapPathFromBundle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(bundlePath, bundleSource, logger) {
8476
8695
  var sourceMappingUrlMatch, sourceMappingUrl, isUrl, isSupportedUrl, url, absoluteSourceMapPath, adjacentSourceMapFilePath;
8477
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
8478
- while (1) switch (_context4.prev = _context4.next) {
8696
+ return _regeneratorRuntime().wrap(function _callee12$(_context12) {
8697
+ while (1) switch (_context12.prev = _context12.next) {
8479
8698
  case 0:
8480
8699
  // 1. try to find source map at `sourceMappingURL` location
8481
8700
  sourceMappingUrlMatch = bundleSource.match(/^\s*\/\/# sourceMappingURL=(.*)$/m);
8482
8701
  if (!sourceMappingUrlMatch) {
8483
- _context4.next = 14;
8702
+ _context12.next = 14;
8484
8703
  break;
8485
8704
  }
8486
8705
  sourceMappingUrl = path__default["default"].normalize(sourceMappingUrlMatch[1]);
@@ -8500,435 +8719,156 @@ function _determineSourceMapPathFromBundle() {
8500
8719
  absoluteSourceMapPath = path__default["default"].join(path__default["default"].dirname(bundlePath), sourceMappingUrl);
8501
8720
  }
8502
8721
  if (!absoluteSourceMapPath) {
8503
- _context4.next = 14;
8722
+ _context12.next = 14;
8504
8723
  break;
8505
8724
  }
8506
- _context4.prev = 6;
8507
- _context4.next = 9;
8725
+ _context12.prev = 6;
8726
+ _context12.next = 9;
8508
8727
  return util__namespace.promisify(fs__default["default"].access)(absoluteSourceMapPath);
8509
8728
  case 9:
8510
- return _context4.abrupt("return", absoluteSourceMapPath);
8729
+ return _context12.abrupt("return", absoluteSourceMapPath);
8511
8730
  case 12:
8512
- _context4.prev = 12;
8513
- _context4.t0 = _context4["catch"](6);
8731
+ _context12.prev = 12;
8732
+ _context12.t0 = _context12["catch"](6);
8514
8733
  case 14:
8515
- _context4.prev = 14;
8734
+ _context12.prev = 14;
8516
8735
  adjacentSourceMapFilePath = bundlePath + ".map";
8517
- _context4.next = 18;
8736
+ _context12.next = 18;
8518
8737
  return util__namespace.promisify(fs__default["default"].access)(adjacentSourceMapFilePath);
8519
8738
  case 18:
8520
- return _context4.abrupt("return", adjacentSourceMapFilePath);
8739
+ return _context12.abrupt("return", adjacentSourceMapFilePath);
8521
8740
  case 21:
8522
- _context4.prev = 21;
8523
- _context4.t1 = _context4["catch"](14);
8741
+ _context12.prev = 21;
8742
+ _context12.t1 = _context12["catch"](14);
8524
8743
  case 23:
8525
8744
  // This is just a debug message because it can be quite spammy for some frameworks
8526
8745
  logger.debug("Could not determine source map path for bundle: ".concat(bundlePath, " - Did you turn on source map generation in your bundler?"));
8527
- return _context4.abrupt("return", undefined);
8746
+ return _context12.abrupt("return", undefined);
8528
8747
  case 25:
8529
8748
  case "end":
8530
- return _context4.stop();
8749
+ return _context12.stop();
8531
8750
  }
8532
- }, _callee4, null, [[6, 12], [14, 21]]);
8751
+ }, _callee12, null, [[6, 12], [14, 21]]);
8533
8752
  }));
8534
8753
  return _determineSourceMapPathFromBundle.apply(this, arguments);
8535
8754
  }
8536
- function prepareSourceMapForDebugIdUpload(_x10, _x11, _x12, _x13, _x14) {
8755
+ function prepareSourceMapForDebugIdUpload(_x12, _x13, _x14, _x15, _x16) {
8537
8756
  return _prepareSourceMapForDebugIdUpload.apply(this, arguments);
8538
8757
  }
8539
8758
  function _prepareSourceMapForDebugIdUpload() {
8540
- _prepareSourceMapForDebugIdUpload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(sourceMapPath, targetPath, debugId, rewriteSourcesHook, logger) {
8759
+ _prepareSourceMapForDebugIdUpload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(sourceMapPath, targetPath, debugId, rewriteSourcesHook, logger) {
8541
8760
  var sourceMapFileContent, map;
8542
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
8543
- while (1) switch (_context5.prev = _context5.next) {
8761
+ return _regeneratorRuntime().wrap(function _callee13$(_context13) {
8762
+ while (1) switch (_context13.prev = _context13.next) {
8544
8763
  case 0:
8545
- _context5.prev = 0;
8546
- _context5.next = 3;
8764
+ _context13.prev = 0;
8765
+ _context13.next = 3;
8547
8766
  return util__namespace.promisify(fs__default["default"].readFile)(sourceMapPath, {
8548
8767
  encoding: "utf8"
8549
8768
  });
8550
8769
  case 3:
8551
- sourceMapFileContent = _context5.sent;
8552
- _context5.next = 10;
8770
+ sourceMapFileContent = _context13.sent;
8771
+ _context13.next = 10;
8553
8772
  break;
8554
8773
  case 6:
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
+ _context13.prev = 6;
8775
+ _context13.t0 = _context13["catch"](0);
8776
+ logger.error("Failed to read source map for debug ID upload: ".concat(sourceMapPath), _context13.t0);
8777
+ return _context13.abrupt("return");
8559
8778
  case 10:
8560
- _context5.prev = 10;
8779
+ _context13.prev = 10;
8561
8780
  map = JSON.parse(sourceMapFileContent);
8562
8781
  // For now we write both fields until we know what will become the standard - if ever.
8563
8782
  map["debug_id"] = debugId;
8564
8783
  map["debugId"] = debugId;
8565
- _context5.next = 20;
8784
+ _context13.next = 20;
8566
8785
  break;
8567
8786
  case 16:
8568
- _context5.prev = 16;
8569
- _context5.t1 = _context5["catch"](10);
8787
+ _context13.prev = 16;
8788
+ _context13.t1 = _context13["catch"](10);
8570
8789
  logger.error("Failed to parse source map for debug ID upload: ".concat(sourceMapPath));
8571
- return _context5.abrupt("return");
8790
+ return _context13.abrupt("return");
8572
8791
  case 20:
8573
8792
  if (map["sources"] && Array.isArray(map["sources"])) {
8574
- map["sources"] = map["sources"].map(function (source) {
8575
- return rewriteSourcesHook(source, map);
8576
- });
8577
- }
8578
- _context5.prev = 21;
8579
- _context5.next = 24;
8580
- return util__namespace.promisify(fs__default["default"].writeFile)(targetPath, JSON.stringify(map), {
8581
- encoding: "utf8"
8582
- });
8583
- case 24:
8584
- _context5.next = 30;
8585
- break;
8586
- case 26:
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");
8591
- case 30:
8592
- case "end":
8593
- return _context5.stop();
8594
- }
8595
- }, _callee5, null, [[0, 6], [10, 16], [21, 26]]);
8596
- }));
8597
- return _prepareSourceMapForDebugIdUpload.apply(this, arguments);
8598
- }
8599
- var PROTOCOL_REGEX = /^[a-zA-Z][a-zA-Z0-9+\-.]*:\/\//;
8600
- function defaultRewriteSourcesHook(source) {
8601
- if (source.match(PROTOCOL_REGEX)) {
8602
- return source.replace(PROTOCOL_REGEX, "");
8603
- } else {
8604
- return path__default["default"].relative(process.cwd(), path__default["default"].normalize(source));
8605
- }
8606
- }
8607
-
8608
- /**
8609
- * Creates a build plugin manager that exposes primitives for everything that a Sentry JavaScript SDK or build tooling may do during a build.
8610
- *
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
- }
8802
- return {
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
- }))();
8793
+ map["sources"] = map["sources"].map(function (source) {
8794
+ return rewriteSourcesHook(source, map);
8795
+ });
8796
+ }
8797
+ _context13.prev = 21;
8798
+ _context13.next = 24;
8799
+ return util__namespace.promisify(fs__default["default"].writeFile)(targetPath, JSON.stringify(map), {
8800
+ encoding: "utf8"
8801
+ });
8802
+ case 24:
8803
+ _context13.next = 30;
8804
+ break;
8805
+ case 26:
8806
+ _context13.prev = 26;
8807
+ _context13.t2 = _context13["catch"](21);
8808
+ logger.error("Failed to prepare source map for debug ID upload: ".concat(sourceMapPath), _context13.t2);
8809
+ return _context13.abrupt("return");
8810
+ case 30:
8811
+ case "end":
8812
+ return _context13.stop();
8855
8813
  }
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() {
8814
+ }, _callee13, null, [[0, 6], [10, 16], [21, 26]]);
8815
+ }));
8816
+ return _prepareSourceMapForDebugIdUpload.apply(this, arguments);
8817
+ }
8818
+ var PROTOCOL_REGEX = /^[a-zA-Z][a-zA-Z0-9+\-.]*:\/\//;
8819
+ function defaultRewriteSourcesHook(source) {
8820
+ if (source.match(PROTOCOL_REGEX)) {
8821
+ return source.replace(PROTOCOL_REGEX, "");
8822
+ } else {
8823
+ return path__default["default"].relative(process.cwd(), path__default["default"].normalize(source));
8824
+ }
8825
+ }
8826
+
8827
+ /**
8828
+ * Creates a plugin that creates releases, sets commits, deploys and finalizes releases.
8829
+ *
8830
+ * Additionally, if legacy upload options are set, it uploads source maps in the legacy (non-debugId) way.
8831
+ */
8832
+ function releaseManagementPlugin(_ref) {
8833
+ var logger = _ref.logger,
8834
+ releaseName = _ref.releaseName,
8835
+ include = _ref.include,
8836
+ dist = _ref.dist,
8837
+ setCommitsOption = _ref.setCommitsOption,
8838
+ shouldCreateRelease = _ref.shouldCreateRelease,
8839
+ shouldFinalizeRelease = _ref.shouldFinalizeRelease,
8840
+ deployOptions = _ref.deployOptions,
8841
+ handleRecoverableError = _ref.handleRecoverableError,
8842
+ sentryScope = _ref.sentryScope,
8843
+ sentryClient = _ref.sentryClient,
8844
+ sentryCliOptions = _ref.sentryCliOptions,
8845
+ createDependencyOnSourcemapFiles = _ref.createDependencyOnSourcemapFiles;
8846
+ var freeGlobalDependencyOnSourcemapFiles = createDependencyOnSourcemapFiles();
8847
+ return {
8848
+ name: "sentry-release-management-plugin",
8849
+ writeBundle: function writeBundle() {
8850
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
8868
8851
  var freeWriteBundleInvocationDependencyOnSourcemapFiles, cliInstance, normalizedInclude;
8869
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
8870
- while (1) switch (_context2.prev = _context2.next) {
8852
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
8853
+ while (1) switch (_context.prev = _context.next) {
8871
8854
  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:
8907
8855
  // 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`)
8908
8856
  // Therefore we need to actually register the execution of this hook as dependency on the sourcemap files.
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;
8857
+ freeWriteBundleInvocationDependencyOnSourcemapFiles = createDependencyOnSourcemapFiles();
8858
+ _context.prev = 1;
8859
+ cliInstance = new SentryCli__default["default"](null, sentryCliOptions);
8860
+ if (!shouldCreateRelease) {
8861
+ _context.next = 6;
8922
8862
  break;
8923
8863
  }
8924
- _context2.next = 29;
8925
- return cliInstance.releases["new"](options.release.name);
8926
- case 29:
8927
- if (!options.release.uploadLegacySourcemaps) {
8928
- _context2.next = 33;
8864
+ _context.next = 6;
8865
+ return cliInstance.releases["new"](releaseName);
8866
+ case 6:
8867
+ if (!include) {
8868
+ _context.next = 10;
8929
8869
  break;
8930
8870
  }
8931
- normalizedInclude = arrayify(options.release.uploadLegacySourcemaps).map(function (includeItem) {
8871
+ normalizedInclude = arrayify$1(include).map(function (includeItem) {
8932
8872
  return typeof includeItem === "string" ? {
8933
8873
  paths: [includeItem]
8934
8874
  } : includeItem;
@@ -8939,409 +8879,202 @@ function createSentryBuildPluginManager(userOptions, bundlerPluginMetaContext) {
8939
8879
  ext: includeEntry.ext ? includeEntry.ext.map(function (extension) {
8940
8880
  return ".".concat(extension.replace(/^\./, ""));
8941
8881
  }) : [".js", ".map", ".jsbundle", ".bundle"],
8942
- ignore: includeEntry.ignore ? arrayify(includeEntry.ignore) : undefined
8882
+ ignore: includeEntry.ignore ? arrayify$1(includeEntry.ignore) : undefined
8943
8883
  });
8944
8884
  });
8945
- _context2.next = 33;
8946
- return cliInstance.releases.uploadSourceMaps(options.release.name, {
8885
+ _context.next = 10;
8886
+ return cliInstance.releases.uploadSourceMaps(releaseName, {
8947
8887
  include: normalizedInclude,
8948
- dist: options.release.dist
8888
+ dist: dist
8949
8889
  });
8950
- case 33:
8951
- if (!(options.release.setCommits !== false)) {
8952
- _context2.next = 46;
8890
+ case 10:
8891
+ if (!(setCommitsOption !== false)) {
8892
+ _context.next = 23;
8953
8893
  break;
8954
8894
  }
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;
8895
+ _context.prev = 11;
8896
+ _context.next = 14;
8897
+ return cliInstance.releases.setCommits(releaseName, setCommitsOption);
8898
+ case 14:
8899
+ _context.next = 23;
8963
8900
  break;
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;
8901
+ case 16:
8902
+ _context.prev = 16;
8903
+ _context.t0 = _context["catch"](11);
8904
+ if (!("shouldNotThrowOnFailure" in setCommitsOption && setCommitsOption.shouldNotThrowOnFailure)) {
8905
+ _context.next = 22;
8969
8906
  break;
8970
8907
  }
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;
8908
+ logger.debug("An error occurred setting commits on release (this message can be ignored unless you commits on release are desired):", _context.t0);
8909
+ _context.next = 23;
8973
8910
  break;
8974
- case 45:
8975
- throw _context2.t0;
8976
- case 46:
8977
- if (!options.release.finalize) {
8978
- _context2.next = 49;
8911
+ case 22:
8912
+ throw _context.t0;
8913
+ case 23:
8914
+ if (!shouldFinalizeRelease) {
8915
+ _context.next = 26;
8979
8916
  break;
8980
8917
  }
8981
- _context2.next = 49;
8982
- return cliInstance.releases.finalize(options.release.name);
8983
- case 49:
8984
- if (!options.release.deploy) {
8985
- _context2.next = 52;
8918
+ _context.next = 26;
8919
+ return cliInstance.releases.finalize(releaseName);
8920
+ case 26:
8921
+ if (!deployOptions) {
8922
+ _context.next = 29;
8986
8923
  break;
8987
8924
  }
8988
- _context2.next = 52;
8989
- return cliInstance.releases.newDeploy(options.release.name, options.release.deploy);
8990
- case 52:
8991
- _context2.next = 60;
8925
+ _context.next = 29;
8926
+ return cliInstance.releases.newDeploy(releaseName, deployOptions);
8927
+ case 29:
8928
+ _context.next = 37;
8992
8929
  break;
8993
- case 54:
8994
- _context2.prev = 54;
8995
- _context2.t1 = _context2["catch"](24);
8930
+ case 31:
8931
+ _context.prev = 31;
8932
+ _context.t1 = _context["catch"](1);
8996
8933
  sentryScope.captureException('Error in "releaseManagementPlugin" writeBundle hook');
8997
- _context2.next = 59;
8934
+ _context.next = 36;
8998
8935
  return safeFlushTelemetry(sentryClient);
8999
- case 59:
9000
- handleRecoverableError(_context2.t1, false);
9001
- case 60:
9002
- _context2.prev = 60;
8936
+ case 36:
8937
+ handleRecoverableError(_context.t1, false);
8938
+ case 37:
8939
+ _context.prev = 37;
8940
+ freeGlobalDependencyOnSourcemapFiles();
9003
8941
  freeWriteBundleInvocationDependencyOnSourcemapFiles();
9004
- return _context2.finish(60);
9005
- case 63:
8942
+ return _context.finish(37);
8943
+ case 41:
9006
8944
  case "end":
9007
- return _context2.stop();
8945
+ return _context.stop();
9008
8946
  }
9009
- }, _callee2, null, [[24, 54, 60, 63], [34, 39]]);
8947
+ }, _callee, null, [[1, 31, 37, 41], [11, 16]]);
9010
8948
  }))();
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) {
8949
+ }
8950
+ };
8951
+ }
8952
+
8953
+ function telemetryPlugin(_ref) {
8954
+ var sentryClient = _ref.sentryClient,
8955
+ sentryScope = _ref.sentryScope,
8956
+ shouldSendTelemetry = _ref.shouldSendTelemetry,
8957
+ logger = _ref.logger;
8958
+ return {
8959
+ name: "sentry-telemetry-plugin",
8960
+ buildStart: function buildStart() {
8961
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
8962
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
8963
+ while (1) switch (_context.prev = _context.next) {
9020
8964
  case 0:
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"));
8965
+ _context.next = 2;
8966
+ return shouldSendTelemetry;
8967
+ case 2:
8968
+ if (!_context.sent) {
8969
+ _context.next = 7;
8970
+ break;
9031
8971
  }
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:
8972
+ logger.info("Sending telemetry data on issues and performance to Sentry. To disable telemetry, set `options.telemetry` to `false`.");
8973
+ startSpan({
8974
+ name: "Sentry Bundler Plugin execution",
8975
+ scope: sentryScope
8976
+ }, function () {
8977
+ //
8978
+ });
8979
+ _context.next = 7;
8980
+ return safeFlushTelemetry(sentryClient);
8981
+ case 7:
9304
8982
  case "end":
9305
- return _context11.stop();
8983
+ return _context.stop();
9306
8984
  }
9307
- }, _callee11);
8985
+ }, _callee);
9308
8986
  }))();
8987
+ }
8988
+ };
8989
+ }
8990
+
8991
+ // Logging everything to stderr not to interfere with stdout
8992
+ function createLogger(options) {
8993
+ return {
8994
+ info: function info(message) {
8995
+ if (!options.silent) {
8996
+ var _console;
8997
+ for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
8998
+ params[_key - 1] = arguments[_key];
8999
+ }
9000
+ // eslint-disable-next-line no-console
9001
+ (_console = console).info.apply(_console, ["".concat(options.prefix, " Info: ").concat(message)].concat(params));
9002
+ }
9309
9003
  },
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) {
9004
+ warn: function warn(message) {
9005
+ if (!options.silent) {
9006
+ var _console2;
9007
+ for (var _len2 = arguments.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
9008
+ params[_key2 - 1] = arguments[_key2];
9009
+ }
9010
+ // eslint-disable-next-line no-console
9011
+ (_console2 = console).warn.apply(_console2, ["".concat(options.prefix, " Warning: ").concat(message)].concat(params));
9012
+ }
9013
+ },
9014
+ error: function error(message) {
9015
+ if (!options.silent) {
9016
+ var _console3;
9017
+ for (var _len3 = arguments.length, params = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
9018
+ params[_key3 - 1] = arguments[_key3];
9019
+ }
9020
+ // eslint-disable-next-line no-console
9021
+ (_console3 = console).error.apply(_console3, ["".concat(options.prefix, " Error: ").concat(message)].concat(params));
9022
+ }
9023
+ },
9024
+ debug: function debug(message) {
9025
+ if (!options.silent && options.debug) {
9026
+ var _console4;
9027
+ for (var _len4 = arguments.length, params = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
9028
+ params[_key4 - 1] = arguments[_key4];
9029
+ }
9030
+ // eslint-disable-next-line no-console
9031
+ (_console4 = console).debug.apply(_console4, ["".concat(options.prefix, " Debug: ").concat(message)].concat(params));
9032
+ }
9033
+ }
9034
+ };
9035
+ }
9036
+
9037
+ function fileDeletionPlugin(_ref) {
9038
+ var handleRecoverableError = _ref.handleRecoverableError,
9039
+ sentryScope = _ref.sentryScope,
9040
+ sentryClient = _ref.sentryClient,
9041
+ filesToDeleteAfterUpload = _ref.filesToDeleteAfterUpload,
9042
+ waitUntilSourcemapFileDependenciesAreFreed = _ref.waitUntilSourcemapFileDependenciesAreFreed,
9043
+ logger = _ref.logger;
9044
+ return {
9045
+ name: "sentry-file-deletion-plugin",
9046
+ writeBundle: function writeBundle() {
9047
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
9048
+ var filesToDelete, filePathsToDelete;
9049
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
9050
+ while (1) switch (_context.prev = _context.next) {
9318
9051
  case 0:
9319
- _context12.prev = 0;
9320
- _context12.next = 3;
9321
- return (_options$sourcemaps5 = options.sourcemaps) === null || _options$sourcemaps5 === void 0 ? void 0 : _options$sourcemaps5.filesToDeleteAfterUpload;
9052
+ _context.prev = 0;
9053
+ _context.next = 3;
9054
+ return filesToDeleteAfterUpload;
9322
9055
  case 3:
9323
- filesToDelete = _context12.sent;
9056
+ filesToDelete = _context.sent;
9324
9057
  if (!(filesToDelete !== undefined)) {
9325
- _context12.next = 14;
9058
+ _context.next = 14;
9326
9059
  break;
9327
9060
  }
9328
- _context12.next = 7;
9061
+ _context.next = 7;
9329
9062
  return glob.glob(filesToDelete, {
9330
9063
  absolute: true,
9331
9064
  nodir: true
9332
9065
  });
9333
9066
  case 7:
9334
- filePathsToDelete = _context12.sent;
9067
+ filePathsToDelete = _context.sent;
9335
9068
  logger.debug("Waiting for dependencies on generated files to be freed before deleting...");
9336
- _context12.next = 11;
9337
- return waitUntilBuildArtifactDependenciesAreFreed();
9069
+ _context.next = 11;
9070
+ return waitUntilSourcemapFileDependenciesAreFreed();
9338
9071
  case 11:
9339
9072
  filePathsToDelete.forEach(function (filePathToDelete) {
9340
9073
  logger.debug("Deleting asset after upload: ".concat(filePathToDelete));
9341
9074
  });
9342
- _context12.next = 14;
9075
+ _context.next = 14;
9343
9076
  return Promise.all(filePathsToDelete.map(function (filePathToDelete) {
9344
- return fs__namespace.promises.rm(filePathToDelete, {
9077
+ return fs__default["default"].promises.rm(filePathToDelete, {
9345
9078
  force: true
9346
9079
  })["catch"](function (e) {
9347
9080
  // This is allowed to fail - we just don't do anything
@@ -9349,31 +9082,53 @@ function createSentryBuildPluginManager(userOptions, bundlerPluginMetaContext) {
9349
9082
  });
9350
9083
  }));
9351
9084
  case 14:
9352
- _context12.next = 22;
9085
+ _context.next = 22;
9353
9086
  break;
9354
9087
  case 16:
9355
- _context12.prev = 16;
9356
- _context12.t0 = _context12["catch"](0);
9088
+ _context.prev = 16;
9089
+ _context.t0 = _context["catch"](0);
9357
9090
  sentryScope.captureException('Error in "sentry-file-deletion-plugin" buildEnd hook');
9358
- _context12.next = 21;
9091
+ _context.next = 21;
9359
9092
  return safeFlushTelemetry(sentryClient);
9360
9093
  case 21:
9361
9094
  // We throw by default if we get here b/c not being able to delete
9362
9095
  // source maps could leak them to production
9363
- handleRecoverableError(_context12.t0, true);
9096
+ handleRecoverableError(_context.t0, true);
9364
9097
  case 22:
9365
9098
  case "end":
9366
- return _context12.stop();
9099
+ return _context.stop();
9367
9100
  }
9368
- }, _callee12, null, [[0, 16]]);
9101
+ }, _callee, null, [[0, 16]]);
9369
9102
  }))();
9370
- },
9371
- createDependencyOnBuildArtifacts: createDependencyOnBuildArtifacts
9103
+ }
9372
9104
  };
9373
9105
  }
9374
9106
 
9375
9107
  /**
9376
- * Creates an unplugin instance used to create Sentry plugins for Vite, Rollup, esbuild, and Webpack.
9108
+ * The sentry bundler plugin concerns itself with two things:
9109
+ * - Release injection
9110
+ * - Sourcemaps upload
9111
+ *
9112
+ * Release injection:
9113
+ * Per default the sentry bundler plugin will inject a global `SENTRY_RELEASE` into each JavaScript/TypeScript module
9114
+ * that is part of the bundle. On a technical level this is done by appending an import (`import "sentry-release-injector";`)
9115
+ * to all entrypoint files of the user code (see `transformInclude` and `transform` hooks). This import is then resolved
9116
+ * by the sentry plugin to a virtual module that sets the global variable (see `resolveId` and `load` hooks).
9117
+ * If a user wants to inject the release into a particular set of modules they can use the `releaseInjectionTargets` option.
9118
+ *
9119
+ * Source maps upload:
9120
+ *
9121
+ * The sentry bundler plugin will also take care of uploading source maps to Sentry. This
9122
+ * is all done in the `writeBundle` hook. In this hook the sentry plugin will execute the
9123
+ * release creation pipeline:
9124
+ *
9125
+ * 1. Create a new release
9126
+ * 2. Upload sourcemaps based on `include` and source-map-specific options
9127
+ * 3. Associate a range of commits with the release (if `setCommits` is specified)
9128
+ * 4. Finalize the release (unless `finalize` is disabled)
9129
+ * 5. Add deploy information to the release (if `deploy` is specified)
9130
+ *
9131
+ * This release creation pipeline relies on Sentry CLI to execute the different steps.
9377
9132
  */
9378
9133
  function sentryUnpluginFactory(_ref) {
9379
9134
  var releaseInjectionPlugin = _ref.releaseInjectionPlugin,
@@ -9383,46 +9138,189 @@ function sentryUnpluginFactory(_ref) {
9383
9138
  debugIdUploadPlugin = _ref.debugIdUploadPlugin,
9384
9139
  bundleSizeOptimizationsPlugin = _ref.bundleSizeOptimizationsPlugin;
9385
9140
  return unplugin.createUnplugin(function () {
9386
- var _userOptions$_metaOpt, _userOptions$_metaOpt2, _options$sourcemaps;
9141
+ var _userOptions$_metaOpt, _userOptions$_metaOpt2, _userOptions$silent, _userOptions$debug, _options$sourcemaps, _options$sourcemaps2, _options$sourcemaps6;
9387
9142
  var userOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
9388
9143
  var unpluginMetaContext = arguments.length > 1 ? arguments[1] : undefined;
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
+ var logger = createLogger({
9145
+ 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]"),
9146
+ silent: (_userOptions$silent = userOptions.silent) !== null && _userOptions$silent !== void 0 ? _userOptions$silent : false,
9147
+ debug: (_userOptions$debug = userOptions.debug) !== null && _userOptions$debug !== void 0 ? _userOptions$debug : false
9392
9148
  });
9393
- var logger = sentryBuildPluginManager.logger,
9394
- options = sentryBuildPluginManager.normalizedOptions,
9395
- bundleSizeOptimizationReplacementValues = sentryBuildPluginManager.bundleSizeOptimizationReplacementValues;
9149
+
9150
+ // Not a bulletproof check but should be good enough to at least sometimes determine
9151
+ // if the plugin is called in dev/watch mode or for a prod build. The important part
9152
+ // here is to avoid a false positive. False negatives are okay.
9153
+ var isDevMode = process.env["NODE_ENV"] === "development";
9154
+ try {
9155
+ var dotenvFile = fs__namespace.readFileSync(path__namespace.join(process.cwd(), ".env.sentry-build-plugin"), "utf-8");
9156
+ // 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.
9157
+ var dotenvResult = dotenv__namespace.parse(dotenvFile);
9158
+
9159
+ // Vite has a bug/behaviour where spreading into process.env will cause it to crash
9160
+ // https://github.com/vitest-dev/vitest/issues/1870#issuecomment-1501140251
9161
+ Object.assign(process.env, dotenvResult);
9162
+ logger.info('Using environment variables configured in ".env.sentry-build-plugin".');
9163
+ } catch (e) {
9164
+ // Ignore "file not found" errors but throw all others
9165
+ if (_typeof(e) === "object" && e && "code" in e && e.code !== "ENOENT") {
9166
+ throw e;
9167
+ }
9168
+ }
9169
+ var options = normalizeUserOptions(userOptions);
9396
9170
  if (options.disable) {
9397
9171
  return [{
9398
9172
  name: "sentry-noop-plugin"
9399
9173
  }];
9400
9174
  }
9175
+ var shouldSendTelemetry = allowedToSendTelemetry(options);
9176
+ var _createSentryInstance = createSentryInstance(options, shouldSendTelemetry, unpluginMetaContext.framework),
9177
+ sentryScope = _createSentryInstance.sentryScope,
9178
+ sentryClient = _createSentryInstance.sentryClient;
9179
+ var _sentryClient$getOpti = sentryClient.getOptions(),
9180
+ release = _sentryClient$getOpti.release,
9181
+ _sentryClient$getOpti2 = _sentryClient$getOpti.environment,
9182
+ environment = _sentryClient$getOpti2 === void 0 ? DEFAULT_ENVIRONMENT : _sentryClient$getOpti2;
9183
+ var sentrySession = makeSession({
9184
+ release: release,
9185
+ environment: environment
9186
+ });
9187
+ sentryScope.setSession(sentrySession);
9188
+ // Send the start of the session
9189
+ sentryClient.captureSession(sentrySession);
9190
+ var sessionHasEnded = false; // Just to prevent infinite loops with beforeExit, which is called whenever the event loop empties out
9191
+
9192
+ function endSession() {
9193
+ if (sessionHasEnded) {
9194
+ return;
9195
+ }
9196
+ closeSession(sentrySession);
9197
+ sentryClient.captureSession(sentrySession);
9198
+ sessionHasEnded = true;
9199
+ }
9200
+
9201
+ // We also need to manually end sessions on errors because beforeExit is not called on crashes
9202
+ process.on("beforeExit", function () {
9203
+ endSession();
9204
+ });
9205
+
9206
+ // Set the User-Agent that Sentry CLI will use when interacting with Sentry
9207
+ process.env["SENTRY_PIPELINE"] = "".concat(unpluginMetaContext.framework, "-plugin/", "3.3.0");
9208
+
9209
+ /**
9210
+ * Handles errors caught and emitted in various areas of the plugin.
9211
+ *
9212
+ * Also sets the sentry session status according to the error handling.
9213
+ *
9214
+ * If users specify their custom `errorHandler` we'll leave the decision to throw
9215
+ * or continue up to them. By default, @param throwByDefault controls if the plugin
9216
+ * should throw an error (which causes a build fail in most bundlers) or continue.
9217
+ */
9218
+ function handleRecoverableError(unknownError, throwByDefault) {
9219
+ sentrySession.status = "abnormal";
9220
+ try {
9221
+ if (options.errorHandler) {
9222
+ try {
9223
+ if (unknownError instanceof Error) {
9224
+ options.errorHandler(unknownError);
9225
+ } else {
9226
+ options.errorHandler(new Error("An unknown error occured"));
9227
+ }
9228
+ } catch (e) {
9229
+ sentrySession.status = "crashed";
9230
+ throw e;
9231
+ }
9232
+ } else {
9233
+ // setting the session to "crashed" b/c from a plugin perspective this run failed.
9234
+ // However, we're intentionally not rethrowing the error to avoid breaking the user build.
9235
+ sentrySession.status = "crashed";
9236
+ if (throwByDefault) {
9237
+ throw unknownError;
9238
+ }
9239
+ logger.error("An error occurred. Couldn't finish all operations:", unknownError);
9240
+ }
9241
+ } finally {
9242
+ endSession();
9243
+ }
9244
+ }
9245
+ if (!validateOptions(options, logger)) {
9246
+ // Throwing by default to avoid a misconfigured plugin going unnoticed.
9247
+ handleRecoverableError(new Error("Options were not set correctly. See output above for more details."), true);
9248
+ }
9401
9249
  if (process.cwd().match(/\\node_modules\\|\/node_modules\//)) {
9402
9250
  logger.warn("Running Sentry plugin from within a `node_modules` folder. Some features may not work.");
9403
9251
  }
9404
9252
  var plugins = [];
9253
+ plugins.push(telemetryPlugin({
9254
+ sentryClient: sentryClient,
9255
+ sentryScope: sentryScope,
9256
+ logger: logger,
9257
+ shouldSendTelemetry: shouldSendTelemetry
9258
+ }));
9405
9259
 
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
- }))();
9260
+ // We have multiple plugins depending on generated source map files. (debug ID upload, legacy upload)
9261
+ // Additionally, we also want to have the functionality to delete files after uploading sourcemaps.
9262
+ // All of these plugins and the delete functionality need to run in the same hook (`writeBundle`).
9263
+ // Since the plugins among themselves are not aware of when they run and finish, we need a system to
9264
+ // track their dependencies on the generated files, so that we can initiate the file deletion only after
9265
+ // nothing depends on the files anymore.
9266
+ var dependenciesOnSourcemapFiles = new Set();
9267
+ var sourcemapFileDependencySubscribers = [];
9268
+ function notifySourcemapFileDependencySubscribers() {
9269
+ sourcemapFileDependencySubscribers.forEach(function (subscriber) {
9270
+ subscriber();
9271
+ });
9272
+ }
9273
+ function createDependencyOnSourcemapFiles() {
9274
+ var dependencyIdentifier = Symbol();
9275
+ dependenciesOnSourcemapFiles.add(dependencyIdentifier);
9276
+ return function freeDependencyOnSourcemapFiles() {
9277
+ dependenciesOnSourcemapFiles["delete"](dependencyIdentifier);
9278
+ notifySourcemapFileDependencySubscribers();
9279
+ };
9280
+ }
9281
+
9282
+ /**
9283
+ * Returns a Promise that resolves when all the currently active dependencies are freed again.
9284
+ *
9285
+ * It is very important that this function is called as late as possible before wanting to await the Promise to give
9286
+ * the dependency producers as much time as possible to register themselves.
9287
+ */
9288
+ function waitUntilSourcemapFileDependenciesAreFreed() {
9289
+ return new Promise(function (resolve) {
9290
+ sourcemapFileDependencySubscribers.push(function () {
9291
+ if (dependenciesOnSourcemapFiles.size === 0) {
9292
+ resolve();
9293
+ }
9294
+ });
9295
+ if (dependenciesOnSourcemapFiles.size === 0) {
9296
+ resolve();
9297
+ }
9298
+ });
9299
+ }
9300
+ if (options.bundleSizeOptimizations) {
9301
+ var bundleSizeOptimizations = options.bundleSizeOptimizations;
9302
+ var replacementValues = {};
9303
+ if (bundleSizeOptimizations.excludeDebugStatements) {
9304
+ replacementValues["__SENTRY_DEBUG__"] = false;
9305
+ }
9306
+ if (bundleSizeOptimizations.excludeTracing) {
9307
+ replacementValues["__SENTRY_TRACING__"] = false;
9308
+ }
9309
+ if (bundleSizeOptimizations.excludeReplayCanvas) {
9310
+ replacementValues["__RRWEB_EXCLUDE_CANVAS__"] = true;
9311
+ }
9312
+ if (bundleSizeOptimizations.excludeReplayIframe) {
9313
+ replacementValues["__RRWEB_EXCLUDE_IFRAME__"] = true;
9314
+ }
9315
+ if (bundleSizeOptimizations.excludeReplayShadowDom) {
9316
+ replacementValues["__RRWEB_EXCLUDE_SHADOW_DOM__"] = true;
9317
+ }
9318
+ if (bundleSizeOptimizations.excludeReplayWorker) {
9319
+ replacementValues["__SENTRY_EXCLUDE_REPLAY_WORKER__"] = true;
9320
+ }
9321
+ if (Object.keys(replacementValues).length > 0) {
9322
+ plugins.push(bundleSizeOptimizationsPlugin(replacementValues));
9422
9323
  }
9423
- });
9424
- if (Object.keys(bundleSizeOptimizationReplacementValues).length > 0) {
9425
- plugins.push(bundleSizeOptimizationsPlugin(bundleSizeOptimizationReplacementValues));
9426
9324
  }
9427
9325
  if (!options.release.inject) {
9428
9326
  logger.debug("Release injection disabled via `release.inject` option. Will not inject release.");
@@ -9435,44 +9333,113 @@ function sentryUnpluginFactory(_ref) {
9435
9333
  });
9436
9334
  plugins.push(releaseInjectionPlugin(_injectionCode));
9437
9335
  }
9438
- if (Object.keys(sentryBuildPluginManager.bundleMetadata).length > 0) {
9439
- var _injectionCode2 = generateModuleMetadataInjectorCode(sentryBuildPluginManager.bundleMetadata);
9336
+ if (options.moduleMetadata || options.applicationKey) {
9337
+ var metadata = {};
9338
+ if (options.applicationKey) {
9339
+ // We use different keys so that if user-code receives multiple bundling passes, we will store the application keys of all the passes.
9340
+ // It is a bit unfortunate that we have to inject the metadata snippet at the top, because after multiple
9341
+ // injections, the first injection will always "win" because it comes last in the code. We would generally be
9342
+ // fine with making the last bundling pass win. But because it cannot win, we have to use a workaround of storing
9343
+ // the app keys in different object keys.
9344
+ // We can simply use the `_sentryBundlerPluginAppKey:` to filter for app keys in the SDK.
9345
+ metadata["_sentryBundlerPluginAppKey:".concat(options.applicationKey)] = true;
9346
+ }
9347
+ if (typeof options.moduleMetadata === "function") {
9348
+ var args = {
9349
+ org: options.org,
9350
+ project: options.project,
9351
+ release: options.release.name
9352
+ };
9353
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
9354
+ metadata = _objectSpread2(_objectSpread2({}, metadata), options.moduleMetadata(args));
9355
+ } else {
9356
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
9357
+ metadata = _objectSpread2(_objectSpread2({}, metadata), options.moduleMetadata);
9358
+ }
9359
+ var _injectionCode2 = generateModuleMetadataInjectorCode(metadata);
9440
9360
  plugins.push(moduleMetadataInjectionPlugin(_injectionCode2));
9441
9361
  }
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
- });
9362
+ // https://turbo.build/repo/docs/reference/system-environment-variables#environment-variables-in-tasks
9363
+ var isRunningInTurborepo = Boolean(process.env["TURBO_HASH"]);
9364
+ var getTurborepoEnvPassthroughWarning = function getTurborepoEnvPassthroughWarning(envVarName) {
9365
+ 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") : "";
9366
+ };
9367
+ if (!options.release.name) {
9368
+ logger.debug("No release name provided. Will not create release. Please set the `release.name` option to identify your release.");
9369
+ } else if (isDevMode) {
9370
+ logger.debug("Running in development mode. Will not create release.");
9371
+ } else if (!options.authToken) {
9372
+ 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"));
9373
+ } else if (!options.org && !options.authToken.startsWith("sntrys_")) {
9374
+ logger.warn("No organization slug provided. Will not create release. Please set the `org` option to your Sentry organization slug." + getTurborepoEnvPassthroughWarning("SENTRY_ORG"));
9375
+ } else if (!options.project) {
9376
+ logger.warn("No project provided. Will not create release. Please set the `project` option to your Sentry project slug." + getTurborepoEnvPassthroughWarning("SENTRY_PROJECT"));
9377
+ } else {
9378
+ plugins.push(releaseManagementPlugin({
9379
+ logger: logger,
9380
+ releaseName: options.release.name,
9381
+ shouldCreateRelease: options.release.create,
9382
+ shouldFinalizeRelease: options.release.finalize,
9383
+ include: options.release.uploadLegacySourcemaps,
9384
+ // setCommits has a default defined by the options mappings
9385
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
9386
+ setCommitsOption: options.release.setCommits,
9387
+ deployOptions: options.release.deploy,
9388
+ dist: options.release.dist,
9389
+ handleRecoverableError: handleRecoverableError,
9390
+ sentryScope: sentryScope,
9391
+ sentryClient: sentryClient,
9392
+ sentryCliOptions: {
9393
+ authToken: options.authToken,
9394
+ org: options.org,
9395
+ project: options.project,
9396
+ silent: options.silent,
9397
+ url: options.url,
9398
+ vcsRemote: options.release.vcsRemote,
9399
+ headers: options.headers
9400
+ },
9401
+ createDependencyOnSourcemapFiles: createDependencyOnSourcemapFiles
9402
+ }));
9403
+ }
9467
9404
  if (!((_options$sourcemaps = options.sourcemaps) !== null && _options$sourcemaps !== void 0 && _options$sourcemaps.disable)) {
9468
9405
  plugins.push(debugIdInjectionPlugin(logger));
9469
9406
  }
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));
9407
+ if ((_options$sourcemaps2 = options.sourcemaps) !== null && _options$sourcemaps2 !== void 0 && _options$sourcemaps2.disable) {
9408
+ logger.debug("Source map upload was disabled. Will not upload sourcemaps using debug ID process.");
9409
+ } else if (isDevMode) {
9410
+ logger.debug("Running in development mode. Will not upload sourcemaps.");
9411
+ } else if (!options.authToken) {
9412
+ 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"));
9413
+ } else if (!options.org && !options.authToken.startsWith("sntrys_")) {
9414
+ logger.warn("No org provided. Will not upload source maps. Please set the `org` option to your Sentry organization slug." + getTurborepoEnvPassthroughWarning("SENTRY_ORG"));
9415
+ } else if (!options.project) {
9416
+ logger.warn("No project provided. Will not upload source maps. Please set the `project` option to your Sentry project slug." + getTurborepoEnvPassthroughWarning("SENTRY_PROJECT"));
9417
+ } else {
9418
+ var _options$sourcemaps3, _options$sourcemaps4, _options$sourcemaps5;
9419
+ // This option is only strongly typed for the webpack plugin, where it is used. It has no effect on other plugins
9420
+ var _webpack_forceExitOnBuildComplete = typeof options._experiments["forceExitOnBuildCompletion"] === "boolean" ? options._experiments["forceExitOnBuildCompletion"] : undefined;
9421
+ plugins.push(debugIdUploadPlugin(createDebugIdUploadFunction({
9422
+ assets: (_options$sourcemaps3 = options.sourcemaps) === null || _options$sourcemaps3 === void 0 ? void 0 : _options$sourcemaps3.assets,
9423
+ ignore: (_options$sourcemaps4 = options.sourcemaps) === null || _options$sourcemaps4 === void 0 ? void 0 : _options$sourcemaps4.ignore,
9424
+ createDependencyOnSourcemapFiles: createDependencyOnSourcemapFiles,
9425
+ dist: options.release.dist,
9426
+ releaseName: options.release.name,
9427
+ logger: logger,
9428
+ handleRecoverableError: handleRecoverableError,
9429
+ rewriteSourcesHook: (_options$sourcemaps5 = options.sourcemaps) === null || _options$sourcemaps5 === void 0 ? void 0 : _options$sourcemaps5.rewriteSources,
9430
+ sentryScope: sentryScope,
9431
+ sentryClient: sentryClient,
9432
+ sentryCliOptions: {
9433
+ authToken: options.authToken,
9434
+ org: options.org,
9435
+ project: options.project,
9436
+ silent: options.silent,
9437
+ url: options.url,
9438
+ vcsRemote: options.release.vcsRemote,
9439
+ headers: options.headers
9440
+ }
9441
+ }), logger, _webpack_forceExitOnBuildComplete));
9442
+ }
9476
9443
  if (options.reactComponentAnnotation) {
9477
9444
  if (!options.reactComponentAnnotation.enabled) {
9478
9445
  logger.debug("The component name annotate plugin is currently disabled. Skipping component name annotations.");
@@ -9482,33 +9449,17 @@ function sentryUnpluginFactory(_ref) {
9482
9449
  componentNameAnnotatePlugin && plugins.push(componentNameAnnotatePlugin(options.reactComponentAnnotation.ignoredComponents));
9483
9450
  }
9484
9451
  }
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
- });
9452
+ plugins.push(fileDeletionPlugin({
9453
+ waitUntilSourcemapFileDependenciesAreFreed: waitUntilSourcemapFileDependenciesAreFreed,
9454
+ filesToDeleteAfterUpload: (_options$sourcemaps6 = options.sourcemaps) === null || _options$sourcemaps6 === void 0 ? void 0 : _options$sourcemaps6.filesToDeleteAfterUpload,
9455
+ logger: logger,
9456
+ handleRecoverableError: handleRecoverableError,
9457
+ sentryScope: sentryScope,
9458
+ sentryClient: sentryClient
9459
+ }));
9504
9460
  return plugins;
9505
9461
  });
9506
9462
  }
9507
-
9508
- /**
9509
- * @deprecated
9510
- */
9511
- // TODO(v4): Don't export this from the package
9512
9463
  function getBuildInformation() {
9513
9464
  var packageJson = getPackageJson();
9514
9465
  var _ref2 = packageJson ? getDependencies(packageJson) : {
@@ -9669,22 +9620,20 @@ function createRollupModuleMetadataInjectionHooks(injectionCode) {
9669
9620
  };
9670
9621
  }
9671
9622
 
9672
- function createRollupDebugIdUploadHooks(upload, _logger, createDependencyOnBuildArtifacts) {
9673
- var freeGlobalDependencyOnDebugIdSourcemapArtifacts = createDependencyOnBuildArtifacts();
9623
+ function createRollupDebugIdUploadHooks(upload) {
9674
9624
  return {
9675
9625
  writeBundle: function writeBundle(outputOptions, bundle) {
9676
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
9626
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
9677
9627
  var outputDir, _buildArtifacts, _buildArtifacts2;
9678
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
9679
- while (1) switch (_context4.prev = _context4.next) {
9628
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
9629
+ while (1) switch (_context.prev = _context.next) {
9680
9630
  case 0:
9681
- _context4.prev = 0;
9682
9631
  if (!outputOptions.dir) {
9683
- _context4.next = 10;
9632
+ _context.next = 9;
9684
9633
  break;
9685
9634
  }
9686
9635
  outputDir = outputOptions.dir;
9687
- _context4.next = 5;
9636
+ _context.next = 4;
9688
9637
  return glob.glob(["/**/*.js", "/**/*.mjs", "/**/*.cjs", "/**/*.js.map", "/**/*.mjs.map", "/**/*.cjs.map"].map(function (q) {
9689
9638
  return "".concat(q, "?(\\?*)?(#*)");
9690
9639
  }),
@@ -9694,38 +9643,34 @@ function createRollupDebugIdUploadHooks(upload, _logger, createDependencyOnBuild
9694
9643
  absolute: true,
9695
9644
  nodir: true
9696
9645
  });
9697
- case 5:
9698
- _buildArtifacts = _context4.sent;
9699
- _context4.next = 8;
9646
+ case 4:
9647
+ _buildArtifacts = _context.sent;
9648
+ _context.next = 7;
9700
9649
  return upload(_buildArtifacts);
9701
- case 8:
9702
- _context4.next = 18;
9650
+ case 7:
9651
+ _context.next = 17;
9703
9652
  break;
9704
- case 10:
9653
+ case 9:
9705
9654
  if (!outputOptions.file) {
9706
- _context4.next = 15;
9655
+ _context.next = 14;
9707
9656
  break;
9708
9657
  }
9709
- _context4.next = 13;
9658
+ _context.next = 12;
9710
9659
  return upload([outputOptions.file]);
9711
- case 13:
9712
- _context4.next = 18;
9660
+ case 12:
9661
+ _context.next = 17;
9713
9662
  break;
9714
- case 15:
9663
+ case 14:
9715
9664
  _buildArtifacts2 = Object.keys(bundle).map(function (asset) {
9716
9665
  return path__namespace.join(path__namespace.resolve(), asset);
9717
9666
  });
9718
- _context4.next = 18;
9667
+ _context.next = 17;
9719
9668
  return upload(_buildArtifacts2);
9720
- case 18:
9721
- _context4.prev = 18;
9722
- freeGlobalDependencyOnDebugIdSourcemapArtifacts();
9723
- return _context4.finish(18);
9724
- case 21:
9669
+ case 17:
9725
9670
  case "end":
9726
- return _context4.stop();
9671
+ return _context.stop();
9727
9672
  }
9728
- }, _callee4, null, [[0,, 18, 21]]);
9673
+ }, _callee);
9729
9674
  }))();
9730
9675
  }
9731
9676
  };
@@ -9733,26 +9678,26 @@ function createRollupDebugIdUploadHooks(upload, _logger, createDependencyOnBuild
9733
9678
  function createComponentNameAnnotateHooks(ignoredComponents) {
9734
9679
  return {
9735
9680
  transform: function transform(code, id) {
9736
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
9681
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
9737
9682
  var idWithoutQueryAndHash, parserPlugins, _result$code, result;
9738
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
9739
- while (1) switch (_context5.prev = _context5.next) {
9683
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
9684
+ while (1) switch (_context2.prev = _context2.next) {
9740
9685
  case 0:
9741
9686
  // id may contain query and hash which will trip up our file extension logic below
9742
9687
  idWithoutQueryAndHash = stripQueryAndHashFromPath(id);
9743
9688
  if (!idWithoutQueryAndHash.match(/\\node_modules\\|\/node_modules\//)) {
9744
- _context5.next = 3;
9689
+ _context2.next = 3;
9745
9690
  break;
9746
9691
  }
9747
- return _context5.abrupt("return", null);
9692
+ return _context2.abrupt("return", null);
9748
9693
  case 3:
9749
9694
  if ([".jsx", ".tsx"].some(function (ending) {
9750
9695
  return idWithoutQueryAndHash.endsWith(ending);
9751
9696
  })) {
9752
- _context5.next = 5;
9697
+ _context2.next = 5;
9753
9698
  break;
9754
9699
  }
9755
- return _context5.abrupt("return", null);
9700
+ return _context2.abrupt("return", null);
9756
9701
  case 5:
9757
9702
  parserPlugins = [];
9758
9703
  if (idWithoutQueryAndHash.endsWith(".jsx")) {
@@ -9760,8 +9705,8 @@ function createComponentNameAnnotateHooks(ignoredComponents) {
9760
9705
  } else if (idWithoutQueryAndHash.endsWith(".tsx")) {
9761
9706
  parserPlugins.push("jsx", "typescript");
9762
9707
  }
9763
- _context5.prev = 7;
9764
- _context5.next = 10;
9708
+ _context2.prev = 7;
9709
+ _context2.next = 10;
9765
9710
  return core.transformAsync(code, {
9766
9711
  plugins: [[componentNameAnnotatePlugin__default["default"], {
9767
9712
  ignoredComponents: ignoredComponents
@@ -9778,24 +9723,24 @@ function createComponentNameAnnotateHooks(ignoredComponents) {
9778
9723
  sourceMaps: true
9779
9724
  });
9780
9725
  case 10:
9781
- result = _context5.sent;
9782
- return _context5.abrupt("return", {
9726
+ result = _context2.sent;
9727
+ return _context2.abrupt("return", {
9783
9728
  code: (_result$code = result === null || result === void 0 ? void 0 : result.code) !== null && _result$code !== void 0 ? _result$code : code,
9784
9729
  map: result === null || result === void 0 ? void 0 : result.map
9785
9730
  });
9786
9731
  case 14:
9787
- _context5.prev = 14;
9788
- _context5.t0 = _context5["catch"](7);
9789
- logger.error("Failed to apply react annotate plugin", _context5.t0);
9732
+ _context2.prev = 14;
9733
+ _context2.t0 = _context2["catch"](7);
9734
+ logger.error("Failed to apply react annotate plugin", _context2.t0);
9790
9735
  case 17:
9791
- return _context5.abrupt("return", {
9736
+ return _context2.abrupt("return", {
9792
9737
  code: code
9793
9738
  });
9794
9739
  case 18:
9795
9740
  case "end":
9796
- return _context5.stop();
9741
+ return _context2.stop();
9797
9742
  }
9798
- }, _callee5, null, [[7, 14]]);
9743
+ }, _callee2, null, [[7, 14]]);
9799
9744
  }))();
9800
9745
  }
9801
9746
  };