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