{"version":3,"file":"vendor-BTIYQVlZ.js","sources":["../../node_modules/scheduler/cjs/scheduler.production.min.js","../../node_modules/scheduler/index.js","../../node_modules/react-dom/cjs/react-dom.production.min.js","../../node_modules/react-dom/index.js","../../node_modules/starfx/esm/_dnt.polyfills.js","../../node_modules/effection/esm/lib/result.js","../../node_modules/effection/esm/_dnt.shims.js","../../node_modules/effection/esm/deps/deno.land/std@0.158.0/fmt/colors.js","../../node_modules/effection/esm/deps/deno.land/std@0.158.0/testing/_diff.js","../../node_modules/effection/esm/deps/deno.land/x/continuation@0.1.5/mod.js","../../node_modules/effection/esm/lib/pause.js","../../node_modules/effection/esm/lib/queue.js","../../node_modules/effection/esm/lib/shift-sync.js","../../node_modules/effection/esm/lib/instructions.js","../../node_modules/effection/esm/lib/run/create.js","../../node_modules/effection/esm/lib/lazy.js","../../node_modules/effection/esm/lib/run/value.js","../../node_modules/effection/esm/lib/run/task.js","../../node_modules/effection/esm/lib/run/frame.js","../../node_modules/effection/esm/lib/run/scope.js","../../node_modules/effection/esm/lib/context.js","../../node_modules/effection/esm/lib/signal.js","../../node_modules/effection/esm/lib/lift.js","../../node_modules/effection/esm/lib/channel.js","../../node_modules/effection/esm/lib/call.js","../../node_modules/effection/esm/lib/sleep.js","../../node_modules/effection/esm/lib/each.js","../../node_modules/effection/esm/lib/ensure.js","../../node_modules/effection/esm/lib/race.js","../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.min.js","../../node_modules/use-sync-external-store/shim/index.js","../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.min.js","../../node_modules/use-sync-external-store/shim/with-selector.js","../../node_modules/react-redux/es/utils/batch.js","../../node_modules/react-redux/es/components/Context.js","../../node_modules/react-redux/es/hooks/useReduxContext.js","../../node_modules/react-redux/es/utils/useSyncExternalStore.js","../../node_modules/react-redux/es/hooks/useSelector.js","../../node_modules/react-is/cjs/react-is.production.min.js","../../node_modules/react-is/index.js","../../node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js","../../node_modules/react-redux/node_modules/react-is/cjs/react-is.production.min.js","../../node_modules/react-redux/node_modules/react-is/index.js","../../node_modules/react-redux/es/utils/Subscription.js","../../node_modules/react-redux/es/utils/useIsomorphicLayoutEffect.js","../../node_modules/react-redux/es/components/Provider.js","../../node_modules/react-redux/es/hooks/useStore.js","../../node_modules/react-redux/es/hooks/useDispatch.js","../../node_modules/react-redux/es/index.js","../../node_modules/reselect/es/defaultMemoize.js","../../node_modules/reselect/es/index.js","../../node_modules/immer/dist/immer.mjs","../../node_modules/starfx/esm/fx/safe.js","../../node_modules/starfx/esm/fx/parallel.js","../../node_modules/starfx/esm/matcher.js","../../node_modules/starfx/esm/queue.js","../../node_modules/starfx/esm/action.js","../../node_modules/starfx/esm/fx/supervisor.js","../../node_modules/starfx/esm/compose.js","../../node_modules/starfx/esm/store/context.js","../../node_modules/starfx/esm/store/run.js","../../node_modules/starfx/esm/store/store.js","../../node_modules/starfx/esm/query/util.js","../../node_modules/starfx/esm/query/create-key.js","../../node_modules/starfx/esm/query/thunk.js","../../node_modules/starfx/esm/query/api.js","../../node_modules/starfx/esm/store/fx.js","../../node_modules/starfx/esm/store/slice/str.js","../../node_modules/starfx/esm/store/slice/num.js","../../node_modules/starfx/esm/store/slice/table.js","../../node_modules/starfx/esm/store/slice/any.js","../../node_modules/starfx/esm/store/slice/obj.js","../../node_modules/starfx/esm/store/slice/loaders.js","../../node_modules/starfx/esm/store/slice/mod.js","../../node_modules/starfx/esm/store/schema.js","../../node_modules/starfx/esm/store/batch.js","../../node_modules/starfx/esm/store/persist.js","../../node_modules/starfx/esm/mdw/fetch.js","../../node_modules/starfx/esm/mdw/query.js","../../node_modules/starfx/esm/mdw/store.js","../../node_modules/starfx/esm/mdw/mod.js","../../node_modules/starfx/esm/supervisor.js","../../node_modules/debug/node_modules/ms/index.js","../../node_modules/debug/src/common.js","../../node_modules/debug/src/browser.js","../../node_modules/@sentry/core/build/esm/debug-build.js","../../node_modules/@sentry/core/build/esm/utils-hoist/version.js","../../node_modules/@sentry/core/build/esm/utils-hoist/worldwide.js","../../node_modules/@sentry/core/build/esm/utils-hoist/debug-build.js","../../node_modules/@sentry/core/build/esm/utils-hoist/logger.js","../../node_modules/@sentry/core/build/esm/utils-hoist/stacktrace.js","../../node_modules/@sentry/core/build/esm/utils-hoist/instrument/handlers.js","../../node_modules/@sentry/core/build/esm/utils-hoist/instrument/globalError.js","../../node_modules/@sentry/core/build/esm/utils-hoist/instrument/globalUnhandledRejection.js","../../node_modules/@sentry/core/build/esm/carrier.js","../../node_modules/@sentry/core/build/esm/utils-hoist/is.js","../../node_modules/@sentry/core/build/esm/utils-hoist/browser.js","../../node_modules/@sentry/core/build/esm/utils-hoist/string.js","../../node_modules/@sentry/core/build/esm/utils-hoist/object.js","../../node_modules/@sentry/core/build/esm/utils-hoist/time.js","../../node_modules/@sentry/core/build/esm/utils-hoist/misc.js","../../node_modules/@sentry/core/build/esm/utils-hoist/syncpromise.js","../../node_modules/@sentry/core/build/esm/session.js","../../node_modules/@sentry/core/build/esm/utils-hoist/propagationContext.js","../../node_modules/@sentry/core/build/esm/utils/merge.js","../../node_modules/@sentry/core/build/esm/utils/spanOnScope.js","../../node_modules/@sentry/core/build/esm/scope.js","../../node_modules/@sentry/core/build/esm/defaultScopes.js","../../node_modules/@sentry/core/build/esm/asyncContext/stackStrategy.js","../../node_modules/@sentry/core/build/esm/asyncContext/index.js","../../node_modules/@sentry/core/build/esm/currentScopes.js","../../node_modules/@sentry/core/build/esm/metrics/metric-summary.js","../../node_modules/@sentry/core/build/esm/semanticAttributes.js","../../node_modules/@sentry/core/build/esm/tracing/spanstatus.js","../../node_modules/@sentry/core/build/esm/utils-hoist/baggage.js","../../node_modules/@sentry/core/build/esm/utils/spanUtils.js","../../node_modules/@sentry/core/build/esm/utils/hasTracingEnabled.js","../../node_modules/@sentry/core/build/esm/constants.js","../../node_modules/@sentry/core/build/esm/tracing/dynamicSamplingContext.js","../../node_modules/@sentry/core/build/esm/utils/parseSampleRate.js","../../node_modules/@sentry/core/build/esm/utils-hoist/dsn.js","../../node_modules/@sentry/core/build/esm/utils-hoist/memo.js","../../node_modules/@sentry/core/build/esm/utils-hoist/normalize.js","../../node_modules/@sentry/core/build/esm/utils-hoist/envelope.js","../../node_modules/@sentry/core/build/esm/envelope.js","../../node_modules/@sentry/core/build/esm/eventProcessors.js","../../node_modules/@sentry/core/build/esm/utils-hoist/debug-ids.js","../../node_modules/@sentry/core/build/esm/utils/applyScopeDataToEvent.js","../../node_modules/@sentry/core/build/esm/utils/prepareEvent.js","../../node_modules/@sentry/core/build/esm/exports.js","../../node_modules/@sentry/core/build/esm/api.js","../../node_modules/@sentry/core/build/esm/integration.js","../../node_modules/@sentry/core/build/esm/utils-hoist/clientreport.js","../../node_modules/@sentry/core/build/esm/utils-hoist/error.js","../../node_modules/@sentry/core/build/esm/baseclient.js","../../node_modules/@sentry/core/build/esm/sdk.js","../../node_modules/@sentry/core/build/esm/utils-hoist/promisebuffer.js","../../node_modules/@sentry/core/build/esm/utils-hoist/ratelimit.js","../../node_modules/@sentry/core/build/esm/transports/base.js","../../node_modules/@sentry/core/build/esm/utils/sdkMetadata.js","../../node_modules/@sentry/core/build/esm/breadcrumbs.js","../../node_modules/@sentry/core/build/esm/integrations/functiontostring.js","../../node_modules/@sentry/core/build/esm/integrations/inboundfilters.js","../../node_modules/@sentry/core/build/esm/utils-hoist/aggregate-errors.js","../../node_modules/@sentry/core/build/esm/utils-hoist/url.js","../../node_modules/@sentry/core/build/esm/utils-hoist/instrument/console.js","../../node_modules/@sentry/core/build/esm/utils-hoist/severity.js","../../node_modules/@sentry/core/build/esm/integrations/dedupe.js","../../node_modules/@sentry/core/build/esm/utils-hoist/breadcrumb-log-level.js","../../node_modules/@sentry/core/build/esm/utils-hoist/supports.js","../../node_modules/@sentry/core/build/esm/utils-hoist/instrument/fetch.js","../../node_modules/@sentry/core/build/esm/utils-hoist/env.js","../../node_modules/@sentry/core/build/esm/utils-hoist/vendor/supportsHistory.js","../../node_modules/@sentry/browser/build/npm/esm/helpers.js","../../node_modules/@sentry/browser/build/npm/esm/debug-build.js","../../node_modules/@sentry/browser/build/npm/esm/eventbuilder.js","../../node_modules/@sentry/browser/build/npm/esm/userfeedback.js","../../node_modules/@sentry/browser/build/npm/esm/client.js","../../node_modules/@sentry-internal/browser-utils/build/esm/debug-build.js","../../node_modules/@sentry-internal/browser-utils/build/esm/types.js","../../node_modules/@sentry-internal/browser-utils/build/esm/instrument/dom.js","../../node_modules/@sentry-internal/browser-utils/build/esm/instrument/history.js","../../node_modules/@sentry-internal/browser-utils/build/esm/getNativeImplementation.js","../../node_modules/@sentry-internal/browser-utils/build/esm/instrument/xhr.js","../../node_modules/@sentry/browser/build/npm/esm/transports/fetch.js","../../node_modules/@sentry/browser/build/npm/esm/stack-parsers.js","../../node_modules/@sentry/browser/build/npm/esm/integrations/breadcrumbs.js","../../node_modules/@sentry/browser/build/npm/esm/integrations/browserapierrors.js","../../node_modules/@sentry/browser/build/npm/esm/integrations/browsersession.js","../../node_modules/@sentry/browser/build/npm/esm/integrations/globalhandlers.js","../../node_modules/@sentry/browser/build/npm/esm/integrations/httpcontext.js","../../node_modules/@sentry/browser/build/npm/esm/integrations/linkederrors.js","../../node_modules/@sentry/browser/build/npm/esm/sdk.js","../../node_modules/@sentry/react/build/esm/sdk.js","../../node_modules/@sentry/react/build/esm/error.js","../../node_modules/@sentry/react/build/esm/debug-build.js","../../node_modules/@sentry/react/build/esm/errorboundary.js","../../node_modules/@github/webauthn-json/dist/esm/webauthn-json.js","../../node_modules/react-router/node_modules/cookie/dist/index.js","../../node_modules/react-router/dist/development/chunk-D52XG6IA.mjs","../../node_modules/classnames/index.js","../../node_modules/qrcode.react/lib/esm/index.js","../../node_modules/prop-types/lib/ReactPropTypesSecret.js","../../node_modules/prop-types/factoryWithThrowingShims.js","../../node_modules/prop-types/index.js","../../node_modules/@stripe/react-stripe-js/dist/react-stripe.esm.mjs"],"sourcesContent":["/**\n * @license React\n * scheduler.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';function f(a,b){var c=a.length;a.push(b);a:for(;0>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","/**\n * @license React\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;cb}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(ra,\nsa);z[b]=new v(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"\")&&(k=k.replace(\"\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e\"+b.valueOf().toString()+\"\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&Ng(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=Lg(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Tg(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Rg(f.type,f.key,f.props,null,a.mode,h),h.ref=Lg(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==\nd;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=Sg(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);Mg(a,f)}return\"string\"===typeof f&&\"\"!==f||\"number\"===typeof f?(f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):\n(c(a,d),d=Qg(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Ug=Og(!0),Vg=Og(!1),Wg=Uf(null),Xg=null,Yg=null,Zg=null;function $g(){Zg=Yg=Xg=null}function ah(a){var b=Wg.current;E(Wg);a._currentValue=b}function bh(a,b,c){for(;null!==a;){var d=a.alternate;(a.childLanes&b)!==b?(a.childLanes|=b,null!==d&&(d.childLanes|=b)):null!==d&&(d.childLanes&b)!==b&&(d.childLanes|=b);if(a===c)break;a=a.return}}\nfunction ch(a,b){Xg=a;Zg=Yg=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(dh=!0),a.firstContext=null)}function eh(a){var b=a._currentValue;if(Zg!==a)if(a={context:a,memoizedValue:b,next:null},null===Yg){if(null===Xg)throw Error(p(308));Yg=a;Xg.dependencies={lanes:0,firstContext:a}}else Yg=Yg.next=a;return b}var fh=null;function gh(a){null===fh?fh=[a]:fh.push(a)}\nfunction hh(a,b,c,d){var e=b.interleaved;null===e?(c.next=c,gh(b)):(c.next=e.next,e.next=c);b.interleaved=c;return ih(a,d)}function ih(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}var jh=!1;function kh(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}\nfunction lh(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function mh(a,b){return{eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}\nfunction nh(a,b,c){var d=a.updateQueue;if(null===d)return null;d=d.shared;if(0!==(K&2)){var e=d.pending;null===e?b.next=b:(b.next=e.next,e.next=b);d.pending=b;return ih(a,c)}e=d.interleaved;null===e?(b.next=b,gh(d)):(b.next=e.next,e.next=b);d.interleaved=b;return ih(a,c)}function oh(a,b,c){b=b.updateQueue;if(null!==b&&(b=b.shared,0!==(c&4194240))){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nfunction ph(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next}while(null!==c);null===f?e=f=b:f=f.next=b}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=\nb;c.lastBaseUpdate=b}\nfunction qh(a,b,c,d){var e=a.updateQueue;jh=!1;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,l=k.next;k.next=null;null===g?f=l:g.next=l;g=k;var m=a.alternate;null!==m&&(m=m.updateQueue,h=m.lastBaseUpdate,h!==g&&(null===h?m.firstBaseUpdate=l:h.next=l,m.lastBaseUpdate=k))}if(null!==f){var q=e.baseState;g=0;m=l=k=null;h=f;do{var r=h.lane,y=h.eventTime;if((d&r)===r){null!==m&&(m=m.next={eventTime:y,lane:0,tag:h.tag,payload:h.payload,callback:h.callback,\nnext:null});a:{var n=a,t=h;r=b;y=c;switch(t.tag){case 1:n=t.payload;if(\"function\"===typeof n){q=n.call(y,q,r);break a}q=n;break a;case 3:n.flags=n.flags&-65537|128;case 0:n=t.payload;r=\"function\"===typeof n?n.call(y,q,r):n;if(null===r||void 0===r)break a;q=A({},q,r);break a;case 2:jh=!0}}null!==h.callback&&0!==h.lane&&(a.flags|=64,r=e.effects,null===r?e.effects=[h]:r.push(h))}else y={eventTime:y,lane:r,tag:h.tag,payload:h.payload,callback:h.callback,next:null},null===m?(l=m=y,k=q):m=m.next=y,g|=r;\nh=h.next;if(null===h)if(h=e.shared.pending,null===h)break;else r=h,h=r.next,r.next=null,e.lastBaseUpdate=r,e.shared.pending=null}while(1);null===m&&(k=q);e.baseState=k;e.firstBaseUpdate=l;e.lastBaseUpdate=m;b=e.shared.interleaved;if(null!==b){e=b;do g|=e.lane,e=e.next;while(e!==b)}else null===f&&(e.shared.lanes=0);rh|=g;a.lanes=g;a.memoizedState=q}}\nfunction sh(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;bc?c:4;a(!0);var d=Gh.transition;Gh.transition={};try{a(!1),b()}finally{C=c,Gh.transition=d}}function wi(){return Uh().memoizedState}\nfunction xi(a,b,c){var d=yi(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,c);else if(c=hh(a,b,c,d),null!==c){var e=R();gi(c,a,d,e);Bi(c,b,d)}}\nfunction ii(a,b,c){var d=yi(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,gh(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=hh(a,b,e,d);null!==c&&(e=R(),gi(c,a,d,e),Bi(c,b,d))}}\nfunction zi(a){var b=a.alternate;return a===M||null!==b&&b===M}function Ai(a,b){Jh=Ih=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Bi(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nvar Rh={readContext:eh,useCallback:P,useContext:P,useEffect:P,useImperativeHandle:P,useInsertionEffect:P,useLayoutEffect:P,useMemo:P,useReducer:P,useRef:P,useState:P,useDebugValue:P,useDeferredValue:P,useTransition:P,useMutableSource:P,useSyncExternalStore:P,useId:P,unstable_isNewReconciler:!1},Oh={readContext:eh,useCallback:function(a,b){Th().memoizedState=[a,void 0===b?null:b];return a},useContext:eh,useEffect:mi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ki(4194308,\n4,pi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ki(4194308,4,a,b)},useInsertionEffect:function(a,b){return ki(4,2,a,b)},useMemo:function(a,b){var c=Th();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=Th();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=xi.bind(null,M,a);return[d.memoizedState,a]},useRef:function(a){var b=\nTh();a={current:a};return b.memoizedState=a},useState:hi,useDebugValue:ri,useDeferredValue:function(a){return Th().memoizedState=a},useTransition:function(){var a=hi(!1),b=a[0];a=vi.bind(null,a[1]);Th().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=M,e=Th();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===Q)throw Error(p(349));0!==(Hh&30)||di(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;mi(ai.bind(null,d,\nf,a),[a]);d.flags|=2048;bi(9,ci.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Th(),b=Q.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=\":\"+b+\"R\"+c;c=Kh++;0\\x3c/script>\",a=a.removeChild(a.firstChild)):\n\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;zj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case \"dialog\":D(\"cancel\",a);D(\"close\",a);e=d;break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;eGj&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304)}else{if(!d)if(a=Ch(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Dj(f,!0),null===f.tail&&\"hidden\"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Gj&&1073741824!==c&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=\nb,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=L.current,G(L,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Hj(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(fj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}\nfunction Ij(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return zh(),E(Wf),E(H),Eh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Bh(b),null;case 13:E(L);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(L),null;case 4:return zh(),null;case 10:return ah(b.type._context),null;case 22:case 23:return Hj(),\nnull;case 24:return null;default:return null}}var Jj=!1,U=!1,Kj=\"function\"===typeof WeakSet?WeakSet:Set,V=null;function Lj(a,b){var c=a.ref;if(null!==c)if(\"function\"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Mj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Nj=!1;\nfunction Oj(a,b){Cf=dd;a=Me();if(Ne(a)){if(\"selectionStart\"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=\nq.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;\ncase 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Ci(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent=\"\":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Nj;Nj=!1;return n}\nfunction Pj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Mj(b,c,f)}e=e.next}while(e!==d)}}function Qj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Rj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}\"function\"===typeof b?b(a):b.current=a}}\nfunction Sj(a){var b=a.alternate;null!==b&&(a.alternate=null,Sj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Tj(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction Uj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Tj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}\nfunction Vj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Vj(a,b,c),a=a.sibling;null!==a;)Vj(a,b,c),a=a.sibling}\nfunction Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}var X=null,Xj=!1;function Yj(a,b,c){for(c=c.child;null!==c;)Zj(a,b,c),c=c.sibling}\nfunction Zj(a,b,c){if(lc&&\"function\"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Lj(c,b);case 6:var d=X,e=Xj;X=null;Yj(a,b,c);X=d;Xj=e;null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Xj;X=c.stateNode.containerInfo;Xj=!0;\nYj(a,b,c);X=d;Xj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Mj(c,b,g):0!==(f&4)&&Mj(c,b,g));e=e.next}while(e!==d)}Yj(a,b,c);break;case 1:if(!U&&(Lj(c,b),d=c.stateNode,\"function\"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Yj(a,b,c);break;case 21:Yj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==\nc.memoizedState,Yj(a,b,c),U=d):Yj(a,b,c);break;default:Yj(a,b,c)}}function ak(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Kj);b.forEach(function(b){var d=bk.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction ck(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*lk(d/1960))-d;if(10a?16:a;if(null===wk)var d=!1;else{a=wk;wk=null;xk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-fk?Kk(a,0):rk|=c);Dk(a,b)}function Yk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=R();a=ih(a,b);null!==a&&(Ac(a,b,c),Dk(a,c))}function uj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Yk(a,c)}\nfunction bk(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Yk(a,c)}var Vk;\nVk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)dh=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return dh=!1,yj(a,b,c);dh=0!==(a.flags&131072)?!0:!1}else dh=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;ij(a,b);a=b.pendingProps;var e=Yf(b,H.current);ch(b,c);e=Nh(null,b,d,a,e,c);var f=Sh();b.flags|=1;\"object\"===typeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=\nnull,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,kh(b),e.updater=Ei,b.stateNode=e,e._reactInternals=b,Ii(b,d,a,c),b=jj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Xi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{ij(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Zk(d);a=Ci(d,a);switch(e){case 0:b=cj(null,b,d,a,c);break a;case 1:b=hj(null,b,d,a,c);break a;case 11:b=Yi(null,b,d,a,c);break a;case 14:b=$i(null,b,d,Ci(d.type,a),c);break a}throw Error(p(306,\nd,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),cj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),hj(a,b,d,e,c);case 3:a:{kj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;lh(a,b);qh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=\nf,b.memoizedState=f,b.flags&256){e=Ji(Error(p(423)),b);b=lj(a,b,d,c,e);break a}else if(d!==e){e=Ji(Error(p(424)),b);b=lj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Vg(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=Zi(a,b,c);break a}Xi(a,b,d,c)}b=b.child}return b;case 5:return Ah(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),\ngj(a,b),Xi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return oj(a,b,c);case 4:return yh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Ug(b,null,d,c):Xi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),Yi(a,b,d,e,c);case 7:return Xi(a,b,b.pendingProps,c),b.child;case 8:return Xi(a,b,b.pendingProps.children,c),b.child;case 12:return Xi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;\ng=e.value;G(Wg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=Zi(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=mh(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);bh(f.return,\nc,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);bh(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Xi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,ch(b,c),e=eh(e),d=d(e),b.flags|=1,Xi(a,b,d,c),\nb.child;case 14:return d=b.type,e=Ci(d,b.pendingProps),e=Ci(d.type,e),$i(a,b,d,e,c);case 15:return bj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),ij(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,ch(b,c),Gi(b,d,e),Ii(b,d,e,c),jj(null,b,d,!0,a,c);case 19:return xj(a,b,c);case 22:return dj(a,b,c)}throw Error(p(156,b.tag));};function Fk(a,b){return ac(a,b)}\nfunction $k(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new $k(a,b,c,d)}function aj(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction Zk(a){if(\"function\"===typeof a)return aj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}\nfunction Pg(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};\nc.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}\nfunction Rg(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)aj(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ya:return Tg(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return pj(c,e,f,b);default:if(\"object\"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;\nbreak a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,\"\"));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Tg(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function pj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function Qg(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}\nfunction Sg(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}\nfunction al(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=\nnull}function bl(a,b,c,d,e,f,g,h,k){a=new al(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};kh(f);return a}function cl(a,b,c){var d=3 ({ ok: true, value });\n/**\n * @ignore\n */\nexport const Err = (error) => ({ ok: false, error });\n//# sourceMappingURL=result.js.map","const dntGlobals = {};\nexport const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);\n// deno-lint-ignore ban-types\nfunction createMergeProxy(baseObj, extObj) {\n return new Proxy(baseObj, {\n get(_target, prop, _receiver) {\n if (prop in extObj) {\n return extObj[prop];\n }\n else {\n return baseObj[prop];\n }\n },\n set(_target, prop, value) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n baseObj[prop] = value;\n return true;\n },\n deleteProperty(_target, prop) {\n let success = false;\n if (prop in extObj) {\n delete extObj[prop];\n success = true;\n }\n if (prop in baseObj) {\n delete baseObj[prop];\n success = true;\n }\n return success;\n },\n ownKeys(_target) {\n const baseKeys = Reflect.ownKeys(baseObj);\n const extKeys = Reflect.ownKeys(extObj);\n const extKeysSet = new Set(extKeys);\n return [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];\n },\n defineProperty(_target, prop, desc) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n Reflect.defineProperty(baseObj, prop, desc);\n return true;\n },\n getOwnPropertyDescriptor(_target, prop) {\n if (prop in extObj) {\n return Reflect.getOwnPropertyDescriptor(extObj, prop);\n }\n else {\n return Reflect.getOwnPropertyDescriptor(baseObj, prop);\n }\n },\n has(_target, prop) {\n return prop in extObj || prop in baseObj;\n },\n });\n}\n//# sourceMappingURL=_dnt.shims.js.map","// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.\n// A module to print ANSI terminal colors. Inspired by chalk, kleur, and colors\n// on npm.\n/**\n * String formatters and utilities for dealing with ANSI color codes.\n *\n * This module is browser compatible.\n *\n * ```ts\n * import { bgBlue, red, bold } from \"https://deno.land/std@$STD_VERSION/fmt/colors.ts\";\n * console.log(bgBlue(red(bold(\"Hello world!\"))));\n * ```\n *\n * This module supports `NO_COLOR` environmental variable disabling any coloring\n * if `NO_COLOR` is set.\n *\n * @module\n */\n// deno-lint-ignore no-explicit-any\nimport * as dntShim from \"../../../../_dnt.shims.js\";\nconst { Deno } = dntShim.dntGlobalThis;\nconst noColor = typeof Deno?.noColor === \"boolean\"\n ? Deno.noColor\n : true;\nlet enabled = !noColor;\n/**\n * Set changing text color to enabled or disabled\n * @param value\n */\nexport function setColorEnabled(value) {\n if (noColor) {\n return;\n }\n enabled = value;\n}\n/** Get whether text color change is enabled or disabled. */\nexport function getColorEnabled() {\n return enabled;\n}\n/**\n * Builds color code\n * @param open\n * @param close\n */\nfunction code(open, close) {\n return {\n open: `\\x1b[${open.join(\";\")}m`,\n close: `\\x1b[${close}m`,\n regexp: new RegExp(`\\\\x1b\\\\[${close}m`, \"g\"),\n };\n}\n/**\n * Applies color and background based on color code and its associated text\n * @param str text to apply color settings to\n * @param code color code to apply\n */\nfunction run(str, code) {\n return enabled\n ? `${code.open}${str.replace(code.regexp, code.open)}${code.close}`\n : str;\n}\n/**\n * Reset the text modified\n * @param str text to reset\n */\nexport function reset(str) {\n return run(str, code([0], 0));\n}\n/**\n * Make the text bold.\n * @param str text to make bold\n */\nexport function bold(str) {\n return run(str, code([1], 22));\n}\n/**\n * The text emits only a small amount of light.\n * @param str text to dim\n */\nexport function dim(str) {\n return run(str, code([2], 22));\n}\n/**\n * Make the text italic.\n * @param str text to make italic\n */\nexport function italic(str) {\n return run(str, code([3], 23));\n}\n/**\n * Make the text underline.\n * @param str text to underline\n */\nexport function underline(str) {\n return run(str, code([4], 24));\n}\n/**\n * Invert background color and text color.\n * @param str text to invert its color\n */\nexport function inverse(str) {\n return run(str, code([7], 27));\n}\n/**\n * Make the text hidden.\n * @param str text to hide\n */\nexport function hidden(str) {\n return run(str, code([8], 28));\n}\n/**\n * Put horizontal line through the center of the text.\n * @param str text to strike through\n */\nexport function strikethrough(str) {\n return run(str, code([9], 29));\n}\n/**\n * Set text color to black.\n * @param str text to make black\n */\nexport function black(str) {\n return run(str, code([30], 39));\n}\n/**\n * Set text color to red.\n * @param str text to make red\n */\nexport function red(str) {\n return run(str, code([31], 39));\n}\n/**\n * Set text color to green.\n * @param str text to make green\n */\nexport function green(str) {\n return run(str, code([32], 39));\n}\n/**\n * Set text color to yellow.\n * @param str text to make yellow\n */\nexport function yellow(str) {\n return run(str, code([33], 39));\n}\n/**\n * Set text color to blue.\n * @param str text to make blue\n */\nexport function blue(str) {\n return run(str, code([34], 39));\n}\n/**\n * Set text color to magenta.\n * @param str text to make magenta\n */\nexport function magenta(str) {\n return run(str, code([35], 39));\n}\n/**\n * Set text color to cyan.\n * @param str text to make cyan\n */\nexport function cyan(str) {\n return run(str, code([36], 39));\n}\n/**\n * Set text color to white.\n * @param str text to make white\n */\nexport function white(str) {\n return run(str, code([37], 39));\n}\n/**\n * Set text color to gray.\n * @param str text to make gray\n */\nexport function gray(str) {\n return brightBlack(str);\n}\n/**\n * Set text color to bright black.\n * @param str text to make bright-black\n */\nexport function brightBlack(str) {\n return run(str, code([90], 39));\n}\n/**\n * Set text color to bright red.\n * @param str text to make bright-red\n */\nexport function brightRed(str) {\n return run(str, code([91], 39));\n}\n/**\n * Set text color to bright green.\n * @param str text to make bright-green\n */\nexport function brightGreen(str) {\n return run(str, code([92], 39));\n}\n/**\n * Set text color to bright yellow.\n * @param str text to make bright-yellow\n */\nexport function brightYellow(str) {\n return run(str, code([93], 39));\n}\n/**\n * Set text color to bright blue.\n * @param str text to make bright-blue\n */\nexport function brightBlue(str) {\n return run(str, code([94], 39));\n}\n/**\n * Set text color to bright magenta.\n * @param str text to make bright-magenta\n */\nexport function brightMagenta(str) {\n return run(str, code([95], 39));\n}\n/**\n * Set text color to bright cyan.\n * @param str text to make bright-cyan\n */\nexport function brightCyan(str) {\n return run(str, code([96], 39));\n}\n/**\n * Set text color to bright white.\n * @param str text to make bright-white\n */\nexport function brightWhite(str) {\n return run(str, code([97], 39));\n}\n/**\n * Set background color to black.\n * @param str text to make its background black\n */\nexport function bgBlack(str) {\n return run(str, code([40], 49));\n}\n/**\n * Set background color to red.\n * @param str text to make its background red\n */\nexport function bgRed(str) {\n return run(str, code([41], 49));\n}\n/**\n * Set background color to green.\n * @param str text to make its background green\n */\nexport function bgGreen(str) {\n return run(str, code([42], 49));\n}\n/**\n * Set background color to yellow.\n * @param str text to make its background yellow\n */\nexport function bgYellow(str) {\n return run(str, code([43], 49));\n}\n/**\n * Set background color to blue.\n * @param str text to make its background blue\n */\nexport function bgBlue(str) {\n return run(str, code([44], 49));\n}\n/**\n * Set background color to magenta.\n * @param str text to make its background magenta\n */\nexport function bgMagenta(str) {\n return run(str, code([45], 49));\n}\n/**\n * Set background color to cyan.\n * @param str text to make its background cyan\n */\nexport function bgCyan(str) {\n return run(str, code([46], 49));\n}\n/**\n * Set background color to white.\n * @param str text to make its background white\n */\nexport function bgWhite(str) {\n return run(str, code([47], 49));\n}\n/**\n * Set background color to bright black.\n * @param str text to make its background bright-black\n */\nexport function bgBrightBlack(str) {\n return run(str, code([100], 49));\n}\n/**\n * Set background color to bright red.\n * @param str text to make its background bright-red\n */\nexport function bgBrightRed(str) {\n return run(str, code([101], 49));\n}\n/**\n * Set background color to bright green.\n * @param str text to make its background bright-green\n */\nexport function bgBrightGreen(str) {\n return run(str, code([102], 49));\n}\n/**\n * Set background color to bright yellow.\n * @param str text to make its background bright-yellow\n */\nexport function bgBrightYellow(str) {\n return run(str, code([103], 49));\n}\n/**\n * Set background color to bright blue.\n * @param str text to make its background bright-blue\n */\nexport function bgBrightBlue(str) {\n return run(str, code([104], 49));\n}\n/**\n * Set background color to bright magenta.\n * @param str text to make its background bright-magenta\n */\nexport function bgBrightMagenta(str) {\n return run(str, code([105], 49));\n}\n/**\n * Set background color to bright cyan.\n * @param str text to make its background bright-cyan\n */\nexport function bgBrightCyan(str) {\n return run(str, code([106], 49));\n}\n/**\n * Set background color to bright white.\n * @param str text to make its background bright-white\n */\nexport function bgBrightWhite(str) {\n return run(str, code([107], 49));\n}\n/* Special Color Sequences */\n/**\n * Clam and truncate color codes\n * @param n\n * @param max number to truncate to\n * @param min number to truncate from\n */\nfunction clampAndTruncate(n, max = 255, min = 0) {\n return Math.trunc(Math.max(Math.min(n, max), min));\n}\n/**\n * Set text color using paletted 8bit colors.\n * https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit\n * @param str text color to apply paletted 8bit colors to\n * @param color code\n */\nexport function rgb8(str, color) {\n return run(str, code([38, 5, clampAndTruncate(color)], 39));\n}\n/**\n * Set background color using paletted 8bit colors.\n * https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit\n * @param str text color to apply paletted 8bit background colors to\n * @param color code\n */\nexport function bgRgb8(str, color) {\n return run(str, code([48, 5, clampAndTruncate(color)], 49));\n}\n/**\n * Set text color using 24bit rgb.\n * `color` can be a number in range `0x000000` to `0xffffff` or\n * an `Rgb`.\n *\n * To produce the color magenta:\n *\n * ```ts\n * import { rgb24 } from \"./colors.ts\";\n * rgb24(\"foo\", 0xff00ff);\n * rgb24(\"foo\", {r: 255, g: 0, b: 255});\n * ```\n * @param str text color to apply 24bit rgb to\n * @param color code\n */\nexport function rgb24(str, color) {\n if (typeof color === \"number\") {\n return run(str, code([38, 2, (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff], 39));\n }\n return run(str, code([\n 38,\n 2,\n clampAndTruncate(color.r),\n clampAndTruncate(color.g),\n clampAndTruncate(color.b),\n ], 39));\n}\n/**\n * Set background color using 24bit rgb.\n * `color` can be a number in range `0x000000` to `0xffffff` or\n * an `Rgb`.\n *\n * To produce the color magenta:\n *\n * ```ts\n * import { bgRgb24 } from \"./colors.ts\";\n * bgRgb24(\"foo\", 0xff00ff);\n * bgRgb24(\"foo\", {r: 255, g: 0, b: 255});\n * ```\n * @param str text color to apply 24bit rgb to\n * @param color code\n */\nexport function bgRgb24(str, color) {\n if (typeof color === \"number\") {\n return run(str, code([48, 2, (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff], 49));\n }\n return run(str, code([\n 48,\n 2,\n clampAndTruncate(color.r),\n clampAndTruncate(color.g),\n clampAndTruncate(color.b),\n ], 49));\n}\n// https://github.com/chalk/ansi-regex/blob/02fa893d619d3da85411acc8fd4e2eea0e95a9d9/index.js\nconst ANSI_PATTERN = new RegExp([\n \"[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)\",\n \"(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-nq-uy=><~]))\",\n].join(\"|\"), \"g\");\n/**\n * Remove ANSI escape codes from the string.\n * @param string to remove ANSI escape codes from\n */\nexport function stripColor(string) {\n return string.replace(ANSI_PATTERN, \"\");\n}\n//# sourceMappingURL=colors.js.map","// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.\n// This module is browser compatible.\nimport { bgGreen, bgRed, bold, gray, green, red, white, } from \"../fmt/colors.js\";\nexport var DiffType;\n(function (DiffType) {\n DiffType[\"removed\"] = \"removed\";\n DiffType[\"common\"] = \"common\";\n DiffType[\"added\"] = \"added\";\n})(DiffType || (DiffType = {}));\nconst REMOVED = 1;\nconst COMMON = 2;\nconst ADDED = 3;\nfunction createCommon(A, B, reverse) {\n const common = [];\n if (A.length === 0 || B.length === 0)\n return [];\n for (let i = 0; i < Math.min(A.length, B.length); i += 1) {\n if (A[reverse ? A.length - i - 1 : i] === B[reverse ? B.length - i - 1 : i]) {\n common.push(A[reverse ? A.length - i - 1 : i]);\n }\n else {\n return common;\n }\n }\n return common;\n}\n/**\n * Renders the differences between the actual and expected values\n * @param A Actual value\n * @param B Expected value\n */\nexport function diff(A, B) {\n const prefixCommon = createCommon(A, B);\n const suffixCommon = createCommon(A.slice(prefixCommon.length), B.slice(prefixCommon.length), true).reverse();\n A = suffixCommon.length\n ? A.slice(prefixCommon.length, -suffixCommon.length)\n : A.slice(prefixCommon.length);\n B = suffixCommon.length\n ? B.slice(prefixCommon.length, -suffixCommon.length)\n : B.slice(prefixCommon.length);\n const swapped = B.length > A.length;\n [A, B] = swapped ? [B, A] : [A, B];\n const M = A.length;\n const N = B.length;\n if (!M && !N && !suffixCommon.length && !prefixCommon.length)\n return [];\n if (!N) {\n return [\n ...prefixCommon.map((c) => ({ type: DiffType.common, value: c })),\n ...A.map((a) => ({\n type: swapped ? DiffType.added : DiffType.removed,\n value: a,\n })),\n ...suffixCommon.map((c) => ({ type: DiffType.common, value: c })),\n ];\n }\n const offset = N;\n const delta = M - N;\n const size = M + N + 1;\n const fp = Array.from({ length: size }, () => ({ y: -1, id: -1 }));\n /**\n * INFO:\n * This buffer is used to save memory and improve performance.\n * The first half is used to save route and last half is used to save diff\n * type.\n * This is because, when I kept new uint8array area to save type,performance\n * worsened.\n */\n const routes = new Uint32Array((M * N + size + 1) * 2);\n const diffTypesPtrOffset = routes.length / 2;\n let ptr = 0;\n let p = -1;\n function backTrace(A, B, current, swapped) {\n const M = A.length;\n const N = B.length;\n const result = [];\n let a = M - 1;\n let b = N - 1;\n let j = routes[current.id];\n let type = routes[current.id + diffTypesPtrOffset];\n while (true) {\n if (!j && !type)\n break;\n const prev = j;\n if (type === REMOVED) {\n result.unshift({\n type: swapped ? DiffType.removed : DiffType.added,\n value: B[b],\n });\n b -= 1;\n }\n else if (type === ADDED) {\n result.unshift({\n type: swapped ? DiffType.added : DiffType.removed,\n value: A[a],\n });\n a -= 1;\n }\n else {\n result.unshift({ type: DiffType.common, value: A[a] });\n a -= 1;\n b -= 1;\n }\n j = routes[prev];\n type = routes[prev + diffTypesPtrOffset];\n }\n return result;\n }\n function createFP(slide, down, k, M) {\n if (slide && slide.y === -1 && down && down.y === -1) {\n return { y: 0, id: 0 };\n }\n if ((down && down.y === -1) ||\n k === M ||\n (slide && slide.y) > (down && down.y) + 1) {\n const prev = slide.id;\n ptr++;\n routes[ptr] = prev;\n routes[ptr + diffTypesPtrOffset] = ADDED;\n return { y: slide.y, id: ptr };\n }\n else {\n const prev = down.id;\n ptr++;\n routes[ptr] = prev;\n routes[ptr + diffTypesPtrOffset] = REMOVED;\n return { y: down.y + 1, id: ptr };\n }\n }\n function snake(k, slide, down, _offset, A, B) {\n const M = A.length;\n const N = B.length;\n if (k < -N || M < k)\n return { y: -1, id: -1 };\n const fp = createFP(slide, down, k, M);\n while (fp.y + k < M && fp.y < N && A[fp.y + k] === B[fp.y]) {\n const prev = fp.id;\n ptr++;\n fp.id = ptr;\n fp.y += 1;\n routes[ptr] = prev;\n routes[ptr + diffTypesPtrOffset] = COMMON;\n }\n return fp;\n }\n while (fp[delta + offset].y < N) {\n p = p + 1;\n for (let k = -p; k < delta; ++k) {\n fp[k + offset] = snake(k, fp[k - 1 + offset], fp[k + 1 + offset], offset, A, B);\n }\n for (let k = delta + p; k > delta; --k) {\n fp[k + offset] = snake(k, fp[k - 1 + offset], fp[k + 1 + offset], offset, A, B);\n }\n fp[delta + offset] = snake(delta, fp[delta - 1 + offset], fp[delta + 1 + offset], offset, A, B);\n }\n return [\n ...prefixCommon.map((c) => ({ type: DiffType.common, value: c })),\n ...backTrace(A, B, fp[delta + offset], swapped),\n ...suffixCommon.map((c) => ({ type: DiffType.common, value: c })),\n ];\n}\n/**\n * Renders the differences between the actual and expected strings\n * Partially inspired from https://github.com/kpdecker/jsdiff\n * @param A Actual string\n * @param B Expected string\n */\nexport function diffstr(A, B) {\n function unescape(string) {\n // unescape invisible characters.\n // ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences\n return string\n .replaceAll(\"\\b\", \"\\\\b\")\n .replaceAll(\"\\f\", \"\\\\f\")\n .replaceAll(\"\\t\", \"\\\\t\")\n .replaceAll(\"\\v\", \"\\\\v\")\n .replaceAll(// does not remove line breaks\n /\\r\\n|\\r|\\n/g, (str) => str === \"\\r\" ? \"\\\\r\" : str === \"\\n\" ? \"\\\\n\\n\" : \"\\\\r\\\\n\\r\\n\");\n }\n function tokenize(string, { wordDiff = false } = {}) {\n if (wordDiff) {\n // Split string on whitespace symbols\n const tokens = string.split(/([^\\S\\r\\n]+|[()[\\]{}'\"\\r\\n]|\\b)/);\n // Extended Latin character set\n const words = /^[a-zA-Z\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}]+$/u;\n // Join boundary splits that we do not consider to be boundaries and merge empty strings surrounded by word chars\n for (let i = 0; i < tokens.length - 1; i++) {\n if (!tokens[i + 1] && tokens[i + 2] && words.test(tokens[i]) &&\n words.test(tokens[i + 2])) {\n tokens[i] += tokens[i + 2];\n tokens.splice(i + 1, 2);\n i--;\n }\n }\n return tokens.filter((token) => token);\n }\n else {\n // Split string on new lines symbols\n const tokens = [], lines = string.split(/(\\n|\\r\\n)/);\n // Ignore final empty token when text ends with a newline\n if (!lines[lines.length - 1]) {\n lines.pop();\n }\n // Merge the content and line separators into single tokens\n for (let i = 0; i < lines.length; i++) {\n if (i % 2) {\n tokens[tokens.length - 1] += lines[i];\n }\n else {\n tokens.push(lines[i]);\n }\n }\n return tokens;\n }\n }\n // Create details by filtering relevant word-diff for current line\n // and merge \"space-diff\" if surrounded by word-diff for cleaner displays\n function createDetails(line, tokens) {\n return tokens.filter(({ type }) => type === line.type || type === DiffType.common).map((result, i, t) => {\n if ((result.type === DiffType.common) && (t[i - 1]) &&\n (t[i - 1]?.type === t[i + 1]?.type) && /\\s+/.test(result.value)) {\n result.type = t[i - 1].type;\n }\n return result;\n });\n }\n // Compute multi-line diff\n const diffResult = diff(tokenize(`${unescape(A)}\\n`), tokenize(`${unescape(B)}\\n`));\n const added = [], removed = [];\n for (const result of diffResult) {\n if (result.type === DiffType.added) {\n added.push(result);\n }\n if (result.type === DiffType.removed) {\n removed.push(result);\n }\n }\n // Compute word-diff\n const aLines = added.length < removed.length ? added : removed;\n const bLines = aLines === removed ? added : removed;\n for (const a of aLines) {\n let tokens = [], b;\n // Search another diff line with at least one common token\n while (bLines.length) {\n b = bLines.shift();\n tokens = diff(tokenize(a.value, { wordDiff: true }), tokenize(b?.value ?? \"\", { wordDiff: true }));\n if (tokens.some(({ type, value }) => type === DiffType.common && value.trim().length)) {\n break;\n }\n }\n // Register word-diff details\n a.details = createDetails(a, tokens);\n if (b) {\n b.details = createDetails(b, tokens);\n }\n }\n return diffResult;\n}\n/**\n * Colors the output of assertion diffs\n * @param diffType Difference type, either added or removed\n */\nfunction createColor(diffType, { background = false } = {}) {\n // TODO(@littledivy): Remove this when we can detect\n // true color terminals.\n // https://github.com/denoland/deno_std/issues/2575\n background = false;\n switch (diffType) {\n case DiffType.added:\n return (s) => background ? bgGreen(white(s)) : green(bold(s));\n case DiffType.removed:\n return (s) => background ? bgRed(white(s)) : red(bold(s));\n default:\n return white;\n }\n}\n/**\n * Prefixes `+` or `-` in diff output\n * @param diffType Difference type, either added or removed\n */\nfunction createSign(diffType) {\n switch (diffType) {\n case DiffType.added:\n return \"+ \";\n case DiffType.removed:\n return \"- \";\n default:\n return \" \";\n }\n}\nexport function buildMessage(diffResult, { stringDiff = false } = {}) {\n const messages = [], diffMessages = [];\n messages.push(\"\");\n messages.push(\"\");\n messages.push(` ${gray(bold(\"[Diff]\"))} ${red(bold(\"Actual\"))} / ${green(bold(\"Expected\"))}`);\n messages.push(\"\");\n messages.push(\"\");\n diffResult.forEach((result) => {\n const c = createColor(result.type);\n const line = result.details?.map((detail) => detail.type !== DiffType.common\n ? createColor(detail.type, { background: true })(detail.value)\n : detail.value).join(\"\") ?? result.value;\n diffMessages.push(c(`${createSign(result.type)}${line}`));\n });\n messages.push(...(stringDiff ? [diffMessages.join(\"\")] : diffMessages));\n messages.push(\"\");\n return messages;\n}\n//# sourceMappingURL=_diff.js.map","// deno-lint-ignore-file no-explicit-any\nexport function* reset(block) {\n return yield { type: \"reset\", block };\n}\nexport function* shift(block) {\n return yield { type: \"shift\", block };\n}\nfunction createStack() {\n let list = [];\n return {\n reducing: false,\n push(...thunks) {\n return list.push(...thunks);\n },\n pop() {\n return list.pop();\n },\n };\n}\nexport function evaluate(iterator) {\n let stack = createStack();\n stack.push({\n method: \"next\",\n iterator: iterator()[Symbol.iterator](),\n });\n return reduce(stack);\n}\nfunction reduce(stack) {\n try {\n stack.reducing = true;\n for (let current = stack.pop(); current; current = stack.pop()) {\n try {\n let next = getNext(current);\n stack.value = next.value;\n if (!next.done) {\n let control = next.value;\n if (control.type === \"reset\") {\n stack.push({\n ...current,\n method: \"next\",\n get value() {\n return stack.value;\n },\n }, {\n method: \"next\",\n iterator: control.block()[Symbol.iterator](),\n });\n }\n else {\n let thunk = current;\n let resolve = oneshot((value) => {\n stack.push({\n method: \"next\",\n iterator: thunk.iterator,\n value,\n });\n return reduce(stack);\n });\n resolve.tail = oneshot((value) => {\n stack.push({\n method: \"next\",\n iterator: thunk.iterator,\n value,\n });\n if (!stack.reducing) {\n reduce(stack);\n }\n });\n let reject = oneshot((error) => {\n stack.push({\n method: \"throw\",\n iterator: thunk.iterator,\n value: error,\n });\n return reduce(stack);\n });\n reject.tail = oneshot((error) => {\n stack.push({\n method: \"throw\",\n iterator: thunk.iterator,\n value: error,\n });\n if (!stack.reducing) {\n reduce(stack);\n }\n });\n stack.push({\n method: \"next\",\n iterator: control.block(resolve, reject)[Symbol.iterator](),\n value: void 0,\n });\n }\n }\n }\n catch (error) {\n let top = stack.pop();\n if (top) {\n stack.push({ ...top, method: \"throw\", value: error });\n }\n else {\n throw error;\n }\n }\n }\n }\n finally {\n stack.reducing = false;\n }\n return stack.value;\n}\nfunction getNext(thunk) {\n let { iterator } = thunk;\n if (thunk.method === \"next\") {\n return iterator.next(thunk.value);\n }\n else {\n let value = thunk.value;\n if (iterator.throw) {\n return iterator.throw(value);\n }\n else {\n throw value;\n }\n }\n}\nfunction oneshot(fn) {\n let continued = false;\n let failure;\n let result;\n return ((value) => {\n if (!continued) {\n continued = true;\n try {\n return (result = fn(value));\n }\n catch (error) {\n failure = { error };\n throw error;\n }\n }\n else if (failure) {\n throw failure.error;\n }\n else {\n return result;\n }\n });\n}\n//# sourceMappingURL=mod.js.map","import { Err, Ok } from \"./result.js\";\nimport { shift } from \"./deps.js\";\nexport function* pause(install) {\n let uninstall = () => { };\n try {\n return yield function pause_i() {\n return shift(function* (k) {\n let resolve = (value) => k.tail(Ok(value));\n let reject = (error) => k.tail(Err(error));\n uninstall = install(resolve, reject);\n });\n };\n }\n finally {\n if (uninstall) {\n uninstall();\n }\n }\n}\n//# sourceMappingURL=pause.js.map","import { pause } from \"./pause.js\";\n/**\n * Creates a new queue. Queues are unlimited in size and sending a message to a\n * queue is always synchronous.\n *\n * @example\n *\n * ```javascript\n * import { each, main, createQueue } from 'effection';\n *\n * await main(function*() {\n * let queue = createQueue();\n * queue.send(1);\n * queue.send(2);\n * queue.send(3);\n *\n * let next = yield* queue.subscription.next();\n * while (!next.done) {\n * console.log(\"got number\", next.value);\n * next = yield* queue.subscription.next();\n * }\n * });\n * ```\n *\n * @typeParam T the type of the items in the queue\n * @typeParam TClose the type of the value that the queue is closed with\n */\nexport function createQueue() {\n let items = [];\n let consumers = new Set();\n function enqueue(item) {\n items.unshift(item);\n while (items.length > 0 && consumers.size > 0) {\n let [consume] = consumers;\n let top = items.pop();\n consume(top);\n }\n }\n return {\n add: (value) => enqueue({ done: false, value }),\n close: (value) => enqueue({ done: true, value }),\n *next() {\n let item = items.pop();\n if (item) {\n return item;\n }\n else {\n return yield* pause((resolve) => {\n consumers.add(resolve);\n return () => consumers.delete(resolve);\n });\n }\n },\n };\n}\n//# sourceMappingURL=queue.js.map","import { shift } from \"./deps.js\";\n/**\n * Create a shift computation where the body of the shift can be resolved\n * in a single step.\n *\n * before:\n * ```ts\n * yield* shift(function*(k) { return k; });\n * ```\n * after:\n * yield* shiftSync(k => k);\n */\nexport function shiftSync(block) {\n return shift((resolve, reject) => {\n return {\n [Symbol.iterator]: () => ({\n next() {\n let value = block(resolve, reject);\n return { done: true, value };\n },\n }),\n };\n });\n}\n//# sourceMappingURL=shift-sync.js.map","import { reset, shift } from \"./deps.js\";\nimport { shiftSync } from \"./shift-sync.js\";\nimport { Err, Ok } from \"./result.js\";\n/**\n * Indefinitely pause execution of the current operation. It is typically\n * used in conjunction with an {@link action} to mark the boundary\n * between setup and teardown.\n *\n * ```js\n * function onEvent(listener, name) {\n * return action(function* (resolve) {\n * try {\n * listener.addEventListener(name, resolve);\n * yield* suspend();\n * } finally {\n * listener.removeEventListener(name, resolve);\n * }\n * });\n * }\n * ```\n *\n * An operation will remain suspended until its enclosing scope is destroyed,\n * at which point it proceeds as though return had been called from the point\n * of suspension. Once an operation suspends once, further suspend operations\n * are ignored.\n *\n * @returns an operation that suspends the current operation\n */\nexport function suspend() {\n return instruction(Suspend);\n}\nfunction Suspend(frame) {\n return shiftSync((k) => {\n if (frame.aborted) {\n k.tail(Ok(void 0));\n }\n });\n}\n/**\n * Create an {@link Operation} that can be either resolved (or rejected) with\n * a synchronous callback. This is the Effection equivalent of `new Promise()`.\n *\n * The action body is itself an operation that runs in a new scope that is\n * destroyed completely before program execution returns to the point where the\n * action was yielded to.\n *\n * For example:\n *\n * ```js\n * let five = yield* action(function*(resolve, reject) {\n * setTimeout(() => {\n * if (Math.random() > 5) {\n * resolve(5)\n * } else {\n * reject(new Error(\"bad luck!\"));\n * }\n * }, 1000);\n * });\n *\n * ```\n *\n * However, it is customary to explicitly {@link suspend} inside the body of the\n * action so that whenever the action resolves, appropriate cleanup code can\n * run. The preceeding example would be more correctly written as:\n *\n * ```js\n * let five = yield* action(function*(resolve) {\n * let timeoutId = setTimeout(() => {\n * if (Math.random() > 5) {\n * resolve(5)\n * } else {\n * reject(new Error(\"bad luck!\"));\n * }\n * }, 1000);\n * try {\n * yield* suspend();\n * } finally {\n * clearTimout(timeoutId);\n * }\n * });\n * ```\n *\n * @typeParam T - type of the action's result.\n * @param operation - body of the action\n * @returns an operation producing the resolved value, or throwing the rejected error\n */\nexport function action(operation) {\n return instruction(function Action(frame) {\n return shift(function* (k) {\n let settle = yield* reset(function* () {\n let result = yield* shiftSync((k) => k.tail);\n let destruction = yield* child.destroy();\n if (!destruction.ok) {\n k.tail(destruction);\n }\n else {\n k.tail(result);\n }\n });\n let resolve = (value) => settle(Ok(value));\n let reject = (error) => settle(Err(error));\n let child = frame.createChild(function* () {\n yield* operation(resolve, reject);\n yield* suspend();\n });\n yield* reset(function* () {\n let result = yield* child;\n if (!result.ok) {\n k.tail(result);\n }\n });\n child.enter();\n });\n });\n}\n/**\n * Run another operation concurrently as a child of the current one.\n *\n * The spawned operation will begin executing immediately and control will\n * return to the caller when it reaches its first suspend point.\n *\n * ### Example\n *\n * ```typescript\n * import { main, sleep, suspend, spawn } from 'effection';\n *\n * await main(function*() {\n * yield* spawn(function*() {\n * yield* sleep(1000);\n * console.log(\"hello\");\n * });\n * yield* spawn(function*() {\n * yield* sleep(2000);\n * console.log(\"world\");\n * });\n * yield* suspend();\n * });\n * ```\n *\n * You should prefer using the spawn operation over calling\n * {@link Scope.run} from within Effection code. The reason being that a\n * synchronous failure in the spawned operation will not be caught\n * until the next yield point when using `run`, which results in lines\n * being executed that should not.\n *\n * ### Example\n *\n * ```typescript\n * import { main, suspend, spawn, useScope } from 'effection';\n *\n * await main(function*() {\n * yield* useScope();\n *\n * scope.run(function*() {\n * throw new Error('boom!');\n * });\n *\n * console.log('this code will run and probably should not');\n *\n * yield* suspend(); // <- error is thrown after this.\n * });\n * ```\n * @param operation the operation to run as a child of the current task\n * @typeParam T the type that the spawned task evaluates to\n * @returns a {@link Task} representing a handle to the running operation\n */\nexport function spawn(operation) {\n return instruction(function Spawn(frame) {\n return shift(function (k) {\n let child = frame.createChild(operation);\n child.enter();\n k.tail(Ok(child.getTask()));\n return reset(function* () {\n let result = yield* child;\n if (!result.ok) {\n yield* frame.crash(result.error);\n }\n });\n });\n });\n}\n/**\n * Define an Effection [resource](https://frontside.com/effection/docs/resources)\n *\n * Resources are a type of operation that passes a value back to its caller\n * while still allowing that operation to run in the background. It does this\n * by invoking the special `provide()` operation. The caller pauses until the\n * resource operation invokes `provide()` at which point the caller resumes with\n * passed value.\n *\n * `provide()` suspends the resource operation until the caller passes out of\n * scope.\n *\n * @example\n * ```js\n * function useWebSocket(url) {\n * return resource(function*(provide) {\n * let socket = new WebSocket(url);\n * yield* once(socket, 'open');\n *\n * try {\n * yield* provide(socket);\n * } finally {\n * socket.close();\n * yield* once(socket, 'close');\n * }\n * })\n * }\n *\n * await main(function*() {\n * let socket = yield* useWebSocket(\"wss://example.com\");\n * socket.send(\"hello world\");\n * });\n * ```\n *\n * @param operation the operation defining the lifecycle of the resource\n * @returns an operation yielding the resource\n */\nexport function resource(operation) {\n return instruction((frame) => shift(function (k) {\n function provide(value) {\n k.tail(Ok(value));\n return suspend();\n }\n let child = frame.createChild(() => operation(provide));\n child.enter();\n return reset(function* () {\n let result = yield* child;\n if (!result.ok) {\n k.tail(result);\n yield* frame.crash(result.error);\n }\n });\n }));\n}\n/**\n * @ignore\n */\nexport function getframe() {\n return instruction((frame) => shiftSync((k) => k.tail(Ok(frame))));\n}\n// An optimized iterator that yields the instruction on the first call\n// to next, then returns its value on the second. Equivalent to:\n// {\n// *[Symbol.iterator]() { return yield instruction; }\n// }\nfunction instruction(i) {\n return {\n [Symbol.iterator]() {\n let entered = false;\n return {\n next(value) {\n if (!entered) {\n entered = true;\n return { done: false, value: i };\n }\n else {\n return { done: true, value };\n }\n },\n throw(error) {\n throw error;\n },\n };\n },\n };\n}\n//# sourceMappingURL=instructions.js.map","export function create(tag, attrs, prototype) {\n let properties = {};\n for (let [key, value] of Object.entries(attrs)) {\n properties[key] = { enumerable: true, value };\n }\n return Object.create({\n ...prototype,\n [Symbol.toStringTag]: tag,\n }, properties);\n}\n//# sourceMappingURL=create.js.map","export function lazy(create) {\n let thunk = () => {\n let value = create();\n thunk = () => value;\n return value;\n };\n return () => thunk();\n}\n//# sourceMappingURL=lazy.js.map","import { reset } from \"../deps.js\";\nimport { shiftSync } from \"../shift-sync.js\";\nexport function* createValue() {\n let result = void 0;\n let listeners = new Set();\n let resolve = yield* reset(function* () {\n let value = yield* shiftSync((k) => k.tail);\n result = { value };\n for (let listener of listeners) {\n listeners.delete(listener);\n listener(value);\n }\n });\n let event = {\n [Symbol.iterator]() {\n if (result) {\n return sync(result.value);\n }\n else {\n return shiftSync((k) => {\n listeners.add(k.tail);\n })[Symbol.iterator]();\n }\n },\n };\n return [resolve, event];\n}\nexport function sync(value) {\n return {\n next() {\n return { done: true, value };\n },\n };\n}\n//# sourceMappingURL=value.js.map","import { evaluate } from \"../deps.js\";\nimport { Err } from \"../result.js\";\nimport { action } from \"../instructions.js\";\nimport { create } from \"./create.js\";\nexport function createTask(frame) {\n let promise;\n let awaitResult = (resolve, reject) => {\n evaluate(function* () {\n let result = getResult(yield* frame);\n if (result.ok) {\n resolve(result.value);\n }\n else {\n reject(result.error);\n }\n });\n };\n let getPromise = () => {\n promise = new Promise((resolve, reject) => {\n awaitResult(resolve, reject);\n });\n getPromise = () => promise;\n return promise;\n };\n let task = create(\"Task\", {}, {\n *[Symbol.iterator]() {\n let frameResult = evaluate(() => frame);\n if (frameResult) {\n let result = getResult(frameResult);\n if (result.ok) {\n return result.value;\n }\n else {\n throw result.error;\n }\n }\n else {\n return yield* action(function* (resolve, reject) {\n awaitResult(resolve, reject);\n });\n }\n },\n then: (...args) => getPromise().then(...args),\n catch: (...args) => getPromise().catch(...args),\n finally: (...args) => getPromise().finally(...args),\n halt() {\n let haltPromise;\n let getHaltPromise = () => {\n haltPromise = new Promise((resolve, reject) => {\n awaitHaltResult(resolve, reject);\n });\n getHaltPromise = () => haltPromise;\n frame.destroy();\n return haltPromise;\n };\n let awaitHaltResult = (resolve, reject) => {\n evaluate(function* () {\n let { destruction } = yield* frame;\n if (destruction.ok) {\n resolve();\n }\n else {\n reject(destruction.error);\n }\n });\n };\n return create(\"Future\", {}, {\n *[Symbol.iterator]() {\n let result = evaluate(() => frame);\n if (result) {\n if (!result.ok) {\n throw result.error;\n }\n }\n else {\n yield* action(function* (resolve, reject) {\n awaitHaltResult(resolve, reject);\n frame.destroy();\n });\n }\n },\n then: (...args) => getHaltPromise().then(...args),\n catch: (...args) => getHaltPromise().catch(...args),\n finally: (...args) => getHaltPromise().finally(...args),\n });\n },\n });\n return task;\n}\nfunction getResult(result) {\n if (!result.ok) {\n return result;\n }\n else if (result.exit.type === \"aborted\") {\n return Err(Error(\"halted\"));\n }\n else if (result.exit.type === \"crashed\") {\n return Err(result.exit.error);\n }\n else {\n return result.exit.result;\n }\n}\n//# sourceMappingURL=task.js.map","import { evaluate, shift } from \"../deps.js\";\nimport { shiftSync } from \"../shift-sync.js\";\nimport { lazy } from \"../lazy.js\";\nimport { Err, Ok } from \"../result.js\";\nimport { createValue } from \"./value.js\";\nimport { createTask } from \"./task.js\";\nimport { create } from \"./create.js\";\nlet ids = 0;\nexport function createFrame(options) {\n return evaluate(function* () {\n let { operation, parent } = options;\n let children = new Set();\n let context = Object.create(parent ?? {});\n let thunks = [{\n done: false,\n value: $next(void 0),\n }];\n let crash = void 0;\n let interrupt = () => { };\n let [setResults, results] = yield* createValue();\n let frame = yield* shiftSync((k) => {\n let self = create(\"Frame\", { id: ids++, context }, {\n createChild(operation) {\n let child = createFrame({ operation, parent: self.context });\n children.add(child);\n evaluate(function* () {\n yield* child;\n children.delete(child);\n });\n return child;\n },\n getTask() {\n let task = createTask(self);\n self.getTask = () => task;\n return task;\n },\n enter() {\n k.tail(self);\n },\n crash(error) {\n abort(error);\n return results;\n },\n destroy() {\n abort();\n return results;\n },\n [Symbol.iterator]: results[Symbol.iterator],\n });\n let abort = (reason) => {\n if (!self.aborted) {\n self.aborted = true;\n crash = reason;\n thunks.unshift({ done: false, value: $abort() });\n interrupt();\n }\n };\n return self;\n });\n let iterator = lazy(() => operation()[Symbol.iterator]());\n let thunk = thunks.pop();\n while (!thunk.done) {\n let getNext = thunk.value;\n try {\n let next = getNext(iterator());\n if (next.done) {\n thunks.unshift({ done: true, value: Ok(next.value) });\n }\n else {\n let instruction = next.value;\n let outcome = yield* shift(function* (k) {\n interrupt = () => k.tail({ type: \"interrupted\" });\n try {\n k.tail({\n type: \"settled\",\n result: yield* instruction(frame),\n });\n }\n catch (error) {\n k.tail({ type: \"settled\", result: Err(error) });\n }\n });\n if (outcome.type === \"settled\") {\n if (outcome.result.ok) {\n thunks.unshift({\n done: false,\n value: $next(outcome.result.value),\n });\n }\n else {\n thunks.unshift({\n done: false,\n value: $throw(outcome.result.error),\n });\n }\n }\n }\n }\n catch (error) {\n thunks.unshift({ done: true, value: Err(error) });\n }\n thunk = thunks.pop();\n }\n frame.exited = true;\n let result = thunk.value;\n let exit;\n if (!result.ok) {\n exit = { type: \"result\", result };\n }\n else if (crash) {\n exit = { type: \"crashed\", error: crash };\n }\n else if (frame.aborted) {\n exit = { type: \"aborted\" };\n }\n else {\n exit = { type: \"result\", result };\n }\n let destruction = Ok(void 0);\n while (children.size !== 0) {\n for (let child of [...children].reverse()) {\n let teardown = yield* child.destroy();\n if (!teardown.ok) {\n destruction = teardown;\n }\n }\n }\n if (!destruction.ok) {\n setResults({ ok: false, error: destruction.error, exit, destruction });\n }\n else {\n if (exit.type === \"aborted\") {\n setResults({ ok: true, value: void 0, exit, destruction });\n }\n else if (exit.type === \"result\") {\n let { result } = exit;\n if (result.ok) {\n setResults({ ok: true, value: void 0, exit, destruction });\n }\n else {\n setResults({ ok: false, error: result.error, exit, destruction });\n }\n }\n else {\n setResults({ ok: false, error: exit.error, exit, destruction });\n }\n }\n });\n}\n// deno-lint-ignore no-explicit-any\nconst $next = (value) => function $next(i) {\n return i.next(value);\n};\nconst $throw = (error) => function $throw(i) {\n if (i.throw) {\n return i.throw(error);\n }\n else {\n throw error;\n }\n};\nconst $abort = (value) => function $abort(i) {\n if (i.return) {\n return i.return(value);\n }\n else {\n return { done: true, value };\n }\n};\n//# sourceMappingURL=frame.js.map","import { evaluate } from \"../deps.js\";\nimport { create } from \"./create.js\";\nimport { createFrame } from \"./frame.js\";\nimport { getframe, suspend } from \"../instructions.js\";\n/**\n * Get the scope of the currently running {@link Operation}.\n *\n * @returns an operation yielding the current scope\n */\nexport function* useScope() {\n let frame = yield* getframe();\n let [scope] = createScope(frame);\n return scope;\n}\n/**\n * Create a new scope to serve as an entry point from normal\n * JavaScript execution into Effection.\n *\n * When creating a fresh scope (as opposed to capturing a reference to\n * an existing one via {@link useScope}) it is the responsibility of\n * the creator of the new scope to destroy it when it is no longer needed.\n *\n * @example\n * ```js\n * let [scope, destroy] = createScope();\n * let task = scope.run(function*() {\n * //do some long running work\n * });\n *\n * //... later\n * await destroy();\n *\n * ```\n * @returns a tuple containing the new scope, and a function to destroy it.\n */\nexport function createScope(frame) {\n let parent = frame ?? createFrame({ operation: suspend });\n let scope = create(\"Scope\", {}, {\n run(operation) {\n if (parent.exited) {\n let error = new Error(`cannot call run() on a scope that has already been exited`);\n error.name = \"InactiveScopeError\";\n throw error;\n }\n let frame = parent.createChild(operation);\n frame.enter();\n evaluate(function* () {\n let result = yield* frame;\n if (!result.ok) {\n yield* parent.crash(result.error);\n }\n });\n return frame.getTask();\n },\n get(context) {\n let { key, defaultValue } = context;\n return (parent.context[key] ?? defaultValue);\n },\n set(context, value) {\n let { key } = context;\n parent.context[key] = value;\n return value;\n },\n });\n parent.enter();\n return [scope, parent.getTask().halt];\n}\n//# sourceMappingURL=scope.js.map","import { create } from \"./run/create.js\";\nimport { useScope } from \"./run/scope.js\";\nexport function createContext(key, defaultValue) {\n let context = create(`Context`, { key }, {\n defaultValue,\n *get() {\n let scope = yield* useScope();\n return scope.get(context);\n },\n *set(value) {\n let scope = yield* useScope();\n return scope.set(context, value);\n },\n *[Symbol.iterator]() {\n let value = yield* context.get();\n if (typeof value === \"undefined\") {\n throw new MissingContextError(`missing required context: '${key}'`);\n }\n else {\n return value;\n }\n },\n });\n return context;\n}\nclass MissingContextError extends Error {\n constructor() {\n super(...arguments);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: \"MissingContextError\"\n });\n }\n}\n//# sourceMappingURL=context.js.map","import { createQueue } from \"./queue.js\";\nimport { resource } from \"./instructions.js\";\nimport { createContext } from \"./context.js\";\n/**\n * @ignore\n * {@link Context} that contains a {@link Queue} factory to be used when creating a {@link Signal}.\n *\n * This allows end-users to customize a Signal's Queue.\n *\n * @example\n * ```javascript\n * export function useActions(pattern: ActionPattern): Stream {\n * return {\n * *subscribe() {\n * const actions = yield* ActionContext;\n * yield* QueueFactory.set(() => createFilterQueue(matcher(pattern));\n * return yield* actions.subscribe();\n * }\n * }\n * }\n *\n * function createFilterQueue(predicate: Predicate) {\n * let queue = createQueue();\n *\n * return {\n * ...queue,\n * add(value) {\n * if (predicate(value)) {\n * queue.add(value);\n * }\n * }\n * }\n * }\n * ```\n */\nexport const SignalQueueFactory = createContext(\"Signal.createQueue\", createQueue);\n/**\n * Create a new {@link Signal}\n *\n * Signal should be used when you need to send messages to a stream\n * from _outside_ of an operation. The most common case of this is to\n * connect a plain, synchronous JavaScript callback to an operation.\n *\n * @example\n * ```javascript\n * function* logClicks(button) {\n * let clicks = createSignal();\n * try {\n * button.addEventListener(\"click\", clicks.send);\n *\n * for (let click of yield* each(clicks)) {\n * console.log(\"click\", click);\n * }\n * } finally {\n * button.removeEventListener(\"click\", clicks.send);\n * }\n * }\n * ```\n *\n * Do not use a signal to send messages from within an operation as it could\n * result in out-of-scope code being executed. In those cases, you should use a\n * {@link Channel}.\n */\nexport function createSignal() {\n let subscribers = new Set();\n let useSubscription = resource(function* (provide) {\n let newQueue = yield* SignalQueueFactory;\n let queue = newQueue();\n subscribers.add(queue);\n try {\n yield* provide({ next: queue.next });\n }\n finally {\n subscribers.delete(queue);\n }\n });\n function send(value) {\n for (let queue of [...subscribers]) {\n queue.add(value);\n }\n }\n function close(value) {\n for (let queue of [...subscribers]) {\n queue.close(value);\n }\n }\n return { send, close, subscribe: () => useSubscription };\n}\n//# sourceMappingURL=signal.js.map","/**\n * Convert a simple function into an {@link Operation}\n *\n * @example\n * ```js\n * let log = lift((message) => console.log(message));\n *\n * export function* run() {\n * yield* log(\"hello world\");\n * yield* log(\"done\");\n * }\n * ```\n *\n * @returns a function returning an operation that invokes `fn` when evaluated\n */\nexport function lift(fn) {\n return (...args) => {\n return ({\n [Symbol.iterator]() {\n let value = fn(...args);\n return { next: () => ({ done: true, value }) };\n },\n });\n };\n}\n//# sourceMappingURL=lift.js.map","import { createSignal } from \"./signal.js\";\nimport { lift } from \"./lift.js\";\n/**\n * Create a new {@link Channel}. Use channels to communicate between operations.\n * In order to dispatch messages from outside an operation such as from a\n * callback, use {@link Signal}.\n *\n * See [the guide on Streams and\n * Subscriptions](https://frontside.com/effection/docs/guides/collections)\n * for more details.\n *\n * @example\n *\n * ``` javascript\n * import { main, createChannel } from 'effection';\n *\n * await main(function*() {\n * let channel = createChannel();\n *\n * yield* channel.send('too early'); // the channel has no subscribers yet!\n *\n * let subscription1 = yield* channel.subscribe();\n * let subscription2 = yield* channel.subscribe();\n *\n * yield* channel.send('hello');\n * yield* channel.send('world');\n *\n * console.log(yield* subscription1.next()); //=> { done: false, value: 'hello' }\n * console.log(yield* subscription1.next()); //=> { done: false, value: 'world' }\n * console.log(yield* subscription2.next()); //=> { done: false, value: 'hello' }\n * console.log(yield* subscription2.next()); //=> { done: false, value: 'world' }\n * });\n * ```\n */\nexport function createChannel() {\n let signal = createSignal();\n return {\n send: lift(signal.send),\n close: lift(signal.close),\n subscribe: signal.subscribe,\n };\n}\n//# sourceMappingURL=channel.js.map","import { action } from \"./instructions.js\";\nimport { pause } from \"./pause.js\";\nexport function call(callable) {\n return action(function* (resolve, reject) {\n try {\n if (typeof callable === \"function\") {\n let fn = callable;\n resolve(yield* toop(fn()));\n }\n else {\n resolve(yield* toop(callable));\n }\n }\n catch (error) {\n reject(error);\n }\n });\n}\nfunction toop(op) {\n if (isPromise(op)) {\n return expect(op);\n }\n else if (isIterable(op)) {\n let iter = op[Symbol.iterator]();\n if (isInstructionIterator(iter)) {\n // operation\n return op;\n }\n else {\n // We are assuming that if an iterator does *not* have `.throw` then\n // it must be a built-in iterator and we should return the value as-is.\n return bare(op);\n }\n }\n else {\n return bare(op);\n }\n}\nfunction bare(val) {\n return {\n [Symbol.iterator]() {\n return { next: () => ({ done: true, value: val }) };\n },\n };\n}\nfunction expect(promise) {\n return pause((resolve, reject) => {\n promise.then(resolve, reject);\n return () => { };\n });\n}\nfunction isFunc(f) {\n return typeof f === \"function\";\n}\nfunction isPromise(p) {\n if (!p)\n return false;\n return isFunc(p.then);\n}\n// iterator must implement both `.next` and `.throw`\n// built-in iterators are not considered iterators to `call()`\nfunction isInstructionIterator(it) {\n if (!it)\n return false;\n return isFunc(it.next) &&\n isFunc(it.throw);\n}\nfunction isIterable(it) {\n if (!it)\n return false;\n return typeof it[Symbol.iterator] === \"function\";\n}\n//# sourceMappingURL=call.js.map","import { action, suspend } from \"./instructions.js\";\n/**\n * Sleep for the given amount of milliseconds.\n *\n * @example\n * ```typescript\n * import { main, sleep } from 'effection';\n *\n * await main(function*() {\n * yield sleep(2000);\n * console.log(\"Hello lazy world!\");\n * });\n * ```\n *\n * @param duration - the number of milliseconds to sleep\n */\nexport function sleep(duration) {\n return action(function* sleep(resolve) {\n let timeoutId = setTimeout(resolve, duration);\n try {\n yield* suspend();\n }\n finally {\n clearTimeout(timeoutId);\n }\n });\n}\n//# sourceMappingURL=sleep.js.map","import { createContext } from \"./context.js\";\n/**\n * Consume an effection stream using a simple for-of loop.\n *\n * Given any stream, you can access its values sequentially using the `each()`\n * operation just as you would use `for await of` loop with an async iterable:\n *\n * ```javascript\n * function* logvalues(stream) {\n * for (let value of yield* each(stream)) {\n * console.log(value);\n * yield* each.next()\n * }\n * }\n * ```\n * You must always invoke `each.next` at the end of each iteration of the loop,\n * including if the interation ends with a `continue` statement.\n *\n * Note that just as with async iterators, there is no way to consume the\n * `TClose` value of a stream using the `for-each` loop.\n *\n * @typeParam T - the type of each value in the stream.\n * @param stream - the stream to iterate\n * @returns an operation to iterate `stream`\n */\nexport function each(stream) {\n return {\n *[Symbol.iterator]() {\n let subscription = yield* stream.subscribe();\n let current = yield* subscription.next();\n let stack = yield* EachStack.get();\n if (!stack) {\n stack = yield* EachStack.set([]);\n }\n let context = { subscription, current };\n stack.push(context);\n let iterator = {\n next() {\n if (context.stale) {\n let error = new Error(`for each loop did not use each.next() operation before continuing`);\n error.name = \"IterationError\";\n throw error;\n }\n else {\n context.stale = true;\n return context.current;\n }\n },\n return() {\n stack.pop();\n return { done: true, value: void 0 };\n },\n };\n return {\n [Symbol.iterator]: () => iterator,\n };\n },\n };\n}\neach.next = function next() {\n return {\n name: \"each.next()\",\n *[Symbol.iterator]() {\n let stack = yield* EachStack;\n let context = stack[stack.length - 1];\n if (!context) {\n let error = new Error(`cannot call next() outside of an iteration`);\n error.name = \"IterationError\";\n throw error;\n }\n let current = yield* context.subscription.next();\n delete context.stale;\n context.current = current;\n if (current.done) {\n stack.pop();\n }\n },\n };\n};\nconst EachStack = createContext(\"each\");\n//# sourceMappingURL=each.js.map","import { resource } from \"./instructions.js\";\n/**\n * Run the given function or operation when the current operation\n * shuts down. This is equivalent to running the function or operation\n * in a `finally {}` block, but it can help you avoid rightward drift.\n *\n * @example using a function\n *\n * ```javascript\n * import { main, ensure } from 'effection';\n * import { createServer } from 'http';\n *\n * await main(function*() {\n * let server = createServer(...);\n * yield* ensure(() => { server.close() });\n * });\n * ```\n *\n * Note that you should wrap the function body in braces, so the function\n * returns `undefined`.\n *\n * @example using operation\n *\n * ```javascript\n * import { main, ensure, once } from 'effection';\n * import { createServer } from 'http';\n *\n * await main(function*() {\n * let server = createServer(...);\n * yield* ensure(function* () {\n * server.close();\n * yield* once(server, 'closed');\n * });\n * });\n * ```\n *\n * Your ensure function should return an operation whenever you need to do\n * asynchronous cleanup. Otherwise, you can return `void`\n *\n * @param fn - a function which returns an {@link Operation} or void\n */\nexport function ensure(fn) {\n return resource(function* (provide) {\n try {\n yield* provide();\n }\n finally {\n let result = fn();\n if (result && typeof result[Symbol.iterator] === \"function\") {\n yield* result;\n }\n }\n });\n}\n//# sourceMappingURL=ensure.js.map","import { action, spawn } from \"./instructions.js\";\n/**\n * Race the given operations against each other and return the value of\n * whichever operation returns first. This has the same purpose as\n * [Promise.race](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race).\n *\n * If an operation become errored first, then `race` will fail with this error.\n * After the first operation wins the race, all other operations will become\n * halted and therefore cannot throw any further errors.\n *\n * @example\n *\n * ```typescript\n * import { main, race, fetch } from 'effection';\n *\n * await main(function*() {\n * let fastest = yield* race([fetch('http://google.com'), fetch('http://bing.com')]);\n * // ...\n * });\n * ```\n *\n * @typeParam T the type of the operations that race against each other\n * @param operations a list of operations to race against each other\n * @returns the value of the fastest operation\n */\nexport function race(operations) {\n return action(function* (resolve, reject) {\n for (let operation of operations) {\n yield* spawn(function* () {\n try {\n resolve(yield* operation);\n }\n catch (error) {\n reject(error);\n }\n });\n }\n });\n}\n//# sourceMappingURL=race.js.map","/**\n * @license React\n * use-sync-external-store-shim.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var e=require(\"react\");function h(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k=\"function\"===typeof Object.is?Object.is:h,l=e.useState,m=e.useEffect,n=e.useLayoutEffect,p=e.useDebugValue;function q(a,b){var d=b(),f=l({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n(function(){c.value=d;c.getSnapshot=b;r(c)&&g({inst:c})},[a,d,b]);m(function(){r(c)&&g({inst:c});return a(function(){r(c)&&g({inst:c})})},[a]);p(d);return d}\nfunction r(a){var b=a.getSnapshot;a=a.value;try{var d=b();return!k(a,d)}catch(f){return!0}}function t(a,b){return b()}var u=\"undefined\"===typeof window||\"undefined\"===typeof window.document||\"undefined\"===typeof window.document.createElement?t:q;exports.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim.production.min.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim.development.js');\n}\n","/**\n * @license React\n * use-sync-external-store-shim/with-selector.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var h=require(\"react\"),n=require(\"use-sync-external-store/shim\");function p(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var q=\"function\"===typeof Object.is?Object.is:p,r=n.useSyncExternalStore,t=h.useRef,u=h.useEffect,v=h.useMemo,w=h.useDebugValue;\nexports.useSyncExternalStoreWithSelector=function(a,b,e,l,g){var c=t(null);if(null===c.current){var f={hasValue:!1,value:null};c.current=f}else f=c.current;c=v(function(){function a(a){if(!c){c=!0;d=a;a=l(a);if(void 0!==g&&f.hasValue){var b=f.value;if(g(b,a))return k=b}return k=a}b=k;if(q(d,a))return b;var e=l(a);if(void 0!==g&&g(b,e))return b;d=a;return k=e}var c=!1,d,k,m=void 0===e?null:e;return[function(){return a(b())},null===m?void 0:function(){return a(m())}]},[b,e,l,g]);var d=r(a,c[0],c[1]);\nu(function(){f.hasValue=!0;f.value=d},[d]);w(d);return d};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.production.min.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.development.js');\n}\n","// Default to a dummy \"batch\" implementation that just runs the callback\nfunction defaultNoopBatch(callback) {\n callback();\n}\n\nlet batch = defaultNoopBatch; // Allow injecting another batching function later\n\nexport const setBatch = newBatch => batch = newBatch; // Supply a getter just to skip dealing with ESM bindings\n\nexport const getBatch = () => batch;","import * as React from 'react';\nconst ContextKey = Symbol.for(`react-redux-context`);\nconst gT = typeof globalThis !== \"undefined\" ? globalThis :\n/* fall back to a per-module scope (pre-8.1 behaviour) if `globalThis` is not available */\n{};\n\nfunction getContext() {\n var _gT$ContextKey;\n\n if (!React.createContext) return {};\n const contextMap = (_gT$ContextKey = gT[ContextKey]) != null ? _gT$ContextKey : gT[ContextKey] = new Map();\n let realContext = contextMap.get(React.createContext);\n\n if (!realContext) {\n realContext = React.createContext(null);\n\n if (process.env.NODE_ENV !== 'production') {\n realContext.displayName = 'ReactRedux';\n }\n\n contextMap.set(React.createContext, realContext);\n }\n\n return realContext;\n}\n\nexport const ReactReduxContext = /*#__PURE__*/getContext();\nexport default ReactReduxContext;","import { useContext } from 'react';\nimport { ReactReduxContext } from '../components/Context';\n\n/**\r\n * Hook factory, which creates a `useReduxContext` hook bound to a given context. This is a low-level\r\n * hook that you should usually not need to call directly.\r\n *\r\n * @param {React.Context} [context=ReactReduxContext] Context passed to your ``.\r\n * @returns {Function} A `useReduxContext` hook bound to the specified context.\r\n */\nexport function createReduxContextHook(context = ReactReduxContext) {\n return function useReduxContext() {\n const contextValue = useContext(context);\n\n if (process.env.NODE_ENV !== 'production' && !contextValue) {\n throw new Error('could not find react-redux context value; please ensure the component is wrapped in a ');\n }\n\n return contextValue;\n };\n}\n/**\r\n * A hook to access the value of the `ReactReduxContext`. This is a low-level\r\n * hook that you should usually not need to call directly.\r\n *\r\n * @returns {any} the value of the `ReactReduxContext`\r\n *\r\n * @example\r\n *\r\n * import React from 'react'\r\n * import { useReduxContext } from 'react-redux'\r\n *\r\n * export const CounterComponent = () => {\r\n * const { store } = useReduxContext()\r\n * return
{store.getState()}
\r\n * }\r\n */\n\nexport const useReduxContext = /*#__PURE__*/createReduxContextHook();","export const notInitialized = () => {\n throw new Error('uSES not initialized!');\n};","import { useCallback, useDebugValue, useRef } from 'react';\nimport { createReduxContextHook, useReduxContext as useDefaultReduxContext } from './useReduxContext';\nimport { ReactReduxContext } from '../components/Context';\nimport { notInitialized } from '../utils/useSyncExternalStore';\nlet useSyncExternalStoreWithSelector = notInitialized;\nexport const initializeUseSelector = fn => {\n useSyncExternalStoreWithSelector = fn;\n};\n\nconst refEquality = (a, b) => a === b;\n/**\r\n * Hook factory, which creates a `useSelector` hook bound to a given context.\r\n *\r\n * @param {React.Context} [context=ReactReduxContext] Context passed to your ``.\r\n * @returns {Function} A `useSelector` hook bound to the specified context.\r\n */\n\n\nexport function createSelectorHook(context = ReactReduxContext) {\n const useReduxContext = context === ReactReduxContext ? useDefaultReduxContext : createReduxContextHook(context);\n return function useSelector(selector, equalityFnOrOptions = {}) {\n const {\n equalityFn = refEquality,\n stabilityCheck = undefined,\n noopCheck = undefined\n } = typeof equalityFnOrOptions === 'function' ? {\n equalityFn: equalityFnOrOptions\n } : equalityFnOrOptions;\n\n if (process.env.NODE_ENV !== 'production') {\n if (!selector) {\n throw new Error(`You must pass a selector to useSelector`);\n }\n\n if (typeof selector !== 'function') {\n throw new Error(`You must pass a function as a selector to useSelector`);\n }\n\n if (typeof equalityFn !== 'function') {\n throw new Error(`You must pass a function as an equality function to useSelector`);\n }\n }\n\n const {\n store,\n subscription,\n getServerState,\n stabilityCheck: globalStabilityCheck,\n noopCheck: globalNoopCheck\n } = useReduxContext();\n const firstRun = useRef(true);\n const wrappedSelector = useCallback({\n [selector.name](state) {\n const selected = selector(state);\n\n if (process.env.NODE_ENV !== 'production') {\n const finalStabilityCheck = typeof stabilityCheck === 'undefined' ? globalStabilityCheck : stabilityCheck;\n\n if (finalStabilityCheck === 'always' || finalStabilityCheck === 'once' && firstRun.current) {\n const toCompare = selector(state);\n\n if (!equalityFn(selected, toCompare)) {\n let stack = undefined;\n\n try {\n throw new Error();\n } catch (e) {\n ;\n ({\n stack\n } = e);\n }\n\n console.warn('Selector ' + (selector.name || 'unknown') + ' returned a different result when called with the same parameters. This can lead to unnecessary rerenders.' + '\\nSelectors that return a new reference (such as an object or an array) should be memoized: https://redux.js.org/usage/deriving-data-selectors#optimizing-selectors-with-memoization', {\n state,\n selected,\n selected2: toCompare,\n stack\n });\n }\n }\n\n const finalNoopCheck = typeof noopCheck === 'undefined' ? globalNoopCheck : noopCheck;\n\n if (finalNoopCheck === 'always' || finalNoopCheck === 'once' && firstRun.current) {\n // @ts-ignore\n if (selected === state) {\n let stack = undefined;\n\n try {\n throw new Error();\n } catch (e) {\n ;\n ({\n stack\n } = e);\n }\n\n console.warn('Selector ' + (selector.name || 'unknown') + ' returned the root state when called. This can lead to unnecessary rerenders.' + '\\nSelectors that return the entire state are almost certainly a mistake, as they will cause a rerender whenever *anything* in state changes.', {\n stack\n });\n }\n }\n\n if (firstRun.current) firstRun.current = false;\n }\n\n return selected;\n }\n\n }[selector.name], [selector, globalStabilityCheck, stabilityCheck]);\n const selectedState = useSyncExternalStoreWithSelector(subscription.addNestedSub, store.getState, getServerState || store.getState, wrappedSelector, equalityFn);\n useDebugValue(selectedState);\n return selectedState;\n };\n}\n/**\r\n * A hook to access the redux store's state. This hook takes a selector function\r\n * as an argument. The selector is called with the store state.\r\n *\r\n * This hook takes an optional equality comparison function as the second parameter\r\n * that allows you to customize the way the selected state is compared to determine\r\n * whether the component needs to be re-rendered.\r\n *\r\n * @param {Function} selector the selector function\r\n * @param {Function=} equalityFn the function that will be used to determine equality\r\n *\r\n * @returns {any} the selected state\r\n *\r\n * @example\r\n *\r\n * import React from 'react'\r\n * import { useSelector } from 'react-redux'\r\n *\r\n * export const CounterComponent = () => {\r\n * const counter = useSelector(state => state.counter)\r\n * return
{counter}
\r\n * }\r\n */\n\nexport const useSelector = /*#__PURE__*/createSelectorHook();","/** @license React v16.13.1\n * react-is.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';var b=\"function\"===typeof Symbol&&Symbol.for,c=b?Symbol.for(\"react.element\"):60103,d=b?Symbol.for(\"react.portal\"):60106,e=b?Symbol.for(\"react.fragment\"):60107,f=b?Symbol.for(\"react.strict_mode\"):60108,g=b?Symbol.for(\"react.profiler\"):60114,h=b?Symbol.for(\"react.provider\"):60109,k=b?Symbol.for(\"react.context\"):60110,l=b?Symbol.for(\"react.async_mode\"):60111,m=b?Symbol.for(\"react.concurrent_mode\"):60111,n=b?Symbol.for(\"react.forward_ref\"):60112,p=b?Symbol.for(\"react.suspense\"):60113,q=b?\nSymbol.for(\"react.suspense_list\"):60120,r=b?Symbol.for(\"react.memo\"):60115,t=b?Symbol.for(\"react.lazy\"):60116,v=b?Symbol.for(\"react.block\"):60121,w=b?Symbol.for(\"react.fundamental\"):60117,x=b?Symbol.for(\"react.responder\"):60118,y=b?Symbol.for(\"react.scope\"):60119;\nfunction z(a){if(\"object\"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;\nexports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};\nexports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};\nexports.isValidElementType=function(a){return\"string\"===typeof a||\"function\"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||\"object\"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-is.production.min.js');\n} else {\n module.exports = require('./cjs/react-is.development.js');\n}\n","'use strict';\n\nvar reactIs = require('react-is');\n\n/**\n * Copyright 2015, Yahoo! Inc.\n * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.\n */\nvar REACT_STATICS = {\n childContextTypes: true,\n contextType: true,\n contextTypes: true,\n defaultProps: true,\n displayName: true,\n getDefaultProps: true,\n getDerivedStateFromError: true,\n getDerivedStateFromProps: true,\n mixins: true,\n propTypes: true,\n type: true\n};\nvar KNOWN_STATICS = {\n name: true,\n length: true,\n prototype: true,\n caller: true,\n callee: true,\n arguments: true,\n arity: true\n};\nvar FORWARD_REF_STATICS = {\n '$$typeof': true,\n render: true,\n defaultProps: true,\n displayName: true,\n propTypes: true\n};\nvar MEMO_STATICS = {\n '$$typeof': true,\n compare: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n type: true\n};\nvar TYPE_STATICS = {};\nTYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;\nTYPE_STATICS[reactIs.Memo] = MEMO_STATICS;\n\nfunction getStatics(component) {\n // React v16.11 and below\n if (reactIs.isMemo(component)) {\n return MEMO_STATICS;\n } // React v16.12 and above\n\n\n return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;\n}\n\nvar defineProperty = Object.defineProperty;\nvar getOwnPropertyNames = Object.getOwnPropertyNames;\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar getPrototypeOf = Object.getPrototypeOf;\nvar objectPrototype = Object.prototype;\nfunction hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {\n if (typeof sourceComponent !== 'string') {\n // don't hoist over string (html) components\n if (objectPrototype) {\n var inheritedComponent = getPrototypeOf(sourceComponent);\n\n if (inheritedComponent && inheritedComponent !== objectPrototype) {\n hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);\n }\n }\n\n var keys = getOwnPropertyNames(sourceComponent);\n\n if (getOwnPropertySymbols) {\n keys = keys.concat(getOwnPropertySymbols(sourceComponent));\n }\n\n var targetStatics = getStatics(targetComponent);\n var sourceStatics = getStatics(sourceComponent);\n\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n\n if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {\n var descriptor = getOwnPropertyDescriptor(sourceComponent, key);\n\n try {\n // Avoid failures from read-only properties\n defineProperty(targetComponent, key, descriptor);\n } catch (e) {}\n }\n }\n }\n\n return targetComponent;\n}\n\nmodule.exports = hoistNonReactStatics;\n","/**\n * @license React\n * react-is.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var b=Symbol.for(\"react.element\"),c=Symbol.for(\"react.portal\"),d=Symbol.for(\"react.fragment\"),e=Symbol.for(\"react.strict_mode\"),f=Symbol.for(\"react.profiler\"),g=Symbol.for(\"react.provider\"),h=Symbol.for(\"react.context\"),k=Symbol.for(\"react.server_context\"),l=Symbol.for(\"react.forward_ref\"),m=Symbol.for(\"react.suspense\"),n=Symbol.for(\"react.suspense_list\"),p=Symbol.for(\"react.memo\"),q=Symbol.for(\"react.lazy\"),t=Symbol.for(\"react.offscreen\"),u;u=Symbol.for(\"react.module.reference\");\nfunction v(a){if(\"object\"===typeof a&&null!==a){var r=a.$$typeof;switch(r){case b:switch(a=a.type,a){case d:case f:case e:case m:case n:return a;default:switch(a=a&&a.$$typeof,a){case k:case h:case l:case q:case p:case g:return a;default:return r}}case c:return r}}}exports.ContextConsumer=h;exports.ContextProvider=g;exports.Element=b;exports.ForwardRef=l;exports.Fragment=d;exports.Lazy=q;exports.Memo=p;exports.Portal=c;exports.Profiler=f;exports.StrictMode=e;exports.Suspense=m;\nexports.SuspenseList=n;exports.isAsyncMode=function(){return!1};exports.isConcurrentMode=function(){return!1};exports.isContextConsumer=function(a){return v(a)===h};exports.isContextProvider=function(a){return v(a)===g};exports.isElement=function(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===b};exports.isForwardRef=function(a){return v(a)===l};exports.isFragment=function(a){return v(a)===d};exports.isLazy=function(a){return v(a)===q};exports.isMemo=function(a){return v(a)===p};\nexports.isPortal=function(a){return v(a)===c};exports.isProfiler=function(a){return v(a)===f};exports.isStrictMode=function(a){return v(a)===e};exports.isSuspense=function(a){return v(a)===m};exports.isSuspenseList=function(a){return v(a)===n};\nexports.isValidElementType=function(a){return\"string\"===typeof a||\"function\"===typeof a||a===d||a===f||a===e||a===m||a===n||a===t||\"object\"===typeof a&&null!==a&&(a.$$typeof===q||a.$$typeof===p||a.$$typeof===g||a.$$typeof===h||a.$$typeof===l||a.$$typeof===u||void 0!==a.getModuleId)?!0:!1};exports.typeOf=v;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-is.production.min.js');\n} else {\n module.exports = require('./cjs/react-is.development.js');\n}\n","import { getBatch } from './batch'; // encapsulates the subscription logic for connecting a component to the redux store, as\n// well as nesting subscriptions of descendant components, so that we can ensure the\n// ancestor components re-render before descendants\n\nfunction createListenerCollection() {\n const batch = getBatch();\n let first = null;\n let last = null;\n return {\n clear() {\n first = null;\n last = null;\n },\n\n notify() {\n batch(() => {\n let listener = first;\n\n while (listener) {\n listener.callback();\n listener = listener.next;\n }\n });\n },\n\n get() {\n let listeners = [];\n let listener = first;\n\n while (listener) {\n listeners.push(listener);\n listener = listener.next;\n }\n\n return listeners;\n },\n\n subscribe(callback) {\n let isSubscribed = true;\n let listener = last = {\n callback,\n next: null,\n prev: last\n };\n\n if (listener.prev) {\n listener.prev.next = listener;\n } else {\n first = listener;\n }\n\n return function unsubscribe() {\n if (!isSubscribed || first === null) return;\n isSubscribed = false;\n\n if (listener.next) {\n listener.next.prev = listener.prev;\n } else {\n last = listener.prev;\n }\n\n if (listener.prev) {\n listener.prev.next = listener.next;\n } else {\n first = listener.next;\n }\n };\n }\n\n };\n}\n\nconst nullListeners = {\n notify() {},\n\n get: () => []\n};\nexport function createSubscription(store, parentSub) {\n let unsubscribe;\n let listeners = nullListeners; // Reasons to keep the subscription active\n\n let subscriptionsAmount = 0; // Is this specific subscription subscribed (or only nested ones?)\n\n let selfSubscribed = false;\n\n function addNestedSub(listener) {\n trySubscribe();\n const cleanupListener = listeners.subscribe(listener); // cleanup nested sub\n\n let removed = false;\n return () => {\n if (!removed) {\n removed = true;\n cleanupListener();\n tryUnsubscribe();\n }\n };\n }\n\n function notifyNestedSubs() {\n listeners.notify();\n }\n\n function handleChangeWrapper() {\n if (subscription.onStateChange) {\n subscription.onStateChange();\n }\n }\n\n function isSubscribed() {\n return selfSubscribed;\n }\n\n function trySubscribe() {\n subscriptionsAmount++;\n\n if (!unsubscribe) {\n unsubscribe = parentSub ? parentSub.addNestedSub(handleChangeWrapper) : store.subscribe(handleChangeWrapper);\n listeners = createListenerCollection();\n }\n }\n\n function tryUnsubscribe() {\n subscriptionsAmount--;\n\n if (unsubscribe && subscriptionsAmount === 0) {\n unsubscribe();\n unsubscribe = undefined;\n listeners.clear();\n listeners = nullListeners;\n }\n }\n\n function trySubscribeSelf() {\n if (!selfSubscribed) {\n selfSubscribed = true;\n trySubscribe();\n }\n }\n\n function tryUnsubscribeSelf() {\n if (selfSubscribed) {\n selfSubscribed = false;\n tryUnsubscribe();\n }\n }\n\n const subscription = {\n addNestedSub,\n notifyNestedSubs,\n handleChangeWrapper,\n isSubscribed,\n trySubscribe: trySubscribeSelf,\n tryUnsubscribe: tryUnsubscribeSelf,\n getListeners: () => listeners\n };\n return subscription;\n}","import * as React from 'react'; // React currently throws a warning when using useLayoutEffect on the server.\n// To get around it, we can conditionally useEffect on the server (no-op) and\n// useLayoutEffect in the browser. We need useLayoutEffect to ensure the store\n// subscription callback always has the selector from the latest render commit\n// available, otherwise a store update may happen between render and the effect,\n// which may cause missed updates; we also must ensure the store subscription\n// is created synchronously, otherwise a store update may occur before the\n// subscription is created and an inconsistent state may be observed\n// Matches logic in React's `shared/ExecutionEnvironment` file\n\nexport const canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');\nexport const useIsomorphicLayoutEffect = canUseDOM ? React.useLayoutEffect : React.useEffect;","import * as React from 'react';\nimport { ReactReduxContext } from './Context';\nimport { createSubscription } from '../utils/Subscription';\nimport { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect';\n\nfunction Provider({\n store,\n context,\n children,\n serverState,\n stabilityCheck = 'once',\n noopCheck = 'once'\n}) {\n const contextValue = React.useMemo(() => {\n const subscription = createSubscription(store);\n return {\n store,\n subscription,\n getServerState: serverState ? () => serverState : undefined,\n stabilityCheck,\n noopCheck\n };\n }, [store, serverState, stabilityCheck, noopCheck]);\n const previousState = React.useMemo(() => store.getState(), [store]);\n useIsomorphicLayoutEffect(() => {\n const {\n subscription\n } = contextValue;\n subscription.onStateChange = subscription.notifyNestedSubs;\n subscription.trySubscribe();\n\n if (previousState !== store.getState()) {\n subscription.notifyNestedSubs();\n }\n\n return () => {\n subscription.tryUnsubscribe();\n subscription.onStateChange = undefined;\n };\n }, [contextValue, previousState]);\n const Context = context || ReactReduxContext; // @ts-ignore 'AnyAction' is assignable to the constraint of type 'A', but 'A' could be instantiated with a different subtype\n\n return /*#__PURE__*/React.createElement(Context.Provider, {\n value: contextValue\n }, children);\n}\n\nexport default Provider;","import { ReactReduxContext } from '../components/Context';\nimport { useReduxContext as useDefaultReduxContext, createReduxContextHook } from './useReduxContext';\n/**\r\n * Hook factory, which creates a `useStore` hook bound to a given context.\r\n *\r\n * @param {React.Context} [context=ReactReduxContext] Context passed to your ``.\r\n * @returns {Function} A `useStore` hook bound to the specified context.\r\n */\n\nexport function createStoreHook(context = ReactReduxContext) {\n const useReduxContext = // @ts-ignore\n context === ReactReduxContext ? useDefaultReduxContext : // @ts-ignore\n createReduxContextHook(context);\n return function useStore() {\n const {\n store\n } = useReduxContext(); // @ts-ignore\n\n return store;\n };\n}\n/**\r\n * A hook to access the redux store.\r\n *\r\n * @returns {any} the redux store\r\n *\r\n * @example\r\n *\r\n * import React from 'react'\r\n * import { useStore } from 'react-redux'\r\n *\r\n * export const ExampleComponent = () => {\r\n * const store = useStore()\r\n * return
{store.getState()}
\r\n * }\r\n */\n\nexport const useStore = /*#__PURE__*/createStoreHook();","import { ReactReduxContext } from '../components/Context';\nimport { useStore as useDefaultStore, createStoreHook } from './useStore';\n/**\r\n * Hook factory, which creates a `useDispatch` hook bound to a given context.\r\n *\r\n * @param {React.Context} [context=ReactReduxContext] Context passed to your ``.\r\n * @returns {Function} A `useDispatch` hook bound to the specified context.\r\n */\n\nexport function createDispatchHook(context = ReactReduxContext) {\n const useStore = // @ts-ignore\n context === ReactReduxContext ? useDefaultStore : createStoreHook(context);\n return function useDispatch() {\n const store = useStore(); // @ts-ignore\n\n return store.dispatch;\n };\n}\n/**\r\n * A hook to access the redux `dispatch` function.\r\n *\r\n * @returns {any|function} redux store's `dispatch` function\r\n *\r\n * @example\r\n *\r\n * import React, { useCallback } from 'react'\r\n * import { useDispatch } from 'react-redux'\r\n *\r\n * export const CounterComponent = ({ value }) => {\r\n * const dispatch = useDispatch()\r\n * const increaseCounter = useCallback(() => dispatch({ type: 'increase-counter' }), [])\r\n * return (\r\n *
\r\n * {value}\r\n * \r\n *
\r\n * )\r\n * }\r\n */\n\nexport const useDispatch = /*#__PURE__*/createDispatchHook();","// The primary entry point assumes we're working with standard ReactDOM/RN, but\n// older versions that do not include `useSyncExternalStore` (React 16.9 - 17.x).\n// Because of that, the useSyncExternalStore compat shim is needed.\nimport { useSyncExternalStore } from 'use-sync-external-store/shim';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';\nimport { unstable_batchedUpdates as batch } from './utils/reactBatchedUpdates';\nimport { setBatch } from './utils/batch';\nimport { initializeUseSelector } from './hooks/useSelector';\nimport { initializeConnect } from './components/connect';\ninitializeUseSelector(useSyncExternalStoreWithSelector);\ninitializeConnect(useSyncExternalStore); // Enable batched updates in our subscriptions for use\n// with standard React renderers (ReactDOM, React Native)\n\nsetBatch(batch);\nexport { batch };\nexport * from './exports';","// Cache implementation based on Erik Rasmussen's `lru-memoize`:\n// https://github.com/erikras/lru-memoize\nvar NOT_FOUND = 'NOT_FOUND';\n\nfunction createSingletonCache(equals) {\n var entry;\n return {\n get: function get(key) {\n if (entry && equals(entry.key, key)) {\n return entry.value;\n }\n\n return NOT_FOUND;\n },\n put: function put(key, value) {\n entry = {\n key: key,\n value: value\n };\n },\n getEntries: function getEntries() {\n return entry ? [entry] : [];\n },\n clear: function clear() {\n entry = undefined;\n }\n };\n}\n\nfunction createLruCache(maxSize, equals) {\n var entries = [];\n\n function get(key) {\n var cacheIndex = entries.findIndex(function (entry) {\n return equals(key, entry.key);\n }); // We found a cached entry\n\n if (cacheIndex > -1) {\n var entry = entries[cacheIndex]; // Cached entry not at top of cache, move it to the top\n\n if (cacheIndex > 0) {\n entries.splice(cacheIndex, 1);\n entries.unshift(entry);\n }\n\n return entry.value;\n } // No entry found in cache, return sentinel\n\n\n return NOT_FOUND;\n }\n\n function put(key, value) {\n if (get(key) === NOT_FOUND) {\n // TODO Is unshift slow?\n entries.unshift({\n key: key,\n value: value\n });\n\n if (entries.length > maxSize) {\n entries.pop();\n }\n }\n }\n\n function getEntries() {\n return entries;\n }\n\n function clear() {\n entries = [];\n }\n\n return {\n get: get,\n put: put,\n getEntries: getEntries,\n clear: clear\n };\n}\n\nexport var defaultEqualityCheck = function defaultEqualityCheck(a, b) {\n return a === b;\n};\nexport function createCacheKeyComparator(equalityCheck) {\n return function areArgumentsShallowlyEqual(prev, next) {\n if (prev === null || next === null || prev.length !== next.length) {\n return false;\n } // Do this in a for loop (and not a `forEach` or an `every`) so we can determine equality as fast as possible.\n\n\n var length = prev.length;\n\n for (var i = 0; i < length; i++) {\n if (!equalityCheck(prev[i], next[i])) {\n return false;\n }\n }\n\n return true;\n };\n}\n// defaultMemoize now supports a configurable cache size with LRU behavior,\n// and optional comparison of the result value with existing values\nexport function defaultMemoize(func, equalityCheckOrOptions) {\n var providedOptions = typeof equalityCheckOrOptions === 'object' ? equalityCheckOrOptions : {\n equalityCheck: equalityCheckOrOptions\n };\n var _providedOptions$equa = providedOptions.equalityCheck,\n equalityCheck = _providedOptions$equa === void 0 ? defaultEqualityCheck : _providedOptions$equa,\n _providedOptions$maxS = providedOptions.maxSize,\n maxSize = _providedOptions$maxS === void 0 ? 1 : _providedOptions$maxS,\n resultEqualityCheck = providedOptions.resultEqualityCheck;\n var comparator = createCacheKeyComparator(equalityCheck);\n var cache = maxSize === 1 ? createSingletonCache(comparator) : createLruCache(maxSize, comparator); // we reference arguments instead of spreading them for performance reasons\n\n function memoized() {\n var value = cache.get(arguments);\n\n if (value === NOT_FOUND) {\n // @ts-ignore\n value = func.apply(null, arguments);\n\n if (resultEqualityCheck) {\n var entries = cache.getEntries();\n var matchingEntry = entries.find(function (entry) {\n return resultEqualityCheck(entry.value, value);\n });\n\n if (matchingEntry) {\n value = matchingEntry.value;\n }\n }\n\n cache.put(arguments, value);\n }\n\n return value;\n }\n\n memoized.clearCache = function () {\n return cache.clear();\n };\n\n return memoized;\n}","import { defaultMemoize, defaultEqualityCheck } from './defaultMemoize';\nexport { defaultMemoize, defaultEqualityCheck };\n\nfunction getDependencies(funcs) {\n var dependencies = Array.isArray(funcs[0]) ? funcs[0] : funcs;\n\n if (!dependencies.every(function (dep) {\n return typeof dep === 'function';\n })) {\n var dependencyTypes = dependencies.map(function (dep) {\n return typeof dep === 'function' ? \"function \" + (dep.name || 'unnamed') + \"()\" : typeof dep;\n }).join(', ');\n throw new Error(\"createSelector expects all input-selectors to be functions, but received the following types: [\" + dependencyTypes + \"]\");\n }\n\n return dependencies;\n}\n\nexport function createSelectorCreator(memoize) {\n for (var _len = arguments.length, memoizeOptionsFromArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n memoizeOptionsFromArgs[_key - 1] = arguments[_key];\n }\n\n var createSelector = function createSelector() {\n for (var _len2 = arguments.length, funcs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n funcs[_key2] = arguments[_key2];\n }\n\n var _recomputations = 0;\n\n var _lastResult; // Due to the intricacies of rest params, we can't do an optional arg after `...funcs`.\n // So, start by declaring the default value here.\n // (And yes, the words 'memoize' and 'options' appear too many times in this next sequence.)\n\n\n var directlyPassedOptions = {\n memoizeOptions: undefined\n }; // Normally, the result func or \"output selector\" is the last arg\n\n var resultFunc = funcs.pop(); // If the result func is actually an _object_, assume it's our options object\n\n if (typeof resultFunc === 'object') {\n directlyPassedOptions = resultFunc; // and pop the real result func off\n\n resultFunc = funcs.pop();\n }\n\n if (typeof resultFunc !== 'function') {\n throw new Error(\"createSelector expects an output function after the inputs, but received: [\" + typeof resultFunc + \"]\");\n } // Determine which set of options we're using. Prefer options passed directly,\n // but fall back to options given to createSelectorCreator.\n\n\n var _directlyPassedOption = directlyPassedOptions,\n _directlyPassedOption2 = _directlyPassedOption.memoizeOptions,\n memoizeOptions = _directlyPassedOption2 === void 0 ? memoizeOptionsFromArgs : _directlyPassedOption2; // Simplifying assumption: it's unlikely that the first options arg of the provided memoizer\n // is an array. In most libs I've looked at, it's an equality function or options object.\n // Based on that, if `memoizeOptions` _is_ an array, we assume it's a full\n // user-provided array of options. Otherwise, it must be just the _first_ arg, and so\n // we wrap it in an array so we can apply it.\n\n var finalMemoizeOptions = Array.isArray(memoizeOptions) ? memoizeOptions : [memoizeOptions];\n var dependencies = getDependencies(funcs);\n var memoizedResultFunc = memoize.apply(void 0, [function recomputationWrapper() {\n _recomputations++; // apply arguments instead of spreading for performance.\n\n return resultFunc.apply(null, arguments);\n }].concat(finalMemoizeOptions)); // If a selector is called with the exact same arguments we don't need to traverse our dependencies again.\n\n var selector = memoize(function dependenciesChecker() {\n var params = [];\n var length = dependencies.length;\n\n for (var i = 0; i < length; i++) {\n // apply arguments instead of spreading and mutate a local list of params for performance.\n // @ts-ignore\n params.push(dependencies[i].apply(null, arguments));\n } // apply arguments instead of spreading for performance.\n\n\n _lastResult = memoizedResultFunc.apply(null, params);\n return _lastResult;\n });\n Object.assign(selector, {\n resultFunc: resultFunc,\n memoizedResultFunc: memoizedResultFunc,\n dependencies: dependencies,\n lastResult: function lastResult() {\n return _lastResult;\n },\n recomputations: function recomputations() {\n return _recomputations;\n },\n resetRecomputations: function resetRecomputations() {\n return _recomputations = 0;\n }\n });\n return selector;\n }; // @ts-ignore\n\n\n return createSelector;\n}\nexport var createSelector = /* #__PURE__ */createSelectorCreator(defaultMemoize);\n// Manual definition of state and output arguments\nexport var createStructuredSelector = function createStructuredSelector(selectors, selectorCreator) {\n if (selectorCreator === void 0) {\n selectorCreator = createSelector;\n }\n\n if (typeof selectors !== 'object') {\n throw new Error('createStructuredSelector expects first argument to be an object ' + (\"where each property is a selector, instead received a \" + typeof selectors));\n }\n\n var objectKeys = Object.keys(selectors);\n var resultSelector = selectorCreator( // @ts-ignore\n objectKeys.map(function (key) {\n return selectors[key];\n }), function () {\n for (var _len3 = arguments.length, values = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n values[_key3] = arguments[_key3];\n }\n\n return values.reduce(function (composition, value, index) {\n composition[objectKeys[index]] = value;\n return composition;\n }, {});\n });\n return resultSelector;\n};","// src/utils/env.ts\nvar NOTHING = Symbol.for(\"immer-nothing\");\nvar DRAFTABLE = Symbol.for(\"immer-draftable\");\nvar DRAFT_STATE = Symbol.for(\"immer-state\");\n\n// src/utils/errors.ts\nvar errors = process.env.NODE_ENV !== \"production\" ? [\n // All error codes, starting by 0:\n function(plugin) {\n return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`;\n },\n function(thing) {\n return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`;\n },\n \"This object has been frozen and should not be mutated\",\n function(data) {\n return \"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" + data;\n },\n \"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n \"Immer forbids circular references\",\n \"The first or second argument to `produce` must be a function\",\n \"The third argument to `produce` must be a function or undefined\",\n \"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n \"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n function(thing) {\n return `'current' expects a draft, got: ${thing}`;\n },\n \"Object.defineProperty() cannot be used on an Immer draft\",\n \"Object.setPrototypeOf() cannot be used on an Immer draft\",\n \"Immer only supports deleting array indices\",\n \"Immer only supports setting array indices and the 'length' property\",\n function(thing) {\n return `'original' expects a draft, got: ${thing}`;\n }\n // Note: if more errors are added, the errorOffset in Patches.ts should be increased\n // See Patches.ts for additional errors\n] : [];\nfunction die(error, ...args) {\n if (process.env.NODE_ENV !== \"production\") {\n const e = errors[error];\n const msg = typeof e === \"function\" ? e.apply(null, args) : e;\n throw new Error(`[Immer] ${msg}`);\n }\n throw new Error(\n `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`\n );\n}\n\n// src/utils/common.ts\nvar getPrototypeOf = Object.getPrototypeOf;\nfunction isDraft(value) {\n return !!value && !!value[DRAFT_STATE];\n}\nfunction isDraftable(value) {\n if (!value)\n return false;\n return isPlainObject(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor?.[DRAFTABLE] || isMap(value) || isSet(value);\n}\nvar objectCtorString = Object.prototype.constructor.toString();\nfunction isPlainObject(value) {\n if (!value || typeof value !== \"object\")\n return false;\n const proto = getPrototypeOf(value);\n if (proto === null) {\n return true;\n }\n const Ctor = Object.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n if (Ctor === Object)\n return true;\n return typeof Ctor == \"function\" && Function.toString.call(Ctor) === objectCtorString;\n}\nfunction original(value) {\n if (!isDraft(value))\n die(15, value);\n return value[DRAFT_STATE].base_;\n}\nfunction each(obj, iter) {\n if (getArchtype(obj) === 0 /* Object */) {\n Object.entries(obj).forEach(([key, value]) => {\n iter(key, value, obj);\n });\n } else {\n obj.forEach((entry, index) => iter(index, entry, obj));\n }\n}\nfunction getArchtype(thing) {\n const state = thing[DRAFT_STATE];\n return state ? state.type_ : Array.isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;\n}\nfunction has(thing, prop) {\n return getArchtype(thing) === 2 /* Map */ ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);\n}\nfunction get(thing, prop) {\n return getArchtype(thing) === 2 /* Map */ ? thing.get(prop) : thing[prop];\n}\nfunction set(thing, propOrOldValue, value) {\n const t = getArchtype(thing);\n if (t === 2 /* Map */)\n thing.set(propOrOldValue, value);\n else if (t === 3 /* Set */) {\n thing.add(value);\n } else\n thing[propOrOldValue] = value;\n}\nfunction is(x, y) {\n if (x === y) {\n return x !== 0 || 1 / x === 1 / y;\n } else {\n return x !== x && y !== y;\n }\n}\nfunction isMap(target) {\n return target instanceof Map;\n}\nfunction isSet(target) {\n return target instanceof Set;\n}\nfunction latest(state) {\n return state.copy_ || state.base_;\n}\nfunction shallowCopy(base, strict) {\n if (isMap(base)) {\n return new Map(base);\n }\n if (isSet(base)) {\n return new Set(base);\n }\n if (Array.isArray(base))\n return Array.prototype.slice.call(base);\n if (!strict && isPlainObject(base)) {\n if (!getPrototypeOf(base)) {\n const obj = /* @__PURE__ */ Object.create(null);\n return Object.assign(obj, base);\n }\n return { ...base };\n }\n const descriptors = Object.getOwnPropertyDescriptors(base);\n delete descriptors[DRAFT_STATE];\n let keys = Reflect.ownKeys(descriptors);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n const desc = descriptors[key];\n if (desc.writable === false) {\n desc.writable = true;\n desc.configurable = true;\n }\n if (desc.get || desc.set)\n descriptors[key] = {\n configurable: true,\n writable: true,\n // could live with !!desc.set as well here...\n enumerable: desc.enumerable,\n value: base[key]\n };\n }\n return Object.create(getPrototypeOf(base), descriptors);\n}\nfunction freeze(obj, deep = false) {\n if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))\n return obj;\n if (getArchtype(obj) > 1) {\n obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;\n }\n Object.freeze(obj);\n if (deep)\n each(obj, (_key, value) => freeze(value, true), true);\n return obj;\n}\nfunction dontMutateFrozenCollections() {\n die(2);\n}\nfunction isFrozen(obj) {\n return Object.isFrozen(obj);\n}\n\n// src/utils/plugins.ts\nvar plugins = {};\nfunction getPlugin(pluginKey) {\n const plugin = plugins[pluginKey];\n if (!plugin) {\n die(0, pluginKey);\n }\n return plugin;\n}\nfunction loadPlugin(pluginKey, implementation) {\n if (!plugins[pluginKey])\n plugins[pluginKey] = implementation;\n}\n\n// src/core/scope.ts\nvar currentScope;\nfunction getCurrentScope() {\n return currentScope;\n}\nfunction createScope(parent_, immer_) {\n return {\n drafts_: [],\n parent_,\n immer_,\n // Whenever the modified draft contains a draft from another scope, we\n // need to prevent auto-freezing so the unowned draft can be finalized.\n canAutoFreeze_: true,\n unfinalizedDrafts_: 0\n };\n}\nfunction usePatchesInScope(scope, patchListener) {\n if (patchListener) {\n getPlugin(\"Patches\");\n scope.patches_ = [];\n scope.inversePatches_ = [];\n scope.patchListener_ = patchListener;\n }\n}\nfunction revokeScope(scope) {\n leaveScope(scope);\n scope.drafts_.forEach(revokeDraft);\n scope.drafts_ = null;\n}\nfunction leaveScope(scope) {\n if (scope === currentScope) {\n currentScope = scope.parent_;\n }\n}\nfunction enterScope(immer2) {\n return currentScope = createScope(currentScope, immer2);\n}\nfunction revokeDraft(draft) {\n const state = draft[DRAFT_STATE];\n if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */)\n state.revoke_();\n else\n state.revoked_ = true;\n}\n\n// src/core/finalize.ts\nfunction processResult(result, scope) {\n scope.unfinalizedDrafts_ = scope.drafts_.length;\n const baseDraft = scope.drafts_[0];\n const isReplaced = result !== void 0 && result !== baseDraft;\n if (isReplaced) {\n if (baseDraft[DRAFT_STATE].modified_) {\n revokeScope(scope);\n die(4);\n }\n if (isDraftable(result)) {\n result = finalize(scope, result);\n if (!scope.parent_)\n maybeFreeze(scope, result);\n }\n if (scope.patches_) {\n getPlugin(\"Patches\").generateReplacementPatches_(\n baseDraft[DRAFT_STATE].base_,\n result,\n scope.patches_,\n scope.inversePatches_\n );\n }\n } else {\n result = finalize(scope, baseDraft, []);\n }\n revokeScope(scope);\n if (scope.patches_) {\n scope.patchListener_(scope.patches_, scope.inversePatches_);\n }\n return result !== NOTHING ? result : void 0;\n}\nfunction finalize(rootScope, value, path) {\n if (isFrozen(value))\n return value;\n const state = value[DRAFT_STATE];\n if (!state) {\n each(\n value,\n (key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path),\n true\n // See #590, don't recurse into non-enumerable of non drafted objects\n );\n return value;\n }\n if (state.scope_ !== rootScope)\n return value;\n if (!state.modified_) {\n maybeFreeze(rootScope, state.base_, true);\n return state.base_;\n }\n if (!state.finalized_) {\n state.finalized_ = true;\n state.scope_.unfinalizedDrafts_--;\n const result = state.copy_;\n let resultEach = result;\n let isSet2 = false;\n if (state.type_ === 3 /* Set */) {\n resultEach = new Set(result);\n result.clear();\n isSet2 = true;\n }\n each(\n resultEach,\n (key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path, isSet2)\n );\n maybeFreeze(rootScope, result, false);\n if (path && rootScope.patches_) {\n getPlugin(\"Patches\").generatePatches_(\n state,\n path,\n rootScope.patches_,\n rootScope.inversePatches_\n );\n }\n }\n return state.copy_;\n}\nfunction finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) {\n if (process.env.NODE_ENV !== \"production\" && childValue === targetObject)\n die(5);\n if (isDraft(childValue)) {\n const path = rootPath && parentState && parentState.type_ !== 3 /* Set */ && // Set objects are atomic since they have no keys.\n !has(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0;\n const res = finalize(rootScope, childValue, path);\n set(targetObject, prop, res);\n if (isDraft(res)) {\n rootScope.canAutoFreeze_ = false;\n } else\n return;\n } else if (targetIsSet) {\n targetObject.add(childValue);\n }\n if (isDraftable(childValue) && !isFrozen(childValue)) {\n if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n return;\n }\n finalize(rootScope, childValue);\n if (!parentState || !parentState.scope_.parent_)\n maybeFreeze(rootScope, childValue);\n }\n}\nfunction maybeFreeze(scope, value, deep = false) {\n if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n freeze(value, deep);\n }\n}\n\n// src/core/proxy.ts\nfunction createProxyProxy(base, parent) {\n const isArray = Array.isArray(base);\n const state = {\n type_: isArray ? 1 /* Array */ : 0 /* Object */,\n // Track which produce call this is associated with.\n scope_: parent ? parent.scope_ : getCurrentScope(),\n // True for both shallow and deep changes.\n modified_: false,\n // Used during finalization.\n finalized_: false,\n // Track which properties have been assigned (true) or deleted (false).\n assigned_: {},\n // The parent draft state.\n parent_: parent,\n // The base state.\n base_: base,\n // The base proxy.\n draft_: null,\n // set below\n // The base copy with any updated values.\n copy_: null,\n // Called by the `produce` function.\n revoke_: null,\n isManual_: false\n };\n let target = state;\n let traps = objectTraps;\n if (isArray) {\n target = [state];\n traps = arrayTraps;\n }\n const { revoke, proxy } = Proxy.revocable(target, traps);\n state.draft_ = proxy;\n state.revoke_ = revoke;\n return proxy;\n}\nvar objectTraps = {\n get(state, prop) {\n if (prop === DRAFT_STATE)\n return state;\n const source = latest(state);\n if (!has(source, prop)) {\n return readPropFromProto(state, source, prop);\n }\n const value = source[prop];\n if (state.finalized_ || !isDraftable(value)) {\n return value;\n }\n if (value === peek(state.base_, prop)) {\n prepareCopy(state);\n return state.copy_[prop] = createProxy(value, state);\n }\n return value;\n },\n has(state, prop) {\n return prop in latest(state);\n },\n ownKeys(state) {\n return Reflect.ownKeys(latest(state));\n },\n set(state, prop, value) {\n const desc = getDescriptorFromProto(latest(state), prop);\n if (desc?.set) {\n desc.set.call(state.draft_, value);\n return true;\n }\n if (!state.modified_) {\n const current2 = peek(latest(state), prop);\n const currentState = current2?.[DRAFT_STATE];\n if (currentState && currentState.base_ === value) {\n state.copy_[prop] = value;\n state.assigned_[prop] = false;\n return true;\n }\n if (is(value, current2) && (value !== void 0 || has(state.base_, prop)))\n return true;\n prepareCopy(state);\n markChanged(state);\n }\n if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'\n (value !== void 0 || prop in state.copy_) || // special case: NaN\n Number.isNaN(value) && Number.isNaN(state.copy_[prop]))\n return true;\n state.copy_[prop] = value;\n state.assigned_[prop] = true;\n return true;\n },\n deleteProperty(state, prop) {\n if (peek(state.base_, prop) !== void 0 || prop in state.base_) {\n state.assigned_[prop] = false;\n prepareCopy(state);\n markChanged(state);\n } else {\n delete state.assigned_[prop];\n }\n if (state.copy_) {\n delete state.copy_[prop];\n }\n return true;\n },\n // Note: We never coerce `desc.value` into an Immer draft, because we can't make\n // the same guarantee in ES5 mode.\n getOwnPropertyDescriptor(state, prop) {\n const owner = latest(state);\n const desc = Reflect.getOwnPropertyDescriptor(owner, prop);\n if (!desc)\n return desc;\n return {\n writable: true,\n configurable: state.type_ !== 1 /* Array */ || prop !== \"length\",\n enumerable: desc.enumerable,\n value: owner[prop]\n };\n },\n defineProperty() {\n die(11);\n },\n getPrototypeOf(state) {\n return getPrototypeOf(state.base_);\n },\n setPrototypeOf() {\n die(12);\n }\n};\nvar arrayTraps = {};\neach(objectTraps, (key, fn) => {\n arrayTraps[key] = function() {\n arguments[0] = arguments[0][0];\n return fn.apply(this, arguments);\n };\n});\narrayTraps.deleteProperty = function(state, prop) {\n if (process.env.NODE_ENV !== \"production\" && isNaN(parseInt(prop)))\n die(13);\n return arrayTraps.set.call(this, state, prop, void 0);\n};\narrayTraps.set = function(state, prop, value) {\n if (process.env.NODE_ENV !== \"production\" && prop !== \"length\" && isNaN(parseInt(prop)))\n die(14);\n return objectTraps.set.call(this, state[0], prop, value, state[0]);\n};\nfunction peek(draft, prop) {\n const state = draft[DRAFT_STATE];\n const source = state ? latest(state) : draft;\n return source[prop];\n}\nfunction readPropFromProto(state, source, prop) {\n const desc = getDescriptorFromProto(source, prop);\n return desc ? `value` in desc ? desc.value : (\n // This is a very special case, if the prop is a getter defined by the\n // prototype, we should invoke it with the draft as context!\n desc.get?.call(state.draft_)\n ) : void 0;\n}\nfunction getDescriptorFromProto(source, prop) {\n if (!(prop in source))\n return void 0;\n let proto = getPrototypeOf(source);\n while (proto) {\n const desc = Object.getOwnPropertyDescriptor(proto, prop);\n if (desc)\n return desc;\n proto = getPrototypeOf(proto);\n }\n return void 0;\n}\nfunction markChanged(state) {\n if (!state.modified_) {\n state.modified_ = true;\n if (state.parent_) {\n markChanged(state.parent_);\n }\n }\n}\nfunction prepareCopy(state) {\n if (!state.copy_) {\n state.copy_ = shallowCopy(\n state.base_,\n state.scope_.immer_.useStrictShallowCopy_\n );\n }\n}\n\n// src/core/immerClass.ts\nvar Immer2 = class {\n constructor(config) {\n this.autoFreeze_ = true;\n this.useStrictShallowCopy_ = false;\n /**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\n this.produce = (base, recipe, patchListener) => {\n if (typeof base === \"function\" && typeof recipe !== \"function\") {\n const defaultBase = recipe;\n recipe = base;\n const self = this;\n return function curriedProduce(base2 = defaultBase, ...args) {\n return self.produce(base2, (draft) => recipe.call(this, draft, ...args));\n };\n }\n if (typeof recipe !== \"function\")\n die(6);\n if (patchListener !== void 0 && typeof patchListener !== \"function\")\n die(7);\n let result;\n if (isDraftable(base)) {\n const scope = enterScope(this);\n const proxy = createProxy(base, void 0);\n let hasError = true;\n try {\n result = recipe(proxy);\n hasError = false;\n } finally {\n if (hasError)\n revokeScope(scope);\n else\n leaveScope(scope);\n }\n usePatchesInScope(scope, patchListener);\n return processResult(result, scope);\n } else if (!base || typeof base !== \"object\") {\n result = recipe(base);\n if (result === void 0)\n result = base;\n if (result === NOTHING)\n result = void 0;\n if (this.autoFreeze_)\n freeze(result, true);\n if (patchListener) {\n const p = [];\n const ip = [];\n getPlugin(\"Patches\").generateReplacementPatches_(base, result, p, ip);\n patchListener(p, ip);\n }\n return result;\n } else\n die(1, base);\n };\n this.produceWithPatches = (base, recipe) => {\n if (typeof base === \"function\") {\n return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));\n }\n let patches, inversePatches;\n const result = this.produce(base, recipe, (p, ip) => {\n patches = p;\n inversePatches = ip;\n });\n return [result, patches, inversePatches];\n };\n if (typeof config?.autoFreeze === \"boolean\")\n this.setAutoFreeze(config.autoFreeze);\n if (typeof config?.useStrictShallowCopy === \"boolean\")\n this.setUseStrictShallowCopy(config.useStrictShallowCopy);\n }\n createDraft(base) {\n if (!isDraftable(base))\n die(8);\n if (isDraft(base))\n base = current(base);\n const scope = enterScope(this);\n const proxy = createProxy(base, void 0);\n proxy[DRAFT_STATE].isManual_ = true;\n leaveScope(scope);\n return proxy;\n }\n finishDraft(draft, patchListener) {\n const state = draft && draft[DRAFT_STATE];\n if (!state || !state.isManual_)\n die(9);\n const { scope_: scope } = state;\n usePatchesInScope(scope, patchListener);\n return processResult(void 0, scope);\n }\n /**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * By default, auto-freezing is enabled.\n */\n setAutoFreeze(value) {\n this.autoFreeze_ = value;\n }\n /**\n * Pass true to enable strict shallow copy.\n *\n * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n */\n setUseStrictShallowCopy(value) {\n this.useStrictShallowCopy_ = value;\n }\n applyPatches(base, patches) {\n let i;\n for (i = patches.length - 1; i >= 0; i--) {\n const patch = patches[i];\n if (patch.path.length === 0 && patch.op === \"replace\") {\n base = patch.value;\n break;\n }\n }\n if (i > -1) {\n patches = patches.slice(i + 1);\n }\n const applyPatchesImpl = getPlugin(\"Patches\").applyPatches_;\n if (isDraft(base)) {\n return applyPatchesImpl(base, patches);\n }\n return this.produce(\n base,\n (draft) => applyPatchesImpl(draft, patches)\n );\n }\n};\nfunction createProxy(value, parent) {\n const draft = isMap(value) ? getPlugin(\"MapSet\").proxyMap_(value, parent) : isSet(value) ? getPlugin(\"MapSet\").proxySet_(value, parent) : createProxyProxy(value, parent);\n const scope = parent ? parent.scope_ : getCurrentScope();\n scope.drafts_.push(draft);\n return draft;\n}\n\n// src/core/current.ts\nfunction current(value) {\n if (!isDraft(value))\n die(10, value);\n return currentImpl(value);\n}\nfunction currentImpl(value) {\n if (!isDraftable(value) || isFrozen(value))\n return value;\n const state = value[DRAFT_STATE];\n let copy;\n if (state) {\n if (!state.modified_)\n return state.base_;\n state.finalized_ = true;\n copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);\n } else {\n copy = shallowCopy(value, true);\n }\n each(copy, (key, childValue) => {\n set(copy, key, currentImpl(childValue));\n });\n if (state) {\n state.finalized_ = false;\n }\n return copy;\n}\n\n// src/plugins/patches.ts\nfunction enablePatches() {\n const errorOffset = 16;\n if (process.env.NODE_ENV !== \"production\") {\n errors.push(\n 'Sets cannot have \"replace\" patches.',\n function(op) {\n return \"Unsupported patch operation: \" + op;\n },\n function(path) {\n return \"Cannot apply patch, path doesn't resolve: \" + path;\n },\n \"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n );\n }\n const REPLACE = \"replace\";\n const ADD = \"add\";\n const REMOVE = \"remove\";\n function generatePatches_(state, basePath, patches, inversePatches) {\n switch (state.type_) {\n case 0 /* Object */:\n case 2 /* Map */:\n return generatePatchesFromAssigned(\n state,\n basePath,\n patches,\n inversePatches\n );\n case 1 /* Array */:\n return generateArrayPatches(state, basePath, patches, inversePatches);\n case 3 /* Set */:\n return generateSetPatches(\n state,\n basePath,\n patches,\n inversePatches\n );\n }\n }\n function generateArrayPatches(state, basePath, patches, inversePatches) {\n let { base_, assigned_ } = state;\n let copy_ = state.copy_;\n if (copy_.length < base_.length) {\n ;\n [base_, copy_] = [copy_, base_];\n [patches, inversePatches] = [inversePatches, patches];\n }\n for (let i = 0; i < base_.length; i++) {\n if (assigned_[i] && copy_[i] !== base_[i]) {\n const path = basePath.concat([i]);\n patches.push({\n op: REPLACE,\n path,\n // Need to maybe clone it, as it can in fact be the original value\n // due to the base/copy inversion at the start of this function\n value: clonePatchValueIfNeeded(copy_[i])\n });\n inversePatches.push({\n op: REPLACE,\n path,\n value: clonePatchValueIfNeeded(base_[i])\n });\n }\n }\n for (let i = base_.length; i < copy_.length; i++) {\n const path = basePath.concat([i]);\n patches.push({\n op: ADD,\n path,\n // Need to maybe clone it, as it can in fact be the original value\n // due to the base/copy inversion at the start of this function\n value: clonePatchValueIfNeeded(copy_[i])\n });\n }\n for (let i = copy_.length - 1; base_.length <= i; --i) {\n const path = basePath.concat([i]);\n inversePatches.push({\n op: REMOVE,\n path\n });\n }\n }\n function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {\n const { base_, copy_ } = state;\n each(state.assigned_, (key, assignedValue) => {\n const origValue = get(base_, key);\n const value = get(copy_, key);\n const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;\n if (origValue === value && op === REPLACE)\n return;\n const path = basePath.concat(key);\n patches.push(op === REMOVE ? { op, path } : { op, path, value });\n inversePatches.push(\n op === ADD ? { op: REMOVE, path } : op === REMOVE ? { op: ADD, path, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path, value: clonePatchValueIfNeeded(origValue) }\n );\n });\n }\n function generateSetPatches(state, basePath, patches, inversePatches) {\n let { base_, copy_ } = state;\n let i = 0;\n base_.forEach((value) => {\n if (!copy_.has(value)) {\n const path = basePath.concat([i]);\n patches.push({\n op: REMOVE,\n path,\n value\n });\n inversePatches.unshift({\n op: ADD,\n path,\n value\n });\n }\n i++;\n });\n i = 0;\n copy_.forEach((value) => {\n if (!base_.has(value)) {\n const path = basePath.concat([i]);\n patches.push({\n op: ADD,\n path,\n value\n });\n inversePatches.unshift({\n op: REMOVE,\n path,\n value\n });\n }\n i++;\n });\n }\n function generateReplacementPatches_(baseValue, replacement, patches, inversePatches) {\n patches.push({\n op: REPLACE,\n path: [],\n value: replacement === NOTHING ? void 0 : replacement\n });\n inversePatches.push({\n op: REPLACE,\n path: [],\n value: baseValue\n });\n }\n function applyPatches_(draft, patches) {\n patches.forEach((patch) => {\n const { path, op } = patch;\n let base = draft;\n for (let i = 0; i < path.length - 1; i++) {\n const parentType = getArchtype(base);\n let p = path[i];\n if (typeof p !== \"string\" && typeof p !== \"number\") {\n p = \"\" + p;\n }\n if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === \"__proto__\" || p === \"constructor\"))\n die(errorOffset + 3);\n if (typeof base === \"function\" && p === \"prototype\")\n die(errorOffset + 3);\n base = get(base, p);\n if (typeof base !== \"object\")\n die(errorOffset + 2, path.join(\"/\"));\n }\n const type = getArchtype(base);\n const value = deepClonePatchValue(patch.value);\n const key = path[path.length - 1];\n switch (op) {\n case REPLACE:\n switch (type) {\n case 2 /* Map */:\n return base.set(key, value);\n case 3 /* Set */:\n die(errorOffset);\n default:\n return base[key] = value;\n }\n case ADD:\n switch (type) {\n case 1 /* Array */:\n return key === \"-\" ? base.push(value) : base.splice(key, 0, value);\n case 2 /* Map */:\n return base.set(key, value);\n case 3 /* Set */:\n return base.add(value);\n default:\n return base[key] = value;\n }\n case REMOVE:\n switch (type) {\n case 1 /* Array */:\n return base.splice(key, 1);\n case 2 /* Map */:\n return base.delete(key);\n case 3 /* Set */:\n return base.delete(patch.value);\n default:\n return delete base[key];\n }\n default:\n die(errorOffset + 1, op);\n }\n });\n return draft;\n }\n function deepClonePatchValue(obj) {\n if (!isDraftable(obj))\n return obj;\n if (Array.isArray(obj))\n return obj.map(deepClonePatchValue);\n if (isMap(obj))\n return new Map(\n Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n );\n if (isSet(obj))\n return new Set(Array.from(obj).map(deepClonePatchValue));\n const cloned = Object.create(getPrototypeOf(obj));\n for (const key in obj)\n cloned[key] = deepClonePatchValue(obj[key]);\n if (has(obj, DRAFTABLE))\n cloned[DRAFTABLE] = obj[DRAFTABLE];\n return cloned;\n }\n function clonePatchValueIfNeeded(obj) {\n if (isDraft(obj)) {\n return deepClonePatchValue(obj);\n } else\n return obj;\n }\n loadPlugin(\"Patches\", {\n applyPatches_,\n generatePatches_,\n generateReplacementPatches_\n });\n}\n\n// src/plugins/mapset.ts\nfunction enableMapSet() {\n class DraftMap extends Map {\n constructor(target, parent) {\n super();\n this[DRAFT_STATE] = {\n type_: 2 /* Map */,\n parent_: parent,\n scope_: parent ? parent.scope_ : getCurrentScope(),\n modified_: false,\n finalized_: false,\n copy_: void 0,\n assigned_: void 0,\n base_: target,\n draft_: this,\n isManual_: false,\n revoked_: false\n };\n }\n get size() {\n return latest(this[DRAFT_STATE]).size;\n }\n has(key) {\n return latest(this[DRAFT_STATE]).has(key);\n }\n set(key, value) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (!latest(state).has(key) || latest(state).get(key) !== value) {\n prepareMapCopy(state);\n markChanged(state);\n state.assigned_.set(key, true);\n state.copy_.set(key, value);\n state.assigned_.set(key, true);\n }\n return this;\n }\n delete(key) {\n if (!this.has(key)) {\n return false;\n }\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareMapCopy(state);\n markChanged(state);\n if (state.base_.has(key)) {\n state.assigned_.set(key, false);\n } else {\n state.assigned_.delete(key);\n }\n state.copy_.delete(key);\n return true;\n }\n clear() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (latest(state).size) {\n prepareMapCopy(state);\n markChanged(state);\n state.assigned_ = /* @__PURE__ */ new Map();\n each(state.base_, (key) => {\n state.assigned_.set(key, false);\n });\n state.copy_.clear();\n }\n }\n forEach(cb, thisArg) {\n const state = this[DRAFT_STATE];\n latest(state).forEach((_value, key, _map) => {\n cb.call(thisArg, this.get(key), key, this);\n });\n }\n get(key) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n const value = latest(state).get(key);\n if (state.finalized_ || !isDraftable(value)) {\n return value;\n }\n if (value !== state.base_.get(key)) {\n return value;\n }\n const draft = createProxy(value, state);\n prepareMapCopy(state);\n state.copy_.set(key, draft);\n return draft;\n }\n keys() {\n return latest(this[DRAFT_STATE]).keys();\n }\n values() {\n const iterator = this.keys();\n return {\n [Symbol.iterator]: () => this.values(),\n next: () => {\n const r = iterator.next();\n if (r.done)\n return r;\n const value = this.get(r.value);\n return {\n done: false,\n value\n };\n }\n };\n }\n entries() {\n const iterator = this.keys();\n return {\n [Symbol.iterator]: () => this.entries(),\n next: () => {\n const r = iterator.next();\n if (r.done)\n return r;\n const value = this.get(r.value);\n return {\n done: false,\n value: [r.value, value]\n };\n }\n };\n }\n [(DRAFT_STATE, Symbol.iterator)]() {\n return this.entries();\n }\n }\n function proxyMap_(target, parent) {\n return new DraftMap(target, parent);\n }\n function prepareMapCopy(state) {\n if (!state.copy_) {\n state.assigned_ = /* @__PURE__ */ new Map();\n state.copy_ = new Map(state.base_);\n }\n }\n class DraftSet extends Set {\n constructor(target, parent) {\n super();\n this[DRAFT_STATE] = {\n type_: 3 /* Set */,\n parent_: parent,\n scope_: parent ? parent.scope_ : getCurrentScope(),\n modified_: false,\n finalized_: false,\n copy_: void 0,\n base_: target,\n draft_: this,\n drafts_: /* @__PURE__ */ new Map(),\n revoked_: false,\n isManual_: false\n };\n }\n get size() {\n return latest(this[DRAFT_STATE]).size;\n }\n has(value) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (!state.copy_) {\n return state.base_.has(value);\n }\n if (state.copy_.has(value))\n return true;\n if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n return true;\n return false;\n }\n add(value) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (!this.has(value)) {\n prepareSetCopy(state);\n markChanged(state);\n state.copy_.add(value);\n }\n return this;\n }\n delete(value) {\n if (!this.has(value)) {\n return false;\n }\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareSetCopy(state);\n markChanged(state);\n return state.copy_.delete(value) || (state.drafts_.has(value) ? state.copy_.delete(state.drafts_.get(value)) : (\n /* istanbul ignore next */\n false\n ));\n }\n clear() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (latest(state).size) {\n prepareSetCopy(state);\n markChanged(state);\n state.copy_.clear();\n }\n }\n values() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareSetCopy(state);\n return state.copy_.values();\n }\n entries() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareSetCopy(state);\n return state.copy_.entries();\n }\n keys() {\n return this.values();\n }\n [(DRAFT_STATE, Symbol.iterator)]() {\n return this.values();\n }\n forEach(cb, thisArg) {\n const iterator = this.values();\n let result = iterator.next();\n while (!result.done) {\n cb.call(thisArg, result.value, result.value, this);\n result = iterator.next();\n }\n }\n }\n function proxySet_(target, parent) {\n return new DraftSet(target, parent);\n }\n function prepareSetCopy(state) {\n if (!state.copy_) {\n state.copy_ = /* @__PURE__ */ new Set();\n state.base_.forEach((value) => {\n if (isDraftable(value)) {\n const draft = createProxy(value, state);\n state.drafts_.set(value, draft);\n state.copy_.add(draft);\n } else {\n state.copy_.add(value);\n }\n });\n }\n }\n function assertUnrevoked(state) {\n if (state.revoked_)\n die(3, JSON.stringify(latest(state)));\n }\n loadPlugin(\"MapSet\", { proxyMap_, proxySet_ });\n}\n\n// src/immer.ts\nvar immer = new Immer2();\nvar produce = immer.produce;\nvar produceWithPatches = immer.produceWithPatches.bind(\n immer\n);\nvar setAutoFreeze = immer.setAutoFreeze.bind(immer);\nvar setUseStrictShallowCopy = immer.setUseStrictShallowCopy.bind(immer);\nvar applyPatches = immer.applyPatches.bind(immer);\nvar createDraft = immer.createDraft.bind(immer);\nvar finishDraft = immer.finishDraft.bind(immer);\nfunction castDraft(value) {\n return value;\n}\nfunction castImmutable(value) {\n return value;\n}\nexport {\n Immer2 as Immer,\n applyPatches,\n castDraft,\n castImmutable,\n createDraft,\n current,\n enableMapSet,\n enablePatches,\n finishDraft,\n freeze,\n DRAFTABLE as immerable,\n isDraft,\n isDraftable,\n NOTHING as nothing,\n original,\n produce,\n produceWithPatches,\n setAutoFreeze,\n setUseStrictShallowCopy\n};\n//# sourceMappingURL=immer.mjs.map","import { call, Err, Ok } from \"../deps.js\";\n/**\n * The goal of `safe` is to wrap Operations to prevent them from raising\n * and error. The result of `safe` is always a {@link Result} type.\n *\n * @example\n * ```ts\n * import { safe } from \"starfx\";\n *\n * function* run() {\n * const results = yield* safe(fetch(\"api.com\"));\n * if (result.ok) {\n * console.log(result.value);\n * } else {\n * console.error(result.error);\n * }\n * }\n * ```\n */\nexport function* safe(operator) {\n try {\n const value = yield* call(operator);\n return Ok(value);\n }\n catch (error) {\n return Err(error);\n }\n}\n//# sourceMappingURL=safe.js.map","import { createChannel, resource, spawn } from \"../deps.js\";\nimport { safe } from \"./safe.js\";\n/**\n * The goal of `parallel` is to make it easier to cooridnate multiple async\n * operations in parallel, with different ways to receive completed tasks.\n *\n * All tasks are called with {@link fx.safe} which means they will never\n * throw an exception. Instead all tasks will return a Result object that\n * the end development must evaluate in order to grab the value.\n *\n * @example\n * ```ts\n * import { parallel } from \"starfx\";\n *\n * function* run() {\n * const task = yield* parallel([job1, job2]);\n * // wait for all tasks to complete before moving to next yield point\n * const results = yield* task;\n * // job1 = results[0];\n * // job2 = results[1];\n * }\n * ```\n *\n * Instead of waiting for all tasks to complete, we can instead loop over\n * tasks as they arrive:\n *\n * @example\n * ```ts\n * function* run() {\n * const task = yield* parallel([job1, job2]);\n * for (const job of yield* each(task.immediate)) {\n * // job2 completes first then it will be first in list\n * console.log(job);\n * yield* each.next();\n * }\n * }\n * ```\n *\n * Or we can instead loop over tasks in order of the array provided to\n * parallel:\n *\n * @example\n * ```ts\n * function* run() {\n * const task = yield* parallel([job1, job2]);\n * for (const job of yield* each(task.sequence)) {\n * // job1 then job2 will be returned regardless of when the jobs\n * // complete\n * console.log(job);\n * yield* each.next();\n * }\n * }\n * ```\n */\nexport function parallel(operations) {\n const sequence = createChannel();\n const immediate = createChannel();\n const results = [];\n return resource(function* (provide) {\n const task = yield* spawn(function* () {\n const tasks = [];\n for (const op of operations) {\n tasks.push(yield* spawn(function* () {\n const result = yield* safe(op);\n yield* immediate.send(result);\n return result;\n }));\n }\n for (const tsk of tasks) {\n const res = yield* tsk;\n results.push(res);\n yield* sequence.send(res);\n }\n yield* sequence.close();\n yield* immediate.close();\n });\n function* wait() {\n yield* task;\n return results;\n }\n yield* provide({\n sequence,\n immediate,\n *[Symbol.iterator]() {\n return yield* wait();\n },\n });\n });\n}\n//# sourceMappingURL=parallel.js.map","export function matcher(pattern) {\n if (pattern === \"*\") {\n return function (input) {\n return !!input;\n };\n }\n if (typeof pattern === \"string\") {\n return function (input) {\n return pattern === input.type;\n };\n }\n if (Array.isArray(pattern)) {\n return function (input) {\n return pattern.some((p) => matcher(p)(input));\n };\n }\n if (typeof pattern === \"function\" && Object.hasOwn(pattern, \"toString\")) {\n return function (input) {\n return pattern.toString() === input.type;\n };\n }\n if (typeof pattern === \"function\") {\n return function (input) {\n return pattern(input);\n };\n }\n throw new Error(\"invalid pattern\");\n}\n//# sourceMappingURL=matcher.js.map","import { createQueue } from \"./deps.js\";\nexport function createFilterQueue(predicate) {\n const queue = createQueue();\n return {\n ...queue,\n add(value) {\n if (predicate(value)) {\n queue.add(value);\n }\n },\n };\n}\n//# sourceMappingURL=queue.js.map","import { call, createContext, createSignal, each, SignalQueueFactory, spawn, } from \"./deps.js\";\nimport { matcher } from \"./matcher.js\";\nimport { createFilterQueue } from \"./queue.js\";\nexport const ActionContext = createContext(\"starfx:action\", createSignal());\nexport function useActions(pattern) {\n return {\n *subscribe() {\n const actions = yield* ActionContext;\n const match = matcher(pattern);\n yield* SignalQueueFactory.set(() => createFilterQueue(match));\n return yield* actions.subscribe();\n },\n };\n}\nexport function emit({ signal, action, }) {\n if (Array.isArray(action)) {\n if (action.length === 0) {\n return;\n }\n action.map((a) => signal.send(a));\n }\n else {\n signal.send(action);\n }\n}\nexport function* put(action) {\n const signal = yield* ActionContext;\n return emit({\n signal,\n action,\n });\n}\nexport function* take(pattern) {\n const fd = useActions(pattern);\n for (const action of yield* each(fd)) {\n return action;\n }\n return { type: \"take failed, this should not be possible\" };\n}\nexport function* takeEvery(pattern, op) {\n const fd = useActions(pattern);\n for (const action of yield* each(fd)) {\n yield* spawn(() => op(action));\n yield* each.next();\n }\n}\nexport function* takeLatest(pattern, op) {\n const fd = useActions(pattern);\n let lastTask;\n for (const action of yield* each(fd)) {\n if (lastTask) {\n yield* lastTask.halt();\n }\n lastTask = yield* spawn(() => op(action));\n yield* each.next();\n }\n}\nexport function* takeLeading(pattern, op) {\n while (true) {\n const action = yield* take(pattern);\n yield* call(() => op(action));\n }\n}\nexport function* waitFor(predicate) {\n const init = yield* call(predicate);\n if (init) {\n return;\n }\n while (true) {\n yield* take(\"*\");\n const result = yield* call(() => predicate);\n if (result) {\n return;\n }\n }\n}\nexport function getIdFromAction(action) {\n return typeof action === \"function\" ? action.toString() : action.payload.key;\n}\nexport const API_ACTION_PREFIX = \"\";\nexport function createAction(actionType) {\n if (!actionType) {\n throw new Error(\"createAction requires non-empty string\");\n }\n const fn = (payload) => ({\n type: actionType,\n payload,\n });\n fn.toString = () => actionType;\n return fn;\n}\n//# sourceMappingURL=action.js.map","import { sleep } from \"../deps.js\";\nimport { safe } from \"./safe.js\";\nimport { parallel } from \"./parallel.js\";\nimport { put } from \"../action.js\";\nimport { API_ACTION_PREFIX } from \"../action.js\";\nexport function superviseBackoff(attempt, max = 10) {\n if (attempt > max)\n return -1;\n // 20ms, 40ms, 80ms, 160ms, 320ms, 640ms, 1280ms, 2560ms, 5120ms, 10240ms\n return 2 ** attempt * 10;\n}\n/**\n * supvervise will watch whatever {@link Operation} is provided\n * and it will automatically try to restart it when it exists. By\n * default it uses a backoff pressure mechanism so if there is an\n * error simply calling the {@link Operation} then it will exponentially\n * wait longer until attempting to restart and eventually give up.\n */\nexport function supervise(op, backoff = superviseBackoff) {\n return function* () {\n let attempt = 1;\n let waitFor = backoff(attempt);\n while (waitFor >= 0) {\n const res = yield* safe(op);\n if (res.ok) {\n attempt = 0;\n }\n else {\n yield* put({\n type: `${API_ACTION_PREFIX}supervise`,\n payload: res.error,\n meta: `Exception caught, waiting ${waitFor}ms before restarting operation`,\n });\n yield* sleep(waitFor);\n }\n attempt += 1;\n waitFor = backoff(attempt);\n }\n };\n}\n/**\n * keepAlive accepts a list of operations and calls them all with\n * {@link supervise}\n */\nexport function* keepAlive(ops, backoff) {\n const group = yield* parallel(ops.map((op) => supervise(op, backoff)));\n const results = yield* group;\n return results;\n}\n//# sourceMappingURL=supervisor.js.map","export function compose(middleware) {\n if (!Array.isArray(middleware)) {\n throw new TypeError(\"Middleware stack must be an array!\");\n }\n for (const fn of middleware) {\n if (typeof fn !== \"function\") {\n throw new TypeError(\"Middleware must be composed of functions!\");\n }\n }\n return function* composeFn(context, mdw) {\n // last called middleware #\n let index = -1;\n function* dispatch(i) {\n if (i <= index) {\n throw new Error(\"next() called multiple times\");\n }\n index = i;\n let fn = middleware[i];\n if (i === middleware.length) {\n fn = mdw;\n }\n if (!fn) {\n return;\n }\n const nxt = dispatch.bind(null, i + 1);\n yield* fn(context, nxt);\n }\n yield* dispatch(0);\n };\n}\n//# sourceMappingURL=compose.js.map","import { createChannel, createContext } from \"../deps.js\";\nexport const StoreUpdateContext = createContext(\"starfx:store:update\", createChannel());\nexport const StoreContext = createContext(\"starfx:store\");\n//# sourceMappingURL=context.js.map","import { parallel, safe } from \"../fx/mod.js\";\nexport function createRun(scope) {\n function run(op) {\n if (Array.isArray(op)) {\n return scope.run(function* () {\n const group = yield* parallel(op);\n const result = yield* group;\n return result;\n });\n }\n return scope.run(() => safe(op));\n }\n return run;\n}\n//# sourceMappingURL=run.js.map","import { ActionContext, API_ACTION_PREFIX, emit } from \"../action.js\";\nimport { compose } from \"../compose.js\";\nimport { createContext, createScope, createSignal, enablePatches, Ok, produceWithPatches, } from \"../deps.js\";\nimport { StoreContext, StoreUpdateContext } from \"./context.js\";\nimport { createRun } from \"./run.js\";\nconst stubMsg = \"This is merely a stub, not implemented\";\nlet id = 0;\n// https://github.com/reduxjs/redux/blob/4a6d2fb227ba119d3498a43fab8f53fe008be64c/src/createStore.ts#L344\nfunction observable() {\n return {\n subscribe: (_observer) => {\n throw new Error(stubMsg);\n },\n [Symbol.observable]() {\n return this;\n },\n };\n}\nexport const IdContext = createContext(\"starfx:id\", 0);\nexport function createStore({ initialState, scope: initScope, middleware = [], }) {\n let scope;\n if (initScope) {\n scope = initScope;\n }\n else {\n const tuple = createScope();\n scope = tuple[0];\n }\n let state = initialState;\n const listeners = new Set();\n enablePatches();\n const signal = createSignal();\n scope.set(ActionContext, signal);\n scope.set(IdContext, id++);\n function getScope() {\n return scope;\n }\n function getState() {\n return state;\n }\n function subscribe(fn) {\n listeners.add(fn);\n return () => listeners.delete(fn);\n }\n function* updateMdw(ctx, next) {\n const upds = [];\n if (Array.isArray(ctx.updater)) {\n upds.push(...ctx.updater);\n }\n else {\n upds.push(ctx.updater);\n }\n const [nextState, patches, _] = produceWithPatches(getState(), (draft) => {\n // TODO: check for return value inside updater\n // deno-lint-ignore no-explicit-any\n upds.forEach((updater) => updater(draft));\n });\n ctx.patches = patches;\n // set the state!\n state = nextState;\n yield* next();\n }\n function* logMdw(ctx, next) {\n dispatch({\n type: `${API_ACTION_PREFIX}store`,\n payload: ctx,\n });\n yield* next();\n }\n function* notifyChannelMdw(_, next) {\n const chan = yield* StoreUpdateContext;\n yield* chan.send();\n yield* next();\n }\n function* notifyListenersMdw(_, next) {\n listeners.forEach((f) => f());\n yield* next();\n }\n function createUpdater() {\n const fn = compose([\n updateMdw,\n ...middleware,\n logMdw,\n notifyChannelMdw,\n notifyListenersMdw,\n ]);\n return fn;\n }\n const mdw = createUpdater();\n function* update(updater) {\n const ctx = {\n updater,\n patches: [],\n result: Ok(undefined),\n };\n yield* mdw(ctx);\n if (!ctx.result.ok) {\n dispatch({\n type: `${API_ACTION_PREFIX}store`,\n payload: ctx.result.error,\n });\n }\n return ctx;\n }\n function dispatch(action) {\n emit({ signal, action });\n }\n function getInitialState() {\n return initialState;\n }\n function* reset(ignoreList = []) {\n return yield* update((s) => {\n const keep = ignoreList.reduce((acc, key) => {\n acc[key] = s[key];\n return acc;\n }, { ...initialState });\n Object.keys(s).forEach((key) => {\n s[key] = keep[key];\n });\n });\n }\n const store = {\n getScope,\n getState,\n subscribe,\n update,\n reset,\n run: createRun(scope),\n // instead of actions relating to store mutation, they\n // refer to pieces of business logic -- that can also mutate state\n dispatch,\n // stubs so `react-redux` is happy\n // deno-lint-ignore no-explicit-any\n replaceReducer(_nextReducer) {\n throw new Error(stubMsg);\n },\n getInitialState,\n [Symbol.observable]: observable,\n };\n // deno-lint-ignore no-explicit-any\n store.getScope().set(StoreContext, store);\n return store;\n}\n/**\n * @deprecated use {@link createStore}\n */\nexport const configureStore = createStore;\n//# sourceMappingURL=store.js.map","export function* noop() { }\n// deno-lint-ignore no-explicit-any\nexport const isFn = (fn) => fn && typeof fn === \"function\";\n// deno-lint-ignore no-explicit-any\nexport const isObject = (obj) => typeof obj === \"object\" && obj !== null;\nexport const mergeHeaders = (cur, next) => {\n if (!cur && !next)\n return {};\n if (!cur && next)\n return next;\n if (cur && !next)\n return cur;\n return { ...cur, ...next };\n};\nexport const mergeRequest = (cur, next) => {\n const defaultReq = { url: \"\", method: \"GET\", headers: mergeHeaders() };\n if (!cur && !next)\n return { ...defaultReq, headers: mergeHeaders() };\n if (!cur && next)\n return { ...defaultReq, ...next };\n if (cur && !next)\n return { ...defaultReq, ...cur };\n return {\n ...defaultReq,\n ...cur,\n ...next,\n headers: mergeHeaders(cur?.headers, next?.headers),\n };\n};\n//# sourceMappingURL=util.js.map","import { isObject } from \"./util.js\";\n// deno-lint-ignore no-explicit-any\nconst deepSortObject = (opts) => {\n if (!isObject(opts))\n return opts;\n return Object.keys(opts)\n .sort()\n .reduce((res, key) => {\n res[`${key}`] = opts[key];\n if (opts[key] && isObject(opts[key])) {\n res[`${key}`] = deepSortObject(opts[key]);\n }\n return res;\n }, {});\n};\nfunction padStart(hash, len) {\n while (hash.length < len) {\n hash = \"0\" + hash;\n }\n return hash;\n}\n// https://gist.github.com/iperelivskiy/4110988\nconst tinySimpleHash = (s) => {\n let h = 9;\n for (let i = 0; i < s.length;) {\n h = Math.imul(h ^ s.charCodeAt(i++), 9 ** 9);\n }\n return h ^ (h >>> 9);\n};\n/**\n * This function used to set `ctx.key`\n */\n// deno-lint-ignore no-explicit-any\nexport const createKey = (name, payload) => {\n const normJsonString = typeof payload !== \"undefined\"\n ? JSON.stringify(deepSortObject(payload))\n : \"\";\n const hash = normJsonString\n ? padStart(tinySimpleHash(normJsonString).toString(16), 8)\n : \"\";\n return hash ? `${name}|${hash}` : name;\n};\n//# sourceMappingURL=create-key.js.map","import { ActionContext, API_ACTION_PREFIX, takeEvery } from \"../action.js\";\nimport { compose } from \"../compose.js\";\nimport { ensure, Ok } from \"../deps.js\";\nimport { keepAlive, supervise } from \"../fx/mod.js\";\nimport { IdContext } from \"../store/store.js\";\nimport { createKey } from \"./create-key.js\";\nimport { isFn, isObject } from \"./util.js\";\nlet id = 0;\n/**\n * Creates a middleware pipeline.\n *\n * @remarks\n * This middleware pipeline is almost exactly like koa's middleware system.\n * See {@link https://koajs.com}\n *\n * @example\n * ```ts\n * import { createThunks } from 'starfx';\n *\n * const thunks = createThunks();\n * thunks.use(function* (ctx, next) {\n * console.log('beginning');\n * yield* next();\n * console.log('end');\n * });\n * thunks.use(thunks.routes());\n *\n * const doit = thunks.create('do-something', function*(ctx, next) {\n * console.log('middle');\n * yield* next();\n * console.log('middle end');\n * });\n *\n * // ...\n *\n * store.dispatch(doit());\n * // beginning\n * // middle\n * // middle end\n * // end\n * ```\n */\nexport function createThunks({ supervisor = takeEvery, } = { supervisor: takeEvery }) {\n let signal = undefined;\n let storeId = undefined;\n const middleware = [];\n const visors = {};\n const middlewareMap = {};\n let dynamicMiddlewareMap = {};\n const actionMap = {};\n const thunkId = id++;\n const storeMap = new Map();\n function* defaultMiddleware(_, next) {\n yield* next();\n }\n const createType = (post) => `${API_ACTION_PREFIX}${post}`;\n function* onApi(action) {\n const { name, key, options } = action.payload;\n const actionFn = actionMap[name];\n const ctx = {\n action,\n name,\n key,\n payload: options,\n actionFn,\n result: Ok(undefined),\n };\n const fn = compose(middleware);\n yield* fn(ctx);\n return ctx;\n }\n function create(name, ...args) {\n if (Object.hasOwn(visors, name)) {\n const msg = `[${name}] already exists, do you have two thunks with the same name?`;\n console.warn(msg);\n }\n const type = createType(name);\n const action = (payload) => {\n return { type, payload };\n };\n let req = null;\n let fn = null;\n if (args.length === 2) {\n req = args[0];\n fn = args[1];\n }\n if (args.length === 1) {\n if (isFn(args[0]) || Array.isArray(args[0])) {\n fn = args[0];\n }\n else {\n req = args[0];\n }\n }\n if (req && !isObject(req)) {\n throw new Error(\"Options must be an object\");\n }\n if (fn && Array.isArray(fn)) {\n fn = compose(fn);\n }\n if (fn && !isFn(fn)) {\n throw new Error(\"Middleware must be a function\");\n }\n middlewareMap[name] = fn || defaultMiddleware;\n const tt = req ? req.supervisor : supervisor;\n function* curVisor() {\n yield* tt(type, onApi);\n }\n visors[name] = curVisor;\n // If signal is already referenced, register immediately, otherwise defer\n for (const [storeId, storeSignal] of storeMap.entries()) {\n storeSignal.send({\n type: `${API_ACTION_PREFIX}REGISTER_THUNK_${storeId}_${thunkId}`,\n payload: curVisor,\n });\n }\n const errMsg = `[${name}] is being called before its thunk has been registered. ` +\n \"Run `store.run(thunks.register)` where `thunks` is the name of your `createThunks` or `createApi` variable.\";\n const actionFn = (options) => {\n if (!signal) {\n console.warn(errMsg);\n }\n const key = createKey(name, options);\n return action({ name, key, options });\n };\n actionFn.run = (action) => {\n if (action && Object.hasOwn(action, \"type\")) {\n return onApi(action);\n }\n return onApi(actionFn(action));\n };\n actionFn.use = (fn) => {\n const cur = middlewareMap[name];\n if (cur) {\n dynamicMiddlewareMap[name] = compose([cur, fn]);\n }\n else {\n dynamicMiddlewareMap[name] = fn;\n }\n };\n actionFn.toString = () => type;\n actionFn._success = {};\n actionFn._error = {};\n actionMap[name] = actionFn;\n return actionFn;\n }\n function* watcher(action) {\n yield* supervise(action.payload)();\n }\n function* register() {\n storeId = yield* IdContext;\n if (storeId && storeMap.has(storeId)) {\n console.warn(\"This thunk instance is already registered.\");\n return;\n }\n signal = yield* ActionContext;\n storeMap.set(storeId, signal);\n yield* ensure(function* () {\n if (storeId) {\n storeMap.delete(storeId);\n }\n });\n // Register any thunks created after signal is available\n yield* keepAlive(Object.values(visors));\n // Spawn a watcher for further thunk matchingPairs\n yield* takeEvery(`${API_ACTION_PREFIX}REGISTER_THUNK_${storeId}_${thunkId}`, watcher);\n }\n function routes() {\n function* router(ctx, next) {\n const match = dynamicMiddlewareMap[ctx.name] || middlewareMap[ctx.name];\n if (!match) {\n yield* next();\n return;\n }\n const result = yield* match(ctx, next);\n return result;\n }\n return router;\n }\n function resetMdw() {\n dynamicMiddlewareMap = {};\n }\n return {\n use: (fn) => {\n middleware.push(fn);\n },\n create,\n routes,\n /**\n * @deprecated use `register()` instead\n */\n bootup: register,\n reset: resetMdw,\n register,\n };\n}\n//# sourceMappingURL=thunk.js.map","import { createThunks } from \"./thunk.js\";\n/**\n * Creates a middleware thunksline for HTTP requests.\n *\n * @remarks\n * It uses {@link createThunks} under the hood.\n *\n * @example\n * ```ts\n * import { createApi, mdw } from 'starfx';\n *\n * const api = createApi();\n * api.use(mdw.api());\n * api.use(api.routes());\n * api.use(mdw.fetch({ baseUrl: 'https://api.com' }));\n *\n * const fetchUsers = api.get('/users', function*(ctx, next) {\n * yield next();\n * });\n *\n * store.dispatch(fetchUsers());\n * ```\n */\nexport function createApi(baseThunk) {\n const thunks = baseThunk || createThunks();\n const uri = (prename) => {\n const create = thunks.create;\n let name = prename;\n let remainder = \"\";\n if (Array.isArray(name)) {\n if (name.length === 0) {\n throw new Error(\"createApi requires a non-empty array for the name of the endpoint\");\n }\n name = prename[0];\n if (name.length > 1) {\n const [_, ...other] = prename;\n remainder = ` ${other.join(\"|\")}`;\n }\n }\n const tmpl = (method) => `${name} [${method}]${remainder}`;\n return {\n get: (...args) => create(tmpl(\"GET\"), ...args),\n post: (...args) => create(tmpl(\"POST\"), ...args),\n put: (...args) => create(tmpl(\"PUT\"), ...args),\n patch: (...args) => create(tmpl(\"PATCH\"), ...args),\n delete: (...args) => create(tmpl(\"DELETE\"), ...args),\n options: (...args) => create(tmpl(\"OPTIONS\"), ...args),\n head: (...args) => create(tmpl(\"HEAD\"), ...args),\n connect: (...args) => create(tmpl(\"CONNECT\"), ...args),\n trace: (...args) => create(tmpl(\"TRACE\"), ...args),\n };\n };\n return {\n use: thunks.use,\n /**\n * @deprecated use `register()` instead\n */\n bootup: thunks.register,\n register: thunks.register,\n create: thunks.create,\n routes: thunks.routes,\n reset: thunks.reset,\n cache: () => {\n return function* onCache(ctx, next) {\n ctx.cache = true;\n yield* next();\n };\n },\n request: (req) => {\n return function* onRequest(ctx, next) {\n ctx.request = ctx.req(req);\n yield* next();\n };\n },\n uri,\n get: (name, ...args) => uri(name).get(...args),\n post: (name, ...args) => uri(name).post(...args),\n put: (name, ...args) => uri(name).put(...args),\n patch: (name, ...args) => uri(name).patch(...args),\n delete: (name, ...args) => uri(name).delete(...args),\n options: (name, ...args) => uri(name).options(...args),\n head: (name, ...args) => uri(name).head(...args),\n connect: (name, ...args) => uri(name).connect(...args),\n trace: (name, ...args) => uri(name).trace(...args),\n };\n}\n//# sourceMappingURL=api.js.map","import { StoreContext } from \"./context.js\";\nimport { parallel, safe } from \"../fx/mod.js\";\nimport { getIdFromAction, take } from \"../action.js\";\nexport function* updateStore(updater) {\n const store = yield* StoreContext;\n // had to cast the store since StoreContext has a generic store type\n const st = store;\n const ctx = yield* st.update(updater);\n return ctx;\n}\nexport function* select(selectorFn, p) {\n const store = yield* StoreContext;\n return selectorFn(store.getState(), p);\n}\nexport function* waitForLoader(loaders, action) {\n const id = getIdFromAction(action);\n const selector = (s) => loaders.selectById(s, { id });\n // check for done state on init\n let loader = yield* select(selector);\n if (loader.isSuccess || loader.isError) {\n return loader;\n }\n while (true) {\n yield* take(\"*\");\n loader = yield* select(selector);\n if (loader.isSuccess || loader.isError) {\n return loader;\n }\n }\n}\nexport function* waitForLoaders(loaders, actions) {\n const group = yield* parallel(actions.map((action) => waitForLoader(loaders, action)));\n return yield* group;\n}\nexport function createTracker(loader) {\n return (id) => {\n return function* (op) {\n yield* updateStore(loader.start({ id }));\n const result = yield* safe(op);\n if (result.ok) {\n yield* updateStore(loader.success({ id }));\n }\n else {\n yield* updateStore(loader.error({\n id,\n message: result.error.message,\n }));\n }\n return result;\n };\n };\n}\n//# sourceMappingURL=fx.js.map","export function createStr({ name, initialState = \"\" }) {\n return {\n schema: \"str\",\n name: name,\n initialState,\n set: (value) => (state) => {\n // deno-lint-ignore no-explicit-any\n state[name] = value;\n },\n reset: () => (state) => {\n // deno-lint-ignore no-explicit-any\n state[name] = initialState;\n },\n select: (state) => {\n // deno-lint-ignore no-explicit-any\n return state[name];\n },\n };\n}\nexport function str(initialState) {\n return (name) => createStr({ name, initialState });\n}\n//# sourceMappingURL=str.js.map","export function createNum({ name, initialState = 0 }) {\n return {\n name: name,\n schema: \"num\",\n initialState,\n set: (value) => (state) => {\n // deno-lint-ignore no-explicit-any\n state[name] = value;\n },\n increment: (by = 1) => (state) => {\n // deno-lint-ignore no-explicit-any\n state[name] += by;\n },\n decrement: (by = 1) => (state) => {\n // deno-lint-ignore no-explicit-any\n state[name] -= by;\n },\n reset: () => (state) => {\n // deno-lint-ignore no-explicit-any\n state[name] = initialState;\n },\n select: (state) => {\n // deno-lint-ignore no-explicit-any\n return state[name];\n },\n };\n}\nexport function num(initialState) {\n return (name) => createNum({ name, initialState });\n}\n//# sourceMappingURL=num.js.map","import { createSelector } from \"../../deps.js\";\nconst excludesFalse = (n) => Boolean(n);\nfunction mustSelectEntity(defaultEntity) {\n const isFn = typeof defaultEntity === \"function\";\n return function selectEntity(selectById) {\n return (state, { id }) => {\n if (isFn) {\n const entity = defaultEntity;\n return selectById(state, { id }) || entity();\n }\n return selectById(state, { id }) || defaultEntity;\n };\n };\n}\nfunction tableSelectors(selectTable, empty) {\n const must = empty ? mustSelectEntity(empty) : null;\n const tableAsList = (data) => Object.values(data).filter(excludesFalse);\n const findById = (data, { id }) => data[id];\n const findByIds = (data, { ids }) => ids.map((id) => data[id]).filter(excludesFalse);\n const selectById = (state, { id }) => {\n const data = selectTable(state);\n return findById(data, { id });\n };\n const sbi = must ? must(selectById) : selectById;\n return {\n findById: must ? must(findById) : findById,\n findByIds,\n tableAsList,\n selectTable,\n selectTableAsList: createSelector(selectTable, (data) => tableAsList(data)),\n selectById: sbi,\n selectByIds: createSelector(selectTable, (_, p) => p.ids, (data, ids) => findByIds(data, { ids })),\n };\n}\nexport function createTable({ name, empty, initialState = {}, }) {\n const selectors = tableSelectors((s) => s[name], empty);\n return {\n schema: \"table\",\n name: name,\n initialState,\n empty: typeof empty === \"function\" ? empty() : empty,\n add: (entities) => (s) => {\n const state = selectors.selectTable(s);\n Object.keys(entities).forEach((id) => {\n state[id] = entities[id];\n });\n },\n set: (entities) => (s) => {\n // deno-lint-ignore no-explicit-any\n s[name] = entities;\n },\n remove: (ids) => (s) => {\n const state = selectors.selectTable(s);\n ids.forEach((id) => {\n delete state[id];\n });\n },\n patch: (entities) => (s) => {\n const state = selectors.selectTable(s);\n Object.keys(entities).forEach((id) => {\n state[id] = { ...state[id], ...entities[id] };\n });\n },\n merge: (entities) => (s) => {\n const state = selectors.selectTable(s);\n Object.keys(entities).forEach((id) => {\n const entity = entities[id];\n Object.keys(entity).forEach((prop) => {\n const val = entity[prop];\n if (Array.isArray(val)) {\n // deno-lint-ignore no-explicit-any\n const list = val;\n // deno-lint-ignore no-explicit-any\n state[id][prop].push(...list);\n }\n else {\n // deno-lint-ignore no-explicit-any\n state[id][prop] = entities[id][prop];\n }\n });\n });\n },\n reset: () => (s) => {\n // deno-lint-ignore no-explicit-any\n s[name] = initialState;\n },\n ...selectors,\n };\n}\nexport function table({ initialState, empty } = {}) {\n return (name) => createTable({ name, empty, initialState });\n}\n//# sourceMappingURL=table.js.map","export function createAny({ name, initialState }) {\n return {\n schema: \"any\",\n name: name,\n initialState,\n set: (value) => (state) => {\n // deno-lint-ignore no-explicit-any\n state[name] = value;\n },\n reset: () => (state) => {\n // deno-lint-ignore no-explicit-any\n state[name] = initialState;\n },\n select: (state) => {\n // deno-lint-ignore no-explicit-any\n return state[name];\n },\n };\n}\nexport function any(initialState) {\n return (name) => createAny({ name, initialState });\n}\n//# sourceMappingURL=any.js.map","export function createObj({ name, initialState }) {\n return {\n schema: \"obj\",\n name: name,\n initialState,\n set: (value) => (state) => {\n // deno-lint-ignore no-explicit-any\n state[name] = value;\n },\n reset: () => (state) => {\n // deno-lint-ignore no-explicit-any\n state[name] = initialState;\n },\n update: (prop) => (state) => {\n // deno-lint-ignore no-explicit-any\n state[name][prop.key] = prop.value;\n },\n select: (state) => {\n // deno-lint-ignore no-explicit-any\n return state[name];\n },\n };\n}\nexport function obj(initialState) {\n return (name) => createObj({ name, initialState });\n}\n//# sourceMappingURL=obj.js.map","import { createSelector } from \"../../deps.js\";\nconst excludesFalse = (n) => Boolean(n);\nexport function defaultLoaderItem(li = {}) {\n return {\n id: \"\",\n status: \"idle\",\n message: \"\",\n lastRun: 0,\n lastSuccess: 0,\n meta: {},\n ...li,\n };\n}\nexport function defaultLoader(l = {}) {\n const loading = defaultLoaderItem(l);\n return {\n ...loading,\n isIdle: loading.status === \"idle\",\n isError: loading.status === \"error\",\n isSuccess: loading.status === \"success\",\n isLoading: loading.status === \"loading\",\n isInitialLoading: (loading.status === \"idle\" || loading.status === \"loading\") &&\n loading.lastSuccess === 0,\n };\n}\nfunction loaderSelectors(selectTable) {\n const empty = defaultLoader();\n const tableAsList = (data) => Object.values(data).filter(excludesFalse);\n const findById = (data, { id }) => (defaultLoader(data[id]) || empty);\n const findByIds = (data, { ids }) => ids.map((id) => defaultLoader(data[id])).filter(excludesFalse);\n const selectById = createSelector(selectTable, (_, p) => p.id, (loaders, id) => findById(loaders, { id }));\n return {\n findById,\n findByIds,\n selectTable,\n selectTableAsList: createSelector(selectTable, (data) => tableAsList(data)),\n selectById,\n selectByIds: createSelector(selectTable, (_, p) => p.ids, (loaders, ids) => findByIds(loaders, { ids })),\n };\n}\nconst ts = () => new Date().getTime();\nexport const createLoaders = ({ name, initialState = {}, }) => {\n const selectors = loaderSelectors((s) => s[name]);\n return {\n schema: \"loader\",\n name: name,\n initialState,\n start: (e) => (s) => {\n const table = selectors.selectTable(s);\n const loader = table[e.id];\n table[e.id] = defaultLoaderItem({\n ...loader,\n ...e,\n status: \"loading\",\n lastRun: ts(),\n });\n },\n success: (e) => (s) => {\n const table = selectors.selectTable(s);\n const loader = table[e.id];\n table[e.id] = defaultLoaderItem({\n ...loader,\n ...e,\n status: \"success\",\n lastSuccess: ts(),\n });\n },\n error: (e) => (s) => {\n const table = selectors.selectTable(s);\n const loader = table[e.id];\n table[e.id] = defaultLoaderItem({\n ...loader,\n ...e,\n status: \"error\",\n });\n },\n reset: () => (s) => {\n // deno-lint-ignore no-explicit-any\n s[name] = initialState;\n },\n resetByIds: (ids) => (s) => {\n const table = selectors.selectTable(s);\n ids.forEach((id) => {\n delete table[id];\n });\n },\n ...selectors,\n };\n};\nexport function loaders(initialState) {\n return (name) => createLoaders({ name, initialState });\n}\n//# sourceMappingURL=loaders.js.map","import { str } from \"./str.js\";\nimport { num } from \"./num.js\";\nimport { table } from \"./table.js\";\nimport { any } from \"./any.js\";\nimport { obj } from \"./obj.js\";\nimport { defaultLoader, defaultLoaderItem, loaders, } from \"./loaders.js\";\nexport const slice = {\n str,\n num,\n table,\n any,\n obj,\n loaders,\n /**\n * @deprecated Use `slice.loaders` instead\n */\n loader: loaders,\n};\nexport { defaultLoader, defaultLoaderItem };\n//# sourceMappingURL=mod.js.map","import { updateStore } from \"./fx.js\";\nimport { slice } from \"./slice/mod.js\";\nconst defaultSchema = function () {\n return { cache: slice.table(), loaders: slice.loaders() };\n};\nexport function createSchema(slices = defaultSchema()) {\n const db = Object.keys(slices).reduce((acc, key) => {\n // deno-lint-ignore no-explicit-any\n acc[key] = slices[key](key);\n return acc;\n }, {});\n const initialState = Object.keys(db).reduce((acc, key) => {\n // deno-lint-ignore no-explicit-any\n acc[key] = db[key].initialState;\n return acc;\n }, {});\n function* update(ups) {\n return yield* updateStore(ups);\n }\n db.update = update;\n return [db, initialState];\n}\n//# sourceMappingURL=schema.js.map","import { action } from \"../deps.js\";\nexport function createBatchMdw(queue) {\n let notifying = false;\n return function* batchMdw(_, next) {\n if (!notifying) {\n notifying = true;\n yield* action(function* (resolve) {\n queue(() => {\n notifying = false;\n resolve();\n });\n });\n yield* next();\n }\n };\n}\n//# sourceMappingURL=batch.js.map","import { Err, Ok } from \"../deps.js\";\nimport { select, updateStore } from \"./fx.js\";\nexport const PERSIST_LOADER_ID = \"@@starfx/persist\";\nexport function createTransform() {\n const transformers = {\n in: function (currentState) {\n return currentState;\n },\n out: function (currentState) {\n return currentState;\n },\n };\n const inTransformer = function (state) {\n return transformers.in(state);\n };\n const outTransformer = function (state) {\n return transformers.out(state);\n };\n return {\n in: inTransformer,\n out: outTransformer,\n };\n}\nexport function createLocalStorageAdapter() {\n return {\n getItem: function* (key) {\n const storage = localStorage.getItem(key) || \"{}\";\n return Ok(JSON.parse(storage));\n },\n setItem: function* (key, s) {\n const state = JSON.stringify(s);\n try {\n localStorage.setItem(key, state);\n }\n catch (err) {\n return Err(err);\n }\n return Ok(undefined);\n },\n removeItem: function* (key) {\n localStorage.removeItem(key);\n return Ok(undefined);\n },\n };\n}\nexport function shallowReconciler(original, persisted) {\n return { ...original, ...persisted };\n}\nexport function createPersistor({ adapter, key = \"starfx\", reconciler = shallowReconciler, allowlist = [], transform, }) {\n function* rehydrate() {\n const persistedState = yield* adapter.getItem(key);\n if (!persistedState.ok) {\n return Err(persistedState.error);\n }\n let stateFromStorage = persistedState.value;\n if (transform) {\n try {\n stateFromStorage = transform.out(persistedState.value);\n }\n catch (err) {\n console.error(\"Persistor outbound transformer error:\", err);\n }\n }\n const state = yield* select((s) => s);\n const nextState = reconciler(state, stateFromStorage);\n yield* updateStore(function (state) {\n Object.keys(nextState).forEach((key) => {\n state[key] = nextState[key];\n });\n });\n return Ok(undefined);\n }\n return {\n key,\n adapter,\n allowlist,\n reconciler,\n rehydrate,\n transform,\n };\n}\nexport function persistStoreMdw({ allowlist, adapter, key, transform }) {\n return function* (_, next) {\n yield* next();\n const state = yield* select((s) => s);\n let transformedState = state;\n if (transform) {\n try {\n transformedState = transform.in(state);\n }\n catch (err) {\n console.error(\"Persistor inbound transformer error:\", err);\n }\n }\n // empty allowlist list means save entire state\n if (allowlist.length === 0) {\n yield* adapter.setItem(key, transformedState);\n return;\n }\n const allowedState = allowlist.reduce((acc, key) => {\n if (key in transformedState) {\n acc[key] = transformedState[key];\n }\n return acc;\n }, {});\n yield* adapter.setItem(key, allowedState);\n };\n}\n//# sourceMappingURL=persist.js.map","import { sleep } from \"../deps.js\";\nimport { safe } from \"../fx/mod.js\";\nimport { isObject, noop } from \"../query/util.js\";\n/**\n * This middleware converts the name provided to {@link createApi}\n * into `url` and `method` for the fetch request.\n */\nexport function* nameParser(ctx, next) {\n const httpMethods = [\n \"get\",\n \"head\",\n \"post\",\n \"put\",\n \"delete\",\n \"connect\",\n \"options\",\n \"trace\",\n \"patch\",\n ];\n const options = ctx.payload || {};\n if (!isObject(options)) {\n yield* next();\n return;\n }\n let url = Object.keys(options).reduce((acc, key) => {\n return acc.replace(`:${key}`, options[key]);\n }, ctx.name);\n let method = \"\";\n httpMethods.forEach((curMethod) => {\n const pattern = new RegExp(`\\\\s*\\\\[` + curMethod + `\\\\]\\\\s*\\\\w*`, \"i\");\n const tmpUrl = url.replace(pattern, \"\");\n if (tmpUrl.length !== url.length) {\n method = curMethod.toLocaleUpperCase();\n }\n url = tmpUrl;\n }, url);\n if (ctx.req().url === \"\") {\n ctx.request = ctx.req({ url });\n }\n if (method) {\n ctx.request = ctx.req({ method });\n }\n yield* next();\n}\n/**\n * Automatically sets `content-type` to `application/json` when\n * that header is not already present.\n */\nexport function* headers(ctx, next) {\n if (!ctx.request) {\n yield* next();\n return;\n }\n const cur = ctx.req();\n if (!Object.hasOwn(cur.headers, \"Content-Type\")) {\n ctx.request = ctx.req({\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n yield* next();\n}\n/**\n * This middleware takes the `ctx.response` and sets `ctx.json` to the body representation\n * requested. It uses the `ctx.bodyType` property to determine how to represent the body.\n * The default is set to `json` which calls `Response.json()`.\n *\n * @example\n * ```ts\n * const fetchUsers = api.get('/users', function*(ctx, next) {\n * ctx.bodyType = 'text'; // calls Response.text();\n * yield next();\n * })\n * ```\n */\nexport function* json(ctx, next) {\n if (!ctx.response) {\n yield* next();\n return;\n }\n if (ctx.response.status === 204) {\n ctx.json = {\n ok: true,\n value: {},\n };\n yield* next();\n return;\n }\n const data = yield* safe(() => {\n const resp = ctx.response;\n if (!resp)\n throw new Error(\"response is falsy\");\n return resp[ctx.bodyType]();\n });\n if (data.ok) {\n if (ctx.response.ok) {\n ctx.json = {\n ok: true,\n value: data.value,\n };\n }\n else {\n ctx.json = {\n ok: false,\n error: data.value,\n };\n }\n }\n else {\n const dta = { message: data.error.message };\n ctx.json = {\n ok: false,\n error: dta,\n };\n }\n yield* next();\n}\n/*\n * This middleware takes the `baseUrl` provided to {@link mdw.fetch} and combines it\n * with the url from `ctx.request.url`.\n */\nexport function composeUrl(baseUrl = \"\") {\n return function* (ctx, next) {\n const req = ctx.req();\n ctx.request = ctx.req({ url: `${baseUrl}${req.url}` });\n yield* next();\n };\n}\n/**\n * If there's a slug inside the ctx.name (which is the URL segement in this case)\n * and there is *not* a corresponding truthy value in the payload, then that means\n * the user has an empty value (e.g. empty string) which means we want to abort the\n * fetch request.\n *\n * e.g. `ctx.name = \"/apps/:id\"` with `payload = { id: '' }`\n *\n * Ideally the action wouldn't have been dispatched at all but that is *not* a\n * gaurantee we can make here.\n */\nexport function* payload(ctx, next) {\n const payload = ctx.payload;\n if (!payload) {\n yield* next();\n return;\n }\n const keys = Object.keys(payload);\n for (let i = 0; i < keys.length; i += 1) {\n const key = keys[i];\n if (!ctx.name.includes(`:${key}`)) {\n continue;\n }\n const val = payload[key];\n if (!val) {\n const data = `found :${key} in endpoint name (${ctx.name}) but payload has falsy value (${val})`;\n ctx.json = {\n ok: false,\n error: data,\n };\n return;\n }\n }\n yield* next();\n}\n/*\n * This middleware simply checks if `ctx.response` already contains a\n * truthy value, and if it does, bail out of the middleware stack.\n */\nexport function response(response) {\n return function* responseMdw(ctx, next) {\n if (response) {\n ctx.response = response;\n }\n yield* next();\n };\n}\n/*\n * This middleware makes the `fetch` http request using `ctx.request` and\n * assigns the response to `ctx.response`.\n */\nexport function* request(ctx, next) {\n // if there is already a response then we want to bail so we don't\n // override it.\n if (ctx.response) {\n yield* next();\n return;\n }\n const { url, ...req } = ctx.req();\n const request = new Request(url, req);\n const result = yield* safe(fetch(request));\n if (result.ok) {\n ctx.response = result.value;\n }\n else {\n throw result.error;\n }\n yield* next();\n}\nfunction backoffExp(attempt) {\n if (attempt > 5)\n return -1;\n // 1s, 1s, 1s, 2s, 4s\n return Math.max(2 ** attempt * 125, 1000);\n}\n/**\n * This middleware will retry failed `Fetch` request if `response.ok` is `false`.\n * It accepts a backoff function to determine how long to continue retrying.\n * The default is an exponential backoff {@link backoffExp} where the minimum is\n * 1sec between attempts and it'll reach 4s between attempts at the end with a\n * max of 5 attempts.\n *\n * An example backoff:\n * @example\n * ```ts\n * // Any value less than 0 will stop the retry middleware.\n * // Each attempt will wait 1s\n * const backoff = (attempt: number) => {\n * if (attempt > 5) return -1;\n * return 1000;\n * }\n *\n * const api = createApi();\n * api.use(mdw.api());\n * api.use(api.routes());\n * api.use(mdw.fetch());\n *\n * const fetchUsers = api.get('/users', [\n * function*(ctx, next) {\n * // ...\n * yield next();\n * },\n * // fetchRetry should be after your endpoint function because\n * // the retry middleware will update `ctx.json` before it reaches\n * // your middleware\n * fetchRetry(backoff),\n * ])\n * ```\n */\nexport function fetchRetry(backoff = backoffExp) {\n return function* (ctx, next) {\n yield* next();\n if (!ctx.response) {\n return;\n }\n if (ctx.response.ok) {\n return;\n }\n let attempt = 1;\n let waitFor = backoff(attempt);\n while (waitFor >= 1) {\n yield* sleep(waitFor);\n // reset response so `request` mdw actually runs\n ctx.response = null;\n yield* safe(() => request(ctx, noop));\n yield* safe(() => json(ctx, noop));\n if (ctx.response && ctx.response.ok) {\n return;\n }\n attempt += 1;\n waitFor = backoff(attempt);\n }\n };\n}\n//# sourceMappingURL=fetch.js.map","import { safe } from \"../fx/mod.js\";\nimport { compose } from \"../compose.js\";\nimport { mergeRequest } from \"../query/util.js\";\nimport * as fetchMdw from \"./fetch.js\";\nimport { call } from \"../deps.js\";\nimport { put } from \"../action.js\";\nexport * from \"./fetch.js\";\n/**\n * This middleware will catch any errors in the pipeline\n * and `console.error` the context object.\n *\n * You are highly encouraged to ditch this middleware if you need something\n * more custom.\n *\n * It also sets `ctx.result` which informs us whether the entire\n * middleware pipeline succeeded or not. Think the `.catch()` case for\n * `window.fetch`.\n */\nexport function* err(ctx, next) {\n ctx.result = yield* safe(next);\n if (!ctx.result.ok) {\n const message = `Error: ${ctx.result.error.message}. Check the endpoint [${ctx.name}]`;\n console.error(message, ctx);\n yield* put({\n type: \"error:query\",\n payload: {\n message,\n ctx,\n },\n });\n }\n}\n/**\n * This middleware allows the user to override the default key provided\n * to every pipeline function and instead use whatever they want.\n *\n * @example\n * ```ts\n * import { createPipe } from 'starfx';\n *\n * const thunk = createPipe();\n * thunk.use(customKey);\n *\n * const doit = thunk.create('some-action', function*(ctx, next) {\n * ctx.key = 'something-i-want';\n * })\n * ```\n */\nexport function* customKey(ctx, next) {\n if (ctx?.key &&\n ctx?.action?.payload?.key &&\n ctx.key !== ctx.action.payload.key) {\n const newKey = ctx.name.split(\"|\")[0] + \"|\" + ctx.key;\n ctx.key = newKey;\n ctx.action.payload.key = newKey;\n }\n yield* next();\n}\n/**\n * This middleware sets up the context object with some values that are\n * necessary for {@link createApi} to work properly.\n */\nexport function* queryCtx(ctx, next) {\n if (!ctx.req) {\n ctx.req = (r) => mergeRequest(ctx.request, r);\n }\n if (!ctx.request)\n ctx.request = ctx.req();\n if (!ctx.response)\n ctx.response = null;\n if (!ctx.json)\n ctx.json = { ok: false, error: {} };\n if (!ctx.actions)\n ctx.actions = [];\n if (!ctx.bodyType)\n ctx.bodyType = \"json\";\n yield* next();\n}\n/**\n * This middleware will take the result of `ctx.actions` and dispatch them\n * as a single batch.\n *\n * @remarks This is useful because sometimes there are a lot of actions that need dispatched\n * within the pipeline of the middleware and instead of dispatching them serially this\n * improves performance by only hitting the reducers once.\n */\nexport function* actions(ctx, next) {\n if (!ctx.actions)\n ctx.actions = [];\n yield* next();\n if (ctx.actions.length === 0)\n return;\n yield* put(ctx.actions);\n}\n/**\n * This middleware will add `performance.now()` before and after your\n * middleware pipeline.\n */\nexport function* perf(ctx, next) {\n const t0 = performance.now();\n yield* next();\n const t1 = performance.now();\n ctx.performance = t1 - t0;\n}\n/**\n * This middleware is a composition of other middleware required to\n * use `window.fetch` {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API}\n * with {@link createApi}\n */\nexport function fetch({ baseUrl = \"\", } = { baseUrl: \"\" }) {\n return compose([\n fetchMdw.composeUrl(baseUrl),\n fetchMdw.payload,\n fetchMdw.request,\n fetchMdw.json,\n ]);\n}\n/**\n * This middleware will only be activated if predicate is true.\n */\nexport function predicate(predicate) {\n return (mdw) => {\n return function* (ctx, next) {\n const valid = yield* call(() => predicate(ctx));\n if (!valid) {\n yield* next();\n return;\n }\n yield* mdw(ctx, next);\n };\n };\n}\n//# sourceMappingURL=query.js.map","import { compose } from \"../compose.js\";\nimport { select, updateStore, } from \"../store/mod.js\";\nimport { actions, customKey, err, queryCtx } from \"./query.js\";\nimport { nameParser } from \"./fetch.js\";\n/**\n * This middleware is a composition of many middleware used to faciliate\n * the {@link createApi}.\n *\n * It is not required, however, it is battle-tested and highly recommended.\n *\n * List of mdw:\n * - {@link mdw.err}\n * - {@link mdw.actions}\n * - {@link mdw.queryCtx}\n * - {@link mdw.customKey}\n * - {@link mdw.nameParser}\n * - {@link mdw.loaderApi}\n * - {@link mdw.cache}\n */\nexport function api(props) {\n return compose([\n err,\n actions,\n queryCtx,\n customKey,\n nameParser,\n loaderApi(props),\n cache(props.schema),\n ]);\n}\n/**\n * This middleware will automatically cache any data found inside `ctx.json`\n * which is where we store JSON data from the {@link mdw.fetch} middleware.\n */\nexport function cache(schema) {\n return function* cache(ctx, next) {\n ctx.cacheData = yield* select(schema.cache.selectById, { id: ctx.key });\n yield* next();\n if (!ctx.cache)\n return;\n let data;\n if (ctx.json.ok) {\n data = ctx.json.value;\n }\n else {\n data = ctx.json.error;\n }\n yield* updateStore(schema.cache.add({ [ctx.key]: data }));\n ctx.cacheData = data;\n };\n}\n/**\n * This middleware will track the status of a middleware fn\n */\nexport function loader(schema) {\n return function* (ctx, next) {\n yield* updateStore([\n schema.loaders.start({ id: ctx.name }),\n schema.loaders.start({ id: ctx.key }),\n ]);\n if (!ctx.loader)\n ctx.loader = {};\n try {\n yield* next();\n if (!ctx.loader) {\n ctx.loader = {};\n }\n yield* updateStore([\n schema.loaders.success({ id: ctx.name, ...ctx.loader }),\n schema.loaders.success({ id: ctx.key, ...ctx.loader }),\n ]);\n }\n catch (err) {\n if (!ctx.loader) {\n ctx.loader = {};\n }\n yield* updateStore([\n schema.loaders.error({\n id: ctx.name,\n message: err.message,\n ...ctx.loader,\n }),\n schema.loaders.error({\n id: ctx.key,\n message: err.message,\n ...ctx.loader,\n }),\n ]);\n }\n finally {\n const loaders = yield* select((s) => schema.loaders.selectByIds(s, { ids: [ctx.name, ctx.key] }));\n const ids = loaders\n .filter((loader) => loader.status === \"loading\")\n .map((loader) => loader.id);\n if (ids.length > 0) {\n yield* updateStore(schema.loaders.resetByIds(ids));\n }\n }\n };\n}\nfunction defaultErrorFn(ctx) {\n const jso = ctx.json;\n if (jso.ok)\n return \"\";\n return jso.error?.message || \"\";\n}\n/**\n * This middleware will track the status of a fetch request.\n */\nexport function loaderApi({ schema, errorFn = defaultErrorFn }) {\n return function* trackLoading(ctx, next) {\n try {\n yield* updateStore([\n schema.loaders.start({ id: ctx.name }),\n schema.loaders.start({ id: ctx.key }),\n ]);\n if (!ctx.loader)\n ctx.loader = {};\n yield* next();\n if (!ctx.response) {\n yield* updateStore(schema.loaders.resetByIds([ctx.name, ctx.key]));\n return;\n }\n if (!ctx.loader) {\n ctx.loader = {};\n }\n if (!ctx.response.ok) {\n yield* updateStore([\n schema.loaders.error({\n id: ctx.name,\n message: errorFn(ctx),\n ...ctx.loader,\n }),\n schema.loaders.error({\n id: ctx.key,\n message: errorFn(ctx),\n ...ctx.loader,\n }),\n ]);\n return;\n }\n yield* updateStore([\n schema.loaders.success({ id: ctx.name, ...ctx.loader }),\n schema.loaders.success({ id: ctx.key, ...ctx.loader }),\n ]);\n }\n catch (err) {\n const message = err?.message || \"unknown exception\";\n yield* updateStore([\n schema.loaders.error({\n id: ctx.name,\n message,\n ...ctx.loader,\n }),\n schema.loaders.error({\n id: ctx.key,\n message,\n ...ctx.loader,\n }),\n ]);\n }\n finally {\n const loaders = yield* select((s) => schema.loaders.selectByIds(s, { ids: [ctx.name, ctx.key] }));\n const ids = loaders\n .filter((loader) => loader.status === \"loading\")\n .map((loader) => loader.id);\n yield* updateStore(schema.loaders.resetByIds(ids));\n }\n };\n}\n//# sourceMappingURL=store.js.map","import * as queryMdw from \"./query.js\";\nimport * as storeMdw from \"./store.js\";\nexport const mdw = { ...queryMdw, ...storeMdw };\n//# sourceMappingURL=mod.js.map","import { createAction, take } from \"./action.js\";\nimport { call, race, sleep, spawn } from \"./deps.js\";\nimport { getIdFromAction } from \"./action.js\";\nconst MS = 1000;\nconst SECONDS = 1 * MS;\nconst MINUTES = 60 * SECONDS;\nexport function poll(parentTimer = 5 * SECONDS, cancelType) {\n return function* poller(actionType, op) {\n const cancel = cancelType || actionType;\n function* fire(action, timer) {\n while (true) {\n yield* op(action);\n yield* sleep(timer);\n }\n }\n while (true) {\n const action = yield* take(actionType);\n const timer = action.payload?.timer || parentTimer;\n yield* race([\n fire(action, timer),\n take(`${cancel}`),\n ]);\n }\n };\n}\nexport const clearTimers = createAction(\"clear-timers\");\n/**\n * timer() will create a cache timer for each `key` inside\n * of a starfx api endpoint. `key` is a hash of the action type and payload.\n *\n * Why do we want this? If we have an api endpoint to fetch a single app: `fetchApp({ id: 1 })`\n * if we don't set a timer per key then all calls to `fetchApp` will be on a timer.\n * So if we call `fetchApp({ id: 1 })` and then `fetchApp({ id: 2 })` if we use a normal\n * cache timer then the second call will not send an http request.\n */\nexport function timer(timer = 5 * MINUTES) {\n return function* onTimer(actionType, op) {\n const map = {};\n function* activate(action) {\n yield* call(() => op(action));\n const idA = getIdFromAction(action);\n const matchFn = (act) => {\n if (act.type !== `${clearTimers}`)\n return false;\n if (!act.payload)\n return false;\n const ids = Array.isArray(act.payload) ? act.payload : [act.payload];\n return ids.some((id) => {\n if (id === \"*\") {\n return true;\n }\n if (typeof id === \"string\") {\n return idA === id;\n }\n else {\n return idA === getIdFromAction(id);\n }\n });\n };\n yield* race([\n sleep(timer),\n take(matchFn),\n ]);\n delete map[action.payload.key];\n }\n while (true) {\n const action = yield* take(`${actionType}`);\n const key = action.payload.key;\n if (!map[key]) {\n const task = yield* spawn(function* () {\n yield* activate(action);\n });\n map[key] = task;\n }\n }\n };\n}\n//# sourceMappingURL=supervisor.js.map","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(' ', ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nexport { DEBUG_BUILD };\n//# sourceMappingURL=debug-build.js.map\n","// This is a magic string replaced by rollup\n\nconst SDK_VERSION = \"8.45.0\" ;\n\nexport { SDK_VERSION };\n//# sourceMappingURL=version.js.map\n","import { SDK_VERSION } from './version.js';\n\n/** Get's the global object for the current JavaScript runtime */\nconst GLOBAL_OBJ = globalThis ;\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__[]` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nfunction getGlobalSingleton(name, creator, obj) {\n const gbl = (obj || GLOBAL_OBJ) ;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const versionedCarrier = (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});\n return versionedCarrier[name] || (versionedCarrier[name] = creator());\n}\n\nexport { GLOBAL_OBJ, getGlobalSingleton };\n//# sourceMappingURL=worldwide.js.map\n","/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nexport { DEBUG_BUILD };\n//# sourceMappingURL=debug-build.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { getGlobalSingleton, GLOBAL_OBJ } from './worldwide.js';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nconst CONSOLE_LEVELS = [\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'log',\n 'assert',\n 'trace',\n] ;\n\n/** This may be mutated by the console instrumentation. */\nconst originalConsoleMethods\n\n = {};\n\n/** JSDoc */\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nfunction consoleSandbox(callback) {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const console = GLOBAL_OBJ.console ;\n const wrappedFuncs = {};\n\n const wrappedLevels = Object.keys(originalConsoleMethods) ;\n\n // Restore all wrapped console methods\n wrappedLevels.forEach(level => {\n const originalConsoleMethod = originalConsoleMethods[level] ;\n wrappedFuncs[level] = console[level] ;\n console[level] = originalConsoleMethod;\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n wrappedLevels.forEach(level => {\n console[level] = wrappedFuncs[level] ;\n });\n }\n}\n\nfunction makeLogger() {\n let enabled = false;\n const logger = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n isEnabled: () => enabled,\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = (...args) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger ;\n}\n\n/**\n * This is a logger singleton which either logs things or no-ops if logging is not enabled.\n * The logger is a singleton on the carrier, to ensure that a consistent logger is used throughout the SDK.\n */\nconst logger = getGlobalSingleton('logger', makeLogger);\n\nexport { CONSOLE_LEVELS, consoleSandbox, logger, originalConsoleMethods };\n//# sourceMappingURL=logger.js.map\n","const STACKTRACE_FRAME_LIMIT = 50;\nconst UNKNOWN_FUNCTION = '?';\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STRIP_FRAME_REGEXP = /captureMessage|captureException/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nfunction createStackParser(...parsers) {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack, skipFirstLines = 0, framesToPop = 0) => {\n const frames = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirstLines; i < lines.length; i++) {\n const line = lines[i] ;\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT + framesToPop) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames.slice(framesToPop));\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nfunction stackParserFromStackParserOptions(stackParser) {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nfunction stripSentryFramesAndReverse(stack) {\n if (!stack.length) {\n return [];\n }\n\n const localStack = Array.from(stack);\n\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (/sentryWrapped/.test(getLastStackFrame(localStack).function || '')) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)\n if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || '')) {\n localStack.pop();\n\n // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')`\n // is produced within the hub itself, making it:\n //\n // Sentry.captureException()\n // getCurrentHub().captureException()\n //\n // instead of just the top `Sentry` call itself.\n // This forces us to possibly strip an additional frame in the exact same was as above.\n if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || '')) {\n localStack.pop();\n }\n }\n\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({\n ...frame,\n filename: frame.filename || getLastStackFrame(localStack).filename,\n function: frame.function || UNKNOWN_FUNCTION,\n }));\n}\n\nfunction getLastStackFrame(arr) {\n return arr[arr.length - 1] || {};\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nfunction getFunctionName(fn) {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Get's stack frames from an event without needing to check for undefined properties.\n */\nfunction getFramesFromEvent(event) {\n const exception = event.exception;\n\n if (exception) {\n const frames = [];\n try {\n // @ts-expect-error Object could be undefined\n exception.values.forEach(value => {\n // @ts-expect-error Value could be undefined\n if (value.stacktrace.frames) {\n // @ts-expect-error Value could be undefined\n frames.push(...value.stacktrace.frames);\n }\n });\n return frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n\nexport { UNKNOWN_FUNCTION, createStackParser, getFramesFromEvent, getFunctionName, stackParserFromStackParserOptions, stripSentryFramesAndReverse };\n//# sourceMappingURL=stacktrace.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { logger } from '../logger.js';\nimport { getFunctionName } from '../stacktrace.js';\n\n// We keep the handlers globally\nconst handlers = {};\nconst instrumented = {};\n\n/** Add a handler function. */\nfunction addHandler(type, handler) {\n handlers[type] = handlers[type] || [];\n (handlers[type] ).push(handler);\n}\n\n/**\n * Reset all instrumentation handlers.\n * This can be used by tests to ensure we have a clean slate of instrumentation handlers.\n */\nfunction resetInstrumentationHandlers() {\n Object.keys(handlers).forEach(key => {\n handlers[key ] = undefined;\n });\n}\n\n/** Maybe run an instrumentation function, unless it was already called. */\nfunction maybeInstrument(type, instrumentFn) {\n if (!instrumented[type]) {\n instrumented[type] = true;\n try {\n instrumentFn();\n } catch (e) {\n DEBUG_BUILD && logger.error(`Error while instrumenting ${type}`, e);\n }\n }\n}\n\n/** Trigger handlers for a given instrumentation type. */\nfunction triggerHandlers(type, data) {\n const typeHandlers = type && handlers[type];\n if (!typeHandlers) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\nexport { addHandler, maybeInstrument, resetInstrumentationHandlers, triggerHandlers };\n//# sourceMappingURL=handlers.js.map\n","import { GLOBAL_OBJ } from '../worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\nlet _oldOnErrorHandler = null;\n\n/**\n * Add an instrumentation handler for when an error is captured by the global error handler.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addGlobalErrorInstrumentationHandler(handler) {\n const type = 'error';\n addHandler(type, handler);\n maybeInstrument(type, instrumentError);\n}\n\nfunction instrumentError() {\n _oldOnErrorHandler = GLOBAL_OBJ.onerror;\n\n // Note: The reason we are doing window.onerror instead of window.addEventListener('error')\n // is that we are using this handler in the Loader Script, to handle buffered errors consistently\n GLOBAL_OBJ.onerror = function (\n msg,\n url,\n line,\n column,\n error,\n ) {\n const handlerData = {\n column,\n error,\n line,\n msg,\n url,\n };\n triggerHandlers('error', handlerData);\n\n if (_oldOnErrorHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n\nexport { addGlobalErrorInstrumentationHandler };\n//# sourceMappingURL=globalError.js.map\n","import { GLOBAL_OBJ } from '../worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\nlet _oldOnUnhandledRejectionHandler = null;\n\n/**\n * Add an instrumentation handler for when an unhandled promise rejection is captured.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addGlobalUnhandledRejectionInstrumentationHandler(\n handler,\n) {\n const type = 'unhandledrejection';\n addHandler(type, handler);\n maybeInstrument(type, instrumentUnhandledRejection);\n}\n\nfunction instrumentUnhandledRejection() {\n _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;\n\n // Note: The reason we are doing window.onunhandledrejection instead of window.addEventListener('unhandledrejection')\n // is that we are using this handler in the Loader Script, to handle buffered rejections consistently\n GLOBAL_OBJ.onunhandledrejection = function (e) {\n const handlerData = e;\n triggerHandlers('unhandledrejection', handlerData);\n\n if (_oldOnUnhandledRejectionHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n\nexport { addGlobalUnhandledRejectionInstrumentationHandler };\n//# sourceMappingURL=globalUnhandledRejection.js.map\n","import { SDK_VERSION } from './utils-hoist/version.js';\nimport { GLOBAL_OBJ } from './utils-hoist/worldwide.js';\n\n/**\n * An object that contains globally accessible properties and maintains a scope stack.\n * @hidden\n */\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nfunction getMainCarrier() {\n // This ensures a Sentry carrier exists\n getSentryCarrier(GLOBAL_OBJ);\n return GLOBAL_OBJ;\n}\n\n/** Will either get the existing sentry carrier, or create a new one. */\nfunction getSentryCarrier(carrier) {\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n\n // For now: First SDK that sets the .version property wins\n __SENTRY__.version = __SENTRY__.version || SDK_VERSION;\n\n // Intentionally populating and returning the version of \"this\" SDK instance\n // rather than what's set in .version so that \"this\" SDK always gets its carrier\n return (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});\n}\n\nexport { getMainCarrier, getSentryCarrier };\n//# sourceMappingURL=carrier.js.map\n","// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isError(wat) {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n case '[object WebAssembly.Exception]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat, className) {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isErrorEvent(wat) {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isDOMError(wat) {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isDOMException(wat) {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isString(wat) {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given string is parameterized\n * {@link isParameterizedString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isParameterizedString(wat) {\n return (\n typeof wat === 'object' &&\n wat !== null &&\n '__sentry_template_string__' in wat &&\n '__sentry_template_values__' in wat\n );\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isPrimitive(wat) {\n return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal, or a class instance.\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isPlainObject(wat) {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isEvent(wat) {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isElement(wat) {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isRegExp(wat) {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nfunction isThenable(wat) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isSyntheticEvent(wat) {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nfunction isInstanceOf(wat, base) {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n\n/**\n * Checks whether given value's type is a Vue ViewModel.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isVueViewModel(wat) {\n // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n return !!(typeof wat === 'object' && wat !== null && ((wat ).__isVue || (wat )._isVue));\n}\n\nexport { isDOMError, isDOMException, isElement, isError, isErrorEvent, isEvent, isInstanceOf, isParameterizedString, isPlainObject, isPrimitive, isRegExp, isString, isSyntheticEvent, isThenable, isVueViewModel };\n//# sourceMappingURL=is.js.map\n","import { isString } from './is.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nconst WINDOW = GLOBAL_OBJ ;\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction htmlTreeAsString(\n elem,\n options = {},\n) {\n if (!elem) {\n return '';\n }\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem ;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el, keyAttrs) {\n const elem = el\n\n;\n\n const out = [];\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n // @ts-expect-error WINDOW has HTMLElement\n if (WINDOW.HTMLElement) {\n // If using the component name annotation plugin, this value may be available on the DOM node\n if (elem instanceof HTMLElement && elem.dataset) {\n if (elem.dataset['sentryComponent']) {\n return elem.dataset['sentryComponent'];\n }\n if (elem.dataset['sentryElement']) {\n return elem.dataset['sentryElement'];\n }\n }\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n const className = elem.className;\n if (className && isString(className)) {\n const classes = className.split(/\\s+/);\n for (const c of classes) {\n out.push(`.${c}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (const k of allowedAttrs) {\n const attr = elem.getAttribute(k);\n if (attr) {\n out.push(`[${k}=\"${attr}\"]`);\n }\n }\n\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nfunction getLocationHref() {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existence of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getDomElement(selector) {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) ;\n }\n return null;\n}\n\n/**\n * Given a DOM element, traverses up the tree until it finds the first ancestor node\n * that has the `data-sentry-component` or `data-sentry-element` attribute with `data-sentry-component` taking\n * precedence. This attribute is added at build-time by projects that have the component name annotation plugin installed.\n *\n * @returns a string representation of the component for the provided DOM element, or `null` if not found\n */\nfunction getComponentName(elem) {\n // @ts-expect-error WINDOW has HTMLElement\n if (!WINDOW.HTMLElement) {\n return null;\n }\n\n let currentElem = elem ;\n const MAX_TRAVERSE_HEIGHT = 5;\n for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) {\n if (!currentElem) {\n return null;\n }\n\n if (currentElem instanceof HTMLElement) {\n if (currentElem.dataset['sentryComponent']) {\n return currentElem.dataset['sentryComponent'];\n }\n if (currentElem.dataset['sentryElement']) {\n return currentElem.dataset['sentryElement'];\n }\n }\n\n currentElem = currentElem.parentNode;\n }\n\n return null;\n}\n\nexport { getComponentName, getDomElement, getLocationHref, htmlTreeAsString };\n//# sourceMappingURL=browser.js.map\n","import { isVueViewModel, isString, isRegExp } from './is.js';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nfunction truncate(str, max = 0) {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nfunction snipLine(line, colno) {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\nfunction safeJoin(input, delimiter) {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/8981\n if (isVueViewModel(value)) {\n output.push('[VueViewModel]');\n } else {\n output.push(String(value));\n }\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nfunction isMatchingPattern(\n value,\n pattern,\n requireExactStringMatch = false,\n) {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nfunction stringMatchesSomePattern(\n testString,\n patterns = [],\n requireExactStringMatch = false,\n) {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n\nexport { isMatchingPattern, safeJoin, snipLine, stringMatchesSomePattern, truncate };\n//# sourceMappingURL=string.js.map\n","import { htmlTreeAsString } from './browser.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { isError, isEvent, isInstanceOf, isElement, isPlainObject, isPrimitive } from './is.js';\nimport { logger } from './logger.js';\nimport { truncate } from './string.js';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nfunction fill(source, name, replacementFactory) {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] ;\n const wrapped = replacementFactory(original) ;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n markFunctionWrapped(wrapped, original);\n }\n\n try {\n source[name] = wrapped;\n } catch (e) {\n DEBUG_BUILD && logger.log(`Failed to replace method \"${name}\" in object`, source);\n }\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nfunction addNonEnumerableProperty(obj, name, value) {\n try {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n } catch (o_O) {\n DEBUG_BUILD && logger.log(`Failed to add non-enumerable property \"${name}\" to object`, obj);\n }\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nfunction markFunctionWrapped(wrapped, original) {\n try {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n } catch (o_O) {} // eslint-disable-line no-empty\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction getOriginalFunction(func) {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n *\n * @deprecated This function is deprecated and will be removed in the next major version of the SDK.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction urlEncode(object) {\n return Object.entries(object)\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor\n * an Error.\n */\nfunction convertToPlainObject(value)\n\n {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj\n\n = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target) {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj) {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj )[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nfunction extractExceptionKeysForMessage(exception, maxLength = 40) {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n const firstKey = keys[0];\n\n if (!firstKey) {\n return '[object has no keys]';\n }\n\n if (firstKey.length >= maxLength) {\n return truncate(firstKey, maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nfunction dropUndefinedKeys(inputValue) {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue, memoizationMap) {\n if (isPojo(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal ;\n }\n\n const returnValue = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.getOwnPropertyNames(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue ;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal ;\n }\n\n const returnValue = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue ;\n }\n\n return inputValue;\n}\n\nfunction isPojo(input) {\n if (!isPlainObject(input)) {\n return false;\n }\n\n try {\n const name = (Object.getPrototypeOf(input) ).constructor.name;\n return !name || name === 'Object';\n } catch (e2) {\n return true;\n }\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nfunction objectify(wat) {\n let objectified;\n switch (true) {\n // this will catch both undefined and null\n case wat == undefined:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat ).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n\nexport { addNonEnumerableProperty, convertToPlainObject, dropUndefinedKeys, extractExceptionKeysForMessage, fill, getOriginalFunction, markFunctionWrapped, objectify, urlEncode };\n//# sourceMappingURL=object.js.map\n","import { GLOBAL_OBJ } from './worldwide.js';\n\nconst ONE_SECOND_IN_MS = 1000;\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n *\n * TODO(v8): Return type should be rounded.\n */\nfunction dateTimestampInSeconds() {\n return Date.now() / ONE_SECOND_IN_MS;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction createUnixTimestampInSecondsFunc() {\n const { performance } = GLOBAL_OBJ ;\n if (!performance || !performance.now) {\n return dateTimestampInSeconds;\n }\n\n // Some browser and environments don't have a timeOrigin, so we fallback to\n // using Date.now() to compute the starting time.\n const approxStartingTimeOrigin = Date.now() - performance.now();\n const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin;\n\n // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current\n // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.\n //\n // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the\n // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and\n // correct for this.\n // See: https://github.com/getsentry/sentry-javascript/issues/2590\n // See: https://github.com/mdn/content/issues/4713\n // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6\n return () => {\n return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;\n };\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nconst timestampInSeconds = createUnixTimestampInSecondsFunc();\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n *\n * @deprecated This variable will be removed in the next major version.\n */\nlet _browserPerformanceTimeOriginMode;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nconst browserPerformanceTimeOrigin = (() => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = GLOBAL_OBJ ;\n if (!performance || !performance.now) {\n // eslint-disable-next-line deprecation/deprecation\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n // eslint-disable-next-line deprecation/deprecation\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n // eslint-disable-next-line deprecation/deprecation\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n // eslint-disable-next-line deprecation/deprecation\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n\nexport { _browserPerformanceTimeOriginMode, browserPerformanceTimeOrigin, dateTimestampInSeconds, timestampInSeconds };\n//# sourceMappingURL=time.js.map\n","import { addNonEnumerableProperty } from './object.js';\nimport { snipLine } from './string.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nfunction uuid4() {\n const gbl = GLOBAL_OBJ ;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n let getRandomByte = () => Math.random() * 16;\n try {\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n if (crypto && crypto.getRandomValues) {\n getRandomByte = () => {\n // crypto.getRandomValues might return undefined instead of the typed array\n // in old Chromium versions (e.g. 23.0.1235.0 (151422))\n // However, `typedArray` is still filled in-place.\n // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray\n const typedArray = new Uint8Array(1);\n crypto.getRandomValues(typedArray);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return typedArray[0];\n };\n }\n } catch (_) {\n // some runtimes can crash invoking crypto\n // https://github.com/getsentry/sentry-javascript/issues/8935\n }\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event) {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nfunction getEventDescription(event) {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nfunction addExceptionTypeValue(event, value, type) {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nfunction addExceptionMechanism(event, newMechanism) {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\n\nfunction _parseInt(input) {\n return parseInt(input || '', 10);\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nfunction parseSemver(input) {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = _parseInt(match[1]);\n const minor = _parseInt(match[2]);\n const patch = _parseInt(match[3]);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nfunction addContextToFrame(lines, frame, linesOfContext = 5) {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line) => snipLine(line, 0));\n\n // We guard here to ensure this is not larger than the existing number of lines\n const lineIndex = Math.min(maxLines - 1, sourceLine);\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n frame.context_line = snipLine(lines[lineIndex], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nfunction checkOrSetAlreadyCaught(exception) {\n if (isAlreadyCaptured(exception)) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception , '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\nfunction isAlreadyCaptured(exception) {\n try {\n return (exception ).__sentry_captured__;\n } catch (e) {} // eslint-disable-line no-empty\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n *\n * @deprecated This function has been deprecated and will not be replaced.\n */\nfunction arrayify(maybeArray) {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n\nexport { addContextToFrame, addExceptionMechanism, addExceptionTypeValue, arrayify, checkOrSetAlreadyCaught, getEventDescription, parseSemver, uuid4 };\n//# sourceMappingURL=misc.js.map\n","import { isThenable } from './is.js';\n\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** SyncPromise internal states */\nvar States; (function (States) {\n /** Pending */\n const PENDING = 0; States[States[\"PENDING\"] = PENDING] = \"PENDING\";\n /** Resolved / OK */\n const RESOLVED = 1; States[States[\"RESOLVED\"] = RESOLVED] = \"RESOLVED\";\n /** Rejected / Error */\n const REJECTED = 2; States[States[\"REJECTED\"] = REJECTED] = \"REJECTED\";\n})(States || (States = {}));\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nfunction resolvedSyncPromise(value) {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nfunction rejectedSyncPromise(reason) {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise {\n\n constructor(\n executor,\n ) {SyncPromise.prototype.__init.call(this);SyncPromise.prototype.__init2.call(this);SyncPromise.prototype.__init3.call(this);SyncPromise.prototype.__init4.call(this);\n this._state = States.PENDING;\n this._handlers = [];\n\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n then(\n onfulfilled,\n onrejected,\n ) {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result );\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n catch(\n onrejected,\n ) {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n finally(onfinally) {\n return new SyncPromise((resolve, reject) => {\n let val;\n let isRejected;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val );\n });\n });\n }\n\n /** JSDoc */\n __init() {this._resolve = (value) => {\n this._setResult(States.RESOLVED, value);\n };}\n\n /** JSDoc */\n __init2() {this._reject = (reason) => {\n this._setResult(States.REJECTED, reason);\n };}\n\n /** JSDoc */\n __init3() {this._setResult = (state, value) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value ).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };}\n\n /** JSDoc */\n __init4() {this._executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n handler[1](this._value );\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };}\n}\n\nexport { SyncPromise, rejectedSyncPromise, resolvedSyncPromise };\n//# sourceMappingURL=syncpromise.js.map\n","import './utils-hoist/version.js';\nimport './utils-hoist/debug-build.js';\nimport './utils-hoist/logger.js';\nimport { dropUndefinedKeys } from './utils-hoist/object.js';\nimport { timestampInSeconds } from './utils-hoist/time.js';\nimport { uuid4 } from './utils-hoist/misc.js';\nimport './utils-hoist/syncpromise.js';\n\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nfunction makeSession(context) {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nfunction updateSession(session, context = {}) {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.abnormal_mechanism) {\n session.abnormal_mechanism = context.abnormal_mechanism;\n }\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nfunction closeSession(session, status) {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session) {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n abnormal_mechanism: session.abnormal_mechanism,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n\nexport { closeSession, makeSession, updateSession };\n//# sourceMappingURL=session.js.map\n","import { uuid4 } from './misc.js';\n\n/**\n * Returns a new minimal propagation context.\n *\n * @deprecated Use `generateTraceId` and `generateSpanId` instead.\n */\nfunction generatePropagationContext() {\n return {\n traceId: generateTraceId(),\n spanId: generateSpanId(),\n };\n}\n\n/**\n * Generate a random, valid trace ID.\n */\nfunction generateTraceId() {\n return uuid4();\n}\n\n/**\n * Generate a random, valid span ID.\n */\nfunction generateSpanId() {\n return uuid4().substring(16);\n}\n\nexport { generatePropagationContext, generateSpanId, generateTraceId };\n//# sourceMappingURL=propagationContext.js.map\n","/**\n * Shallow merge two objects.\n * Does not mutate the passed in objects.\n * Undefined/empty values in the merge object will overwrite existing values.\n *\n * By default, this merges 2 levels deep.\n */\nfunction merge(initialObj, mergeObj, levels = 2) {\n // If the merge value is not an object, or we have no merge levels left,\n // we just set the value to the merge value\n if (!mergeObj || typeof mergeObj !== 'object' || levels <= 0) {\n return mergeObj;\n }\n\n // If the merge object is an empty object, and the initial object is not undefined, we return the initial object\n if (initialObj && mergeObj && Object.keys(mergeObj).length === 0) {\n return initialObj;\n }\n\n // Clone object\n const output = { ...initialObj };\n\n // Merge values into output, resursively\n for (const key in mergeObj) {\n if (Object.prototype.hasOwnProperty.call(mergeObj, key)) {\n output[key] = merge(output[key], mergeObj[key], levels - 1);\n }\n }\n\n return output;\n}\n\nexport { merge };\n//# sourceMappingURL=merge.js.map\n","import { addNonEnumerableProperty } from '../utils-hoist/object.js';\n\nconst SCOPE_SPAN_FIELD = '_sentrySpan';\n\n/**\n * Set the active span for a given scope.\n * NOTE: This should NOT be used directly, but is only used internally by the trace methods.\n */\nfunction _setSpanForScope(scope, span) {\n if (span) {\n addNonEnumerableProperty(scope , SCOPE_SPAN_FIELD, span);\n } else {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete (scope )[SCOPE_SPAN_FIELD];\n }\n}\n\n/**\n * Get the active span for a given scope.\n * NOTE: This should NOT be used directly, but is only used internally by the trace methods.\n */\nfunction _getSpanForScope(scope) {\n return scope[SCOPE_SPAN_FIELD];\n}\n\nexport { _getSpanForScope, _setSpanForScope };\n//# sourceMappingURL=spanOnScope.js.map\n","import { updateSession } from './session.js';\nimport { isPlainObject } from './utils-hoist/is.js';\nimport { logger } from './utils-hoist/logger.js';\nimport { uuid4 } from './utils-hoist/misc.js';\nimport { generateTraceId, generateSpanId } from './utils-hoist/propagationContext.js';\nimport { dateTimestampInSeconds } from './utils-hoist/time.js';\nimport { merge } from './utils/merge.js';\nimport { _setSpanForScope, _getSpanForScope } from './utils/spanOnScope.js';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * Holds additional event information.\n */\nclass ScopeClass {\n /** Flag if notifying is happening. */\n\n /** Callback for client to receive scope changes. */\n\n /** Callback list that will be called during event processing. */\n\n /** Array of breadcrumbs. */\n\n /** User */\n\n /** Tags */\n\n /** Extra */\n\n /** Contexts */\n\n /** Attachments */\n\n /** Propagation Context for distributed tracing */\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n\n /** Fingerprint */\n\n /** Severity */\n\n /**\n * Transaction Name\n *\n * IMPORTANT: The transaction name on the scope has nothing to do with root spans/transaction objects.\n * It's purpose is to assign a transaction to the scope that's added to non-transaction events.\n */\n\n /** Session */\n\n /** Request Mode Session Status */\n // eslint-disable-next-line deprecation/deprecation\n\n /** The client on this scope */\n\n /** Contains the last event id of a captured event. */\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n this._propagationContext = {\n traceId: generateTraceId(),\n spanId: generateSpanId(),\n };\n }\n\n /**\n * @inheritDoc\n */\n clone() {\n const newScope = new ScopeClass();\n newScope._breadcrumbs = [...this._breadcrumbs];\n newScope._tags = { ...this._tags };\n newScope._extra = { ...this._extra };\n newScope._contexts = { ...this._contexts };\n if (this._contexts.flags) {\n // We need to copy the `values` array so insertions on a cloned scope\n // won't affect the original array.\n newScope._contexts.flags = {\n values: [...this._contexts.flags.values],\n };\n }\n\n newScope._user = this._user;\n newScope._level = this._level;\n newScope._session = this._session;\n newScope._transactionName = this._transactionName;\n newScope._fingerprint = this._fingerprint;\n newScope._eventProcessors = [...this._eventProcessors];\n newScope._requestSession = this._requestSession;\n newScope._attachments = [...this._attachments];\n newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n newScope._propagationContext = { ...this._propagationContext };\n newScope._client = this._client;\n newScope._lastEventId = this._lastEventId;\n\n _setSpanForScope(newScope, _getSpanForScope(this));\n\n return newScope;\n }\n\n /**\n * @inheritDoc\n */\n setClient(client) {\n this._client = client;\n }\n\n /**\n * @inheritDoc\n */\n setLastEventId(lastEventId) {\n this._lastEventId = lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n getClient() {\n return this._client ;\n }\n\n /**\n * @inheritDoc\n */\n lastEventId() {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n addScopeListener(callback) {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n addEventProcessor(callback) {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setUser(user) {\n // If null is passed we want to unset everything, but still define keys,\n // so that later down in the pipeline any existing values are cleared.\n this._user = user || {\n email: undefined,\n id: undefined,\n ip_address: undefined,\n username: undefined,\n };\n\n if (this._session) {\n updateSession(this._session, { user });\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getUser() {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n getRequestSession() {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n setRequestSession(requestSession) {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTags(tags) {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTag(key, value) {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setExtras(extras) {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setExtra(key, extra) {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setFingerprint(fingerprint) {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setLevel(level) {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTransactionName(name) {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setContext(key, context) {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setSession(session) {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getSession() {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n update(captureContext) {\n if (!captureContext) {\n return this;\n }\n\n const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;\n\n const [scopeInstance, requestSession] =\n scopeToMerge instanceof Scope\n ? // eslint-disable-next-line deprecation/deprecation\n [scopeToMerge.getScopeData(), scopeToMerge.getRequestSession()]\n : isPlainObject(scopeToMerge)\n ? [captureContext , (captureContext ).requestSession]\n : [];\n\n const { tags, extra, user, contexts, level, fingerprint = [], propagationContext } = scopeInstance || {};\n\n this._tags = { ...this._tags, ...tags };\n this._extra = { ...this._extra, ...extra };\n this._contexts = { ...this._contexts, ...contexts };\n\n if (user && Object.keys(user).length) {\n this._user = user;\n }\n\n if (level) {\n this._level = level;\n }\n\n if (fingerprint.length) {\n this._fingerprint = fingerprint;\n }\n\n if (propagationContext) {\n this._propagationContext = propagationContext;\n }\n\n if (requestSession) {\n this._requestSession = requestSession;\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n clear() {\n // client is not cleared here on purpose!\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._session = undefined;\n _setSpanForScope(this, undefined);\n this._attachments = [];\n this.setPropagationContext({ traceId: generateTraceId() });\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n addBreadcrumb(breadcrumb, maxBreadcrumbs) {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n\n const breadcrumbs = this._breadcrumbs;\n breadcrumbs.push(mergedBreadcrumb);\n this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getLastBreadcrumb() {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n clearBreadcrumbs() {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n addAttachment(attachment) {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n clearAttachments() {\n this._attachments = [];\n return this;\n }\n\n /** @inheritDoc */\n getScopeData() {\n return {\n breadcrumbs: this._breadcrumbs,\n attachments: this._attachments,\n contexts: this._contexts,\n tags: this._tags,\n extra: this._extra,\n user: this._user,\n level: this._level,\n fingerprint: this._fingerprint || [],\n eventProcessors: this._eventProcessors,\n propagationContext: this._propagationContext,\n sdkProcessingMetadata: this._sdkProcessingMetadata,\n transactionName: this._transactionName,\n span: _getSpanForScope(this),\n };\n }\n\n /**\n * @inheritDoc\n */\n setSDKProcessingMetadata(newData) {\n this._sdkProcessingMetadata = merge(this._sdkProcessingMetadata, newData, 2);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setPropagationContext(\n context,\n ) {\n this._propagationContext = {\n // eslint-disable-next-line deprecation/deprecation\n spanId: generateSpanId(),\n ...context,\n };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getPropagationContext() {\n return this._propagationContext;\n }\n\n /**\n * @inheritDoc\n */\n captureException(exception, hint) {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture exception!');\n return eventId;\n }\n\n const syntheticException = new Error('Sentry syntheticException');\n\n this._client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureMessage(message, level, hint) {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture message!');\n return eventId;\n }\n\n const syntheticException = new Error(message);\n\n this._client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureEvent(event, hint) {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture event!');\n return eventId;\n }\n\n this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n\n return eventId;\n }\n\n /**\n * This will be called on every set call.\n */\n _notifyScopeListeners() {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n}\n\n/**\n * Holds additional event information.\n */\nconst Scope = ScopeClass;\n\n/**\n * Holds additional event information.\n */\n\nexport { Scope };\n//# sourceMappingURL=scope.js.map\n","import { Scope } from './scope.js';\nimport { getGlobalSingleton } from './utils-hoist/worldwide.js';\n\n/** Get the default current scope. */\nfunction getDefaultCurrentScope() {\n return getGlobalSingleton('defaultCurrentScope', () => new Scope());\n}\n\n/** Get the default isolation scope. */\nfunction getDefaultIsolationScope() {\n return getGlobalSingleton('defaultIsolationScope', () => new Scope());\n}\n\nexport { getDefaultCurrentScope, getDefaultIsolationScope };\n//# sourceMappingURL=defaultScopes.js.map\n","import { getDefaultCurrentScope, getDefaultIsolationScope } from '../defaultScopes.js';\nimport { Scope } from '../scope.js';\nimport { isThenable } from '../utils-hoist/is.js';\nimport { getMainCarrier, getSentryCarrier } from '../carrier.js';\n\n/**\n * This is an object that holds a stack of scopes.\n */\nclass AsyncContextStack {\n\n constructor(scope, isolationScope) {\n let assignedScope;\n if (!scope) {\n assignedScope = new Scope();\n } else {\n assignedScope = scope;\n }\n\n let assignedIsolationScope;\n if (!isolationScope) {\n assignedIsolationScope = new Scope();\n } else {\n assignedIsolationScope = isolationScope;\n }\n\n // scope stack for domains or the process\n this._stack = [{ scope: assignedScope }];\n this._isolationScope = assignedIsolationScope;\n }\n\n /**\n * Fork a scope for the stack.\n */\n withScope(callback) {\n const scope = this._pushScope();\n\n let maybePromiseResult;\n try {\n maybePromiseResult = callback(scope);\n } catch (e) {\n this._popScope();\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n // @ts-expect-error - isThenable returns the wrong type\n return maybePromiseResult.then(\n res => {\n this._popScope();\n return res;\n },\n e => {\n this._popScope();\n throw e;\n },\n );\n }\n\n this._popScope();\n return maybePromiseResult;\n }\n\n /**\n * Get the client of the stack.\n */\n getClient() {\n return this.getStackTop().client ;\n }\n\n /**\n * Returns the scope of the top stack.\n */\n getScope() {\n return this.getStackTop().scope;\n }\n\n /**\n * Get the isolation scope for the stack.\n */\n getIsolationScope() {\n return this._isolationScope;\n }\n\n /**\n * Returns the topmost scope layer in the order domain > local > process.\n */\n getStackTop() {\n return this._stack[this._stack.length - 1] ;\n }\n\n /**\n * Push a scope to the stack.\n */\n _pushScope() {\n // We want to clone the content of prev scope\n const scope = this.getScope().clone();\n this._stack.push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * Pop a scope from the stack.\n */\n _popScope() {\n if (this._stack.length <= 1) return false;\n return !!this._stack.pop();\n }\n}\n\n/**\n * Get the global async context stack.\n * This will be removed during the v8 cycle and is only here to make migration easier.\n */\nfunction getAsyncContextStack() {\n const registry = getMainCarrier();\n const sentry = getSentryCarrier(registry);\n\n return (sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope()));\n}\n\nfunction withScope(callback) {\n return getAsyncContextStack().withScope(callback);\n}\n\nfunction withSetScope(scope, callback) {\n const stack = getAsyncContextStack() ;\n return stack.withScope(() => {\n stack.getStackTop().scope = scope;\n return callback(scope);\n });\n}\n\nfunction withIsolationScope(callback) {\n return getAsyncContextStack().withScope(() => {\n return callback(getAsyncContextStack().getIsolationScope());\n });\n}\n\n/**\n * Get the stack-based async context strategy.\n */\nfunction getStackAsyncContextStrategy() {\n return {\n withIsolationScope,\n withScope,\n withSetScope,\n withSetIsolationScope: (_isolationScope, callback) => {\n return withIsolationScope(callback);\n },\n getCurrentScope: () => getAsyncContextStack().getScope(),\n getIsolationScope: () => getAsyncContextStack().getIsolationScope(),\n };\n}\n\nexport { AsyncContextStack, getStackAsyncContextStrategy };\n//# sourceMappingURL=stackStrategy.js.map\n","import { getMainCarrier, getSentryCarrier } from '../carrier.js';\nimport { getStackAsyncContextStrategy } from './stackStrategy.js';\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nfunction setAsyncContextStrategy(strategy) {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n const sentry = getSentryCarrier(registry);\n sentry.acs = strategy;\n}\n\n/**\n * Get the current async context strategy.\n * If none has been setup, the default will be used.\n */\nfunction getAsyncContextStrategy(carrier) {\n const sentry = getSentryCarrier(carrier);\n\n if (sentry.acs) {\n return sentry.acs;\n }\n\n // Otherwise, use the default one (stack)\n return getStackAsyncContextStrategy();\n}\n\nexport { getAsyncContextStrategy, setAsyncContextStrategy };\n//# sourceMappingURL=index.js.map\n","import { getAsyncContextStrategy } from './asyncContext/index.js';\nimport { getMainCarrier } from './carrier.js';\nimport { Scope } from './scope.js';\nimport { dropUndefinedKeys } from './utils-hoist/object.js';\nimport { getGlobalSingleton } from './utils-hoist/worldwide.js';\n\n/**\n * Get the currently active scope.\n */\nfunction getCurrentScope() {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n return acs.getCurrentScope();\n}\n\n/**\n * Get the currently active isolation scope.\n * The isolation scope is active for the current execution context.\n */\nfunction getIsolationScope() {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n return acs.getIsolationScope();\n}\n\n/**\n * Get the global scope.\n * This scope is applied to _all_ events.\n */\nfunction getGlobalScope() {\n return getGlobalSingleton('globalScope', () => new Scope());\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n */\n\n/**\n * Either creates a new active scope, or sets the given scope as active scope in the given callback.\n */\nfunction withScope(\n ...rest\n) {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [scope, callback] = rest;\n\n if (!scope) {\n return acs.withScope(callback);\n }\n\n return acs.withSetScope(scope, callback);\n }\n\n return acs.withScope(rest[0]);\n}\n\n/**\n * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n */\n\n/**\n * Either creates a new active isolation scope, or sets the given isolation scope as active scope in the given callback.\n */\nfunction withIsolationScope(\n ...rest\n\n) {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [isolationScope, callback] = rest;\n\n if (!isolationScope) {\n return acs.withIsolationScope(callback);\n }\n\n return acs.withSetIsolationScope(isolationScope, callback);\n }\n\n return acs.withIsolationScope(rest[0]);\n}\n\n/**\n * Get the currently active client.\n */\nfunction getClient() {\n return getCurrentScope().getClient();\n}\n\n/**\n * Get a trace context for the given scope.\n */\nfunction getTraceContextFromScope(scope) {\n const propagationContext = scope.getPropagationContext();\n\n // TODO(v9): Use generateSpanId() instead of spanId\n // eslint-disable-next-line deprecation/deprecation\n const { traceId, spanId, parentSpanId } = propagationContext;\n\n const traceContext = dropUndefinedKeys({\n trace_id: traceId,\n span_id: spanId,\n parent_span_id: parentSpanId,\n });\n\n return traceContext;\n}\n\nexport { getClient, getCurrentScope, getGlobalScope, getIsolationScope, getTraceContextFromScope, withIsolationScope, withScope };\n//# sourceMappingURL=currentScopes.js.map\n","import { dropUndefinedKeys } from '../utils-hoist/object.js';\n\n/**\n * key: bucketKey\n * value: [exportKey, MetricSummary]\n */\n\nconst METRICS_SPAN_FIELD = '_sentryMetrics';\n\n/**\n * Fetches the metric summary if it exists for the passed span\n */\nfunction getMetricSummaryJsonForSpan(span) {\n const storage = (span )[METRICS_SPAN_FIELD];\n\n if (!storage) {\n return undefined;\n }\n const output = {};\n\n for (const [, [exportKey, summary]] of storage) {\n const arr = output[exportKey] || (output[exportKey] = []);\n arr.push(dropUndefinedKeys(summary));\n }\n\n return output;\n}\n\n/**\n * Updates the metric summary on a span.\n */\nfunction updateMetricSummaryOnSpan(\n span,\n metricType,\n sanitizedName,\n value,\n unit,\n tags,\n bucketKey,\n) {\n const existingStorage = (span )[METRICS_SPAN_FIELD];\n const storage =\n existingStorage ||\n ((span )[METRICS_SPAN_FIELD] = new Map());\n\n const exportKey = `${metricType}:${sanitizedName}@${unit}`;\n const bucketItem = storage.get(bucketKey);\n\n if (bucketItem) {\n const [, summary] = bucketItem;\n storage.set(bucketKey, [\n exportKey,\n {\n min: Math.min(summary.min, value),\n max: Math.max(summary.max, value),\n count: (summary.count += 1),\n sum: (summary.sum += value),\n tags: summary.tags,\n },\n ]);\n } else {\n storage.set(bucketKey, [\n exportKey,\n {\n min: value,\n max: value,\n count: 1,\n sum: value,\n tags,\n },\n ]);\n }\n}\n\nexport { getMetricSummaryJsonForSpan, updateMetricSummaryOnSpan };\n//# sourceMappingURL=metric-summary.js.map\n","/**\n * Use this attribute to represent the source of a span.\n * Should be one of: custom, url, route, view, component, task, unknown\n *\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source';\n\n/**\n * Use this attribute to represent the sample rate used for a span.\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate';\n\n/**\n * Use this attribute to represent the operation of a span.\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op';\n\n/**\n * Use this attribute to represent the origin of a span.\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';\n\n/** The reason why an idle span finished. */\nconst SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON = 'sentry.idle_span_finish_reason';\n\n/** The unit of a measurement, which may be stored as a TimedEvent. */\nconst SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = 'sentry.measurement_unit';\n\n/** The value of a measurement, which may be stored as a TimedEvent. */\nconst SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE = 'sentry.measurement_value';\n\n/**\n * The id of the profile that this span occurred in.\n */\nconst SEMANTIC_ATTRIBUTE_PROFILE_ID = 'sentry.profile_id';\n\nconst SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = 'sentry.exclusive_time';\n\nconst SEMANTIC_ATTRIBUTE_CACHE_HIT = 'cache.hit';\n\nconst SEMANTIC_ATTRIBUTE_CACHE_KEY = 'cache.key';\n\nconst SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE = 'cache.item_size';\n\n/** TODO: Remove these once we update to latest semantic conventions */\nconst SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD = 'http.request.method';\nconst SEMANTIC_ATTRIBUTE_URL_FULL = 'url.full';\n\nexport { SEMANTIC_ATTRIBUTE_CACHE_HIT, SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, SEMANTIC_ATTRIBUTE_CACHE_KEY, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD, SEMANTIC_ATTRIBUTE_PROFILE_ID, SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_URL_FULL };\n//# sourceMappingURL=semanticAttributes.js.map\n","const SPAN_STATUS_UNSET = 0;\nconst SPAN_STATUS_OK = 1;\nconst SPAN_STATUS_ERROR = 2;\n\n/**\n * Converts a HTTP status code into a sentry status with a message.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\n// https://develop.sentry.dev/sdk/event-payloads/span/\nfunction getSpanStatusFromHttpCode(httpStatus) {\n if (httpStatus < 400 && httpStatus >= 100) {\n return { code: SPAN_STATUS_OK };\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return { code: SPAN_STATUS_ERROR, message: 'unauthenticated' };\n case 403:\n return { code: SPAN_STATUS_ERROR, message: 'permission_denied' };\n case 404:\n return { code: SPAN_STATUS_ERROR, message: 'not_found' };\n case 409:\n return { code: SPAN_STATUS_ERROR, message: 'already_exists' };\n case 413:\n return { code: SPAN_STATUS_ERROR, message: 'failed_precondition' };\n case 429:\n return { code: SPAN_STATUS_ERROR, message: 'resource_exhausted' };\n case 499:\n return { code: SPAN_STATUS_ERROR, message: 'cancelled' };\n default:\n return { code: SPAN_STATUS_ERROR, message: 'invalid_argument' };\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return { code: SPAN_STATUS_ERROR, message: 'unimplemented' };\n case 503:\n return { code: SPAN_STATUS_ERROR, message: 'unavailable' };\n case 504:\n return { code: SPAN_STATUS_ERROR, message: 'deadline_exceeded' };\n default:\n return { code: SPAN_STATUS_ERROR, message: 'internal_error' };\n }\n }\n\n return { code: SPAN_STATUS_ERROR, message: 'unknown_error' };\n}\n\n/**\n * Sets the Http status attributes on the current span based on the http code.\n * Additionally, the span's status is updated, depending on the http code.\n */\nfunction setHttpStatus(span, httpStatus) {\n span.setAttribute('http.response.status_code', httpStatus);\n\n const spanStatus = getSpanStatusFromHttpCode(httpStatus);\n if (spanStatus.message !== 'unknown_error') {\n span.setStatus(spanStatus);\n }\n}\n\nexport { SPAN_STATUS_ERROR, SPAN_STATUS_OK, SPAN_STATUS_UNSET, getSpanStatusFromHttpCode, setHttpStatus };\n//# sourceMappingURL=spanstatus.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { isString } from './is.js';\nimport { logger } from './logger.js';\n\n/**\n * @deprecated Use a `\"baggage\"` string directly\n */\nconst BAGGAGE_HEADER_NAME = 'baggage';\n\nconst SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nconst SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\n\n/**\n * Max length of a serialized baggage string\n *\n * https://www.w3.org/TR/baggage/#limits\n */\nconst MAX_BAGGAGE_STRING_LENGTH = 8192;\n\n/**\n * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the \"sentry-\" prefixed values\n * from it.\n *\n * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.\n * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.\n */\nfunction baggageHeaderToDynamicSamplingContext(\n // Very liberal definition of what any incoming header might look like\n baggageHeader,\n) {\n const baggageObject = parseBaggageHeader(baggageHeader);\n\n if (!baggageObject) {\n return undefined;\n }\n\n // Read all \"sentry-\" prefixed values out of the baggage object and put it onto a dynamic sampling context object.\n const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => {\n if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {\n const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n acc[nonPrefixedKey] = value;\n }\n return acc;\n }, {});\n\n // Only return a dynamic sampling context object if there are keys in it.\n // A keyless object means there were no sentry values on the header, which means that there is no DSC.\n if (Object.keys(dynamicSamplingContext).length > 0) {\n return dynamicSamplingContext ;\n } else {\n return undefined;\n }\n}\n\n/**\n * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with \"sentry-\".\n *\n * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility\n * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is\n * `undefined` the function will return `undefined`.\n * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`\n * was `undefined`, or if `dynamicSamplingContext` didn't contain any values.\n */\nfunction dynamicSamplingContextToSentryBaggageHeader(\n // this also takes undefined for convenience and bundle size in other places\n dynamicSamplingContext,\n) {\n if (!dynamicSamplingContext) {\n return undefined;\n }\n\n // Prefix all DSC keys with \"sentry-\" and put them into a new object\n const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce(\n (acc, [dscKey, dscValue]) => {\n if (dscValue) {\n acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n }\n return acc;\n },\n {},\n );\n\n return objectToBaggageHeader(sentryPrefixedDSC);\n}\n\n/**\n * Take a baggage header and parse it into an object.\n */\nfunction parseBaggageHeader(\n baggageHeader,\n) {\n if (!baggageHeader || (!isString(baggageHeader) && !Array.isArray(baggageHeader))) {\n return undefined;\n }\n\n if (Array.isArray(baggageHeader)) {\n // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it\n return baggageHeader.reduce((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n Object.entries(currBaggageObject).forEach(([key, value]) => {\n acc[key] = value;\n });\n return acc;\n }, {});\n }\n\n return baggageHeaderToObject(baggageHeader);\n}\n\n/**\n * Will parse a baggage header, which is a simple key-value map, into a flat object.\n *\n * @param baggageHeader The baggage header to parse.\n * @returns a flat object containing all the key-value pairs from `baggageHeader`.\n */\nfunction baggageHeaderToObject(baggageHeader) {\n return baggageHeader\n .split(',')\n .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim())))\n .reduce((acc, [key, value]) => {\n if (key && value) {\n acc[key] = value;\n }\n return acc;\n }, {});\n}\n\n/**\n * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.\n *\n * @param object The object to turn into a baggage header.\n * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header\n * is not spec compliant.\n */\nfunction objectToBaggageHeader(object) {\n if (Object.keys(object).length === 0) {\n // An empty baggage header is not spec compliant: We return undefined.\n return undefined;\n }\n\n return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n );\n return baggageHeader;\n } else {\n return newBaggageHeader;\n }\n }, '');\n}\n\nexport { BAGGAGE_HEADER_NAME, MAX_BAGGAGE_STRING_LENGTH, SENTRY_BAGGAGE_KEY_PREFIX, SENTRY_BAGGAGE_KEY_PREFIX_REGEX, baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader, parseBaggageHeader };\n//# sourceMappingURL=baggage.js.map\n","import { getAsyncContextStrategy } from '../asyncContext/index.js';\nimport { getMainCarrier } from '../carrier.js';\nimport { getCurrentScope } from '../currentScopes.js';\nimport { getMetricSummaryJsonForSpan, updateMetricSummaryOnSpan } from '../metrics/metric-summary.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../semanticAttributes.js';\nimport { SPAN_STATUS_UNSET, SPAN_STATUS_OK } from '../tracing/spanstatus.js';\nimport { consoleSandbox } from '../utils-hoist/logger.js';\nimport { dropUndefinedKeys, addNonEnumerableProperty } from '../utils-hoist/object.js';\nimport { generateSpanId } from '../utils-hoist/propagationContext.js';\nimport { timestampInSeconds } from '../utils-hoist/time.js';\nimport { generateSentryTraceHeader } from '../utils-hoist/tracing.js';\nimport { _getSpanForScope } from './spanOnScope.js';\n\n// These are aligned with OpenTelemetry trace flags\nconst TRACE_FLAG_NONE = 0x0;\nconst TRACE_FLAG_SAMPLED = 0x1;\n\n// todo(v9): Remove this once we've stopped dropping spans via `beforeSendSpan`\nlet hasShownSpanDropWarning = false;\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in an event.\n * By default, this will only include trace_id, span_id & parent_span_id.\n * If `includeAllData` is true, it will also include data, op, status & origin.\n */\nfunction spanToTransactionTraceContext(span) {\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n const { data, op, parent_span_id, status, origin } = spanToJSON(span);\n\n return dropUndefinedKeys({\n parent_span_id,\n span_id,\n trace_id,\n data,\n op,\n status,\n origin,\n });\n}\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in a non-transaction event.\n */\nfunction spanToTraceContext(span) {\n const { spanId, traceId: trace_id, isRemote } = span.spanContext();\n\n // If the span is remote, we use a random/virtual span as span_id to the trace context,\n // and the remote span as parent_span_id\n const parent_span_id = isRemote ? spanId : spanToJSON(span).parent_span_id;\n const span_id = isRemote ? generateSpanId() : spanId;\n\n return dropUndefinedKeys({\n parent_span_id,\n span_id,\n trace_id,\n });\n}\n\n/**\n * Convert a Span to a Sentry trace header.\n */\nfunction spanToTraceHeader(span) {\n const { traceId, spanId } = span.spanContext();\n const sampled = spanIsSampled(span);\n return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\n/**\n * Convert a span time input into a timestamp in seconds.\n */\nfunction spanTimeInputToSeconds(input) {\n if (typeof input === 'number') {\n return ensureTimestampInSeconds(input);\n }\n\n if (Array.isArray(input)) {\n // See {@link HrTime} for the array-based time format\n return input[0] + input[1] / 1e9;\n }\n\n if (input instanceof Date) {\n return ensureTimestampInSeconds(input.getTime());\n }\n\n return timestampInSeconds();\n}\n\n/**\n * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.\n */\nfunction ensureTimestampInSeconds(timestamp) {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Convert a span to a JSON representation.\n */\n// Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).\n// This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.\n// And `spanToJSON` needs the Span class from `span.ts` to check here.\nfunction spanToJSON(span) {\n if (spanIsSentrySpan(span)) {\n return span.getSpanJSON();\n }\n\n try {\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n\n // Handle a span from @opentelemetry/sdk-base-trace's `Span` class\n if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) {\n const { attributes, startTime, name, endTime, parentSpanId, status } = span;\n\n return dropUndefinedKeys({\n span_id,\n trace_id,\n data: attributes,\n description: name,\n parent_span_id: parentSpanId,\n start_timestamp: spanTimeInputToSeconds(startTime),\n // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time\n timestamp: spanTimeInputToSeconds(endTime) || undefined,\n status: getStatusMessage(status),\n op: attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],\n origin: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] ,\n _metrics_summary: getMetricSummaryJsonForSpan(span),\n });\n }\n\n // Finally, at least we have `spanContext()`....\n return {\n span_id,\n trace_id,\n };\n } catch (e) {\n return {};\n }\n}\n\nfunction spanIsOpenTelemetrySdkTraceBaseSpan(span) {\n const castSpan = span ;\n return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status;\n}\n\n/** Exported only for tests. */\n\n/**\n * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.\n * :( So instead we approximate this by checking if it has the `getSpanJSON` method.\n */\nfunction spanIsSentrySpan(span) {\n return typeof (span ).getSpanJSON === 'function';\n}\n\n/**\n * Returns true if a span is sampled.\n * In most cases, you should just use `span.isRecording()` instead.\n * However, this has a slightly different semantic, as it also returns false if the span is finished.\n * So in the case where this distinction is important, use this method.\n */\nfunction spanIsSampled(span) {\n // We align our trace flags with the ones OpenTelemetry use\n // So we also check for sampled the same way they do.\n const { traceFlags } = span.spanContext();\n return traceFlags === TRACE_FLAG_SAMPLED;\n}\n\n/** Get the status message to use for a JSON representation of a span. */\nfunction getStatusMessage(status) {\n if (!status || status.code === SPAN_STATUS_UNSET) {\n return undefined;\n }\n\n if (status.code === SPAN_STATUS_OK) {\n return 'ok';\n }\n\n return status.message || 'unknown_error';\n}\n\nconst CHILD_SPANS_FIELD = '_sentryChildSpans';\nconst ROOT_SPAN_FIELD = '_sentryRootSpan';\n\n/**\n * Adds an opaque child span reference to a span.\n */\nfunction addChildSpanToSpan(span, childSpan) {\n // We store the root span reference on the child span\n // We need this for `getRootSpan()` to work\n const rootSpan = span[ROOT_SPAN_FIELD] || span;\n addNonEnumerableProperty(childSpan , ROOT_SPAN_FIELD, rootSpan);\n\n // We store a list of child spans on the parent span\n // We need this for `getSpanDescendants()` to work\n if (span[CHILD_SPANS_FIELD]) {\n span[CHILD_SPANS_FIELD].add(childSpan);\n } else {\n addNonEnumerableProperty(span, CHILD_SPANS_FIELD, new Set([childSpan]));\n }\n}\n\n/** This is only used internally by Idle Spans. */\nfunction removeChildSpanFromSpan(span, childSpan) {\n if (span[CHILD_SPANS_FIELD]) {\n span[CHILD_SPANS_FIELD].delete(childSpan);\n }\n}\n\n/**\n * Returns an array of the given span and all of its descendants.\n */\nfunction getSpanDescendants(span) {\n const resultSet = new Set();\n\n function addSpanChildren(span) {\n // This exit condition is required to not infinitely loop in case of a circular dependency.\n if (resultSet.has(span)) {\n return;\n // We want to ignore unsampled spans (e.g. non recording spans)\n } else if (spanIsSampled(span)) {\n resultSet.add(span);\n const childSpans = span[CHILD_SPANS_FIELD] ? Array.from(span[CHILD_SPANS_FIELD]) : [];\n for (const childSpan of childSpans) {\n addSpanChildren(childSpan);\n }\n }\n }\n\n addSpanChildren(span);\n\n return Array.from(resultSet);\n}\n\n/**\n * Returns the root span of a given span.\n */\nfunction getRootSpan(span) {\n return span[ROOT_SPAN_FIELD] || span;\n}\n\n/**\n * Returns the currently active span.\n */\nfunction getActiveSpan() {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n if (acs.getActiveSpan) {\n return acs.getActiveSpan();\n }\n\n return _getSpanForScope(getCurrentScope());\n}\n\n/**\n * Updates the metric summary on the currently active span\n */\nfunction updateMetricSummaryOnActiveSpan(\n metricType,\n sanitizedName,\n value,\n unit,\n tags,\n bucketKey,\n) {\n const span = getActiveSpan();\n if (span) {\n updateMetricSummaryOnSpan(span, metricType, sanitizedName, value, unit, tags, bucketKey);\n }\n}\n\n/**\n * Logs a warning once if `beforeSendSpan` is used to drop spans.\n *\n * todo(v9): Remove this once we've stopped dropping spans via `beforeSendSpan`.\n */\nfunction showSpanDropWarning() {\n if (!hasShownSpanDropWarning) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Sentry] Deprecation warning: Returning null from `beforeSendSpan` will be disallowed from SDK version 9.0.0 onwards. The callback will only support mutating spans. To drop certain spans, configure the respective integrations directly.',\n );\n });\n hasShownSpanDropWarning = true;\n }\n}\n\nexport { TRACE_FLAG_NONE, TRACE_FLAG_SAMPLED, addChildSpanToSpan, getActiveSpan, getRootSpan, getSpanDescendants, getStatusMessage, removeChildSpanFromSpan, showSpanDropWarning, spanIsSampled, spanTimeInputToSeconds, spanToJSON, spanToTraceContext, spanToTraceHeader, spanToTransactionTraceContext, updateMetricSummaryOnActiveSpan };\n//# sourceMappingURL=spanUtils.js.map\n","import { getClient } from '../currentScopes.js';\n\n// Treeshakable guard to remove all code related to tracing\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nfunction hasTracingEnabled(\n maybeOptions,\n) {\n if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {\n return false;\n }\n\n const client = getClient();\n const options = maybeOptions || (client && client.getOptions());\n // eslint-disable-next-line deprecation/deprecation\n return !!options && (options.enableTracing || 'tracesSampleRate' in options || 'tracesSampler' in options);\n}\n\nexport { hasTracingEnabled };\n//# sourceMappingURL=hasTracingEnabled.js.map\n","const DEFAULT_ENVIRONMENT = 'production';\n\nexport { DEFAULT_ENVIRONMENT };\n//# sourceMappingURL=constants.js.map\n","import { DEFAULT_ENVIRONMENT } from '../constants.js';\nimport { getClient } from '../currentScopes.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes.js';\nimport { baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader } from '../utils-hoist/baggage.js';\nimport { dropUndefinedKeys, addNonEnumerableProperty } from '../utils-hoist/object.js';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled.js';\nimport { getRootSpan, spanToJSON, spanIsSampled } from '../utils/spanUtils.js';\n\n/**\n * If you change this value, also update the terser plugin config to\n * avoid minification of the object property!\n */\nconst FROZEN_DSC_FIELD = '_frozenDsc';\n\n/**\n * Freeze the given DSC on the given span.\n */\nfunction freezeDscOnSpan(span, dsc) {\n const spanWithMaybeDsc = span ;\n addNonEnumerableProperty(spanWithMaybeDsc, FROZEN_DSC_FIELD, dsc);\n}\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatches the `createDsc` lifecycle hook as a side effect.\n */\nfunction getDynamicSamplingContextFromClient(trace_id, client) {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n\n const dsc = dropUndefinedKeys({\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n public_key,\n trace_id,\n }) ;\n\n client.emit('createDsc', dsc);\n\n return dsc;\n}\n\n/**\n * Get the dynamic sampling context for the currently active scopes.\n */\nfunction getDynamicSamplingContextFromScope(client, scope) {\n const propagationContext = scope.getPropagationContext();\n return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);\n}\n\n/**\n * Creates a dynamic sampling context from a span (and client and scope)\n *\n * @param span the span from which a few values like the root span name and sample rate are extracted.\n *\n * @returns a dynamic sampling context\n */\nfunction getDynamicSamplingContextFromSpan(span) {\n const client = getClient();\n if (!client) {\n return {};\n }\n\n const rootSpan = getRootSpan(span);\n\n // For core implementation, we freeze the DSC onto the span as a non-enumerable property\n const frozenDsc = (rootSpan )[FROZEN_DSC_FIELD];\n if (frozenDsc) {\n return frozenDsc;\n }\n\n // For OpenTelemetry, we freeze the DSC on the trace state\n const traceState = rootSpan.spanContext().traceState;\n const traceStateDsc = traceState && traceState.get('sentry.dsc');\n\n // If the span has a DSC, we want it to take precedence\n const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);\n\n if (dscOnTraceState) {\n return dscOnTraceState;\n }\n\n // Else, we generate it from the span\n const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);\n const jsonSpan = spanToJSON(rootSpan);\n const attributes = jsonSpan.data || {};\n const maybeSampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];\n\n if (maybeSampleRate != null) {\n dsc.sample_rate = `${maybeSampleRate}`;\n }\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n const name = jsonSpan.description;\n if (source !== 'url' && name) {\n dsc.transaction = name;\n }\n\n // How can we even land here with hasTracingEnabled() returning false?\n // Otel creates a Non-recording span in Tracing Without Performance mode when handling incoming requests\n // So we end up with an active span that is not sampled (neither positively nor negatively)\n if (hasTracingEnabled()) {\n dsc.sampled = String(spanIsSampled(rootSpan));\n }\n\n client.emit('createDsc', dsc, rootSpan);\n\n return dsc;\n}\n\n/**\n * Convert a Span to a baggage header.\n */\nfunction spanToBaggageHeader(span) {\n const dsc = getDynamicSamplingContextFromSpan(span);\n return dynamicSamplingContextToSentryBaggageHeader(dsc);\n}\n\nexport { freezeDscOnSpan, getDynamicSamplingContextFromClient, getDynamicSamplingContextFromScope, getDynamicSamplingContextFromSpan, spanToBaggageHeader };\n//# sourceMappingURL=dynamicSamplingContext.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { logger } from '../utils-hoist/logger.js';\n\n/**\n * Parse a sample rate from a given value.\n * This will either return a boolean or number sample rate, if the sample rate is valid (between 0 and 1).\n * If a string is passed, we try to convert it to a number.\n *\n * Any invalid sample rate will return `undefined`.\n */\nfunction parseSampleRate(sampleRate) {\n if (typeof sampleRate === 'boolean') {\n return Number(sampleRate);\n }\n\n const rate = typeof sampleRate === 'string' ? parseFloat(sampleRate) : sampleRate;\n if (typeof rate !== 'number' || isNaN(rate) || rate < 0 || rate > 1) {\n DEBUG_BUILD &&\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n sampleRate,\n )} of type ${JSON.stringify(typeof sampleRate)}.`,\n );\n return undefined;\n }\n\n return rate;\n}\n\nexport { parseSampleRate };\n//# sourceMappingURL=parseSampleRate.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { consoleSandbox, logger } from './logger.js';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol) {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nfunction dsnToString(dsn, withPassword = false) {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nfunction dsnFromString(str) {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n // This should be logged to the console\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\n });\n return undefined;\n }\n\n const [protocol, publicKey, pass = '', host = '', port = '', lastPath = ''] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() ;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey });\n}\n\nfunction dsnFromComponents(components) {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn) {\n if (!DEBUG_BUILD) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n logger.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nfunction makeDsn(from) {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n\nexport { dsnFromString, dsnToString, makeDsn };\n//# sourceMappingURL=dsn.js.map\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Helper to decycle json objects\n *\n * @deprecated This function is deprecated and will be removed in the next major version.\n */\n// TODO(v9): Move this function into normalize() directly\nfunction memoBuilder() {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner = hasWeakSet ? new WeakSet() : [];\n function memoize(obj) {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj) {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n\nexport { memoBuilder };\n//# sourceMappingURL=memo.js.map\n","import { isVueViewModel, isSyntheticEvent } from './is.js';\nimport { memoBuilder } from './memo.js';\nimport { convertToPlainObject } from './object.js';\nimport { getFunctionName } from './stacktrace.js';\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normalized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalize(input, depth = 100, maxProperties = +Infinity) {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nfunction normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object,\n // Default Node.js REPL depth\n depth = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize = 100 * 1024,\n) {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized ;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key,\n value,\n depth = +Infinity,\n maxProperties = +Infinity,\n // eslint-disable-next-line deprecation/deprecation\n memo = memoBuilder(),\n) {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n ['boolean', 'string'].includes(typeof value) ||\n (typeof value === 'number' && Number.isFinite(value))\n ) {\n return value ;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value )['__sentry_skip_normalization__']) {\n return value ;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value )['__sentry_override_normalization_depth__'] === 'number'\n ? ((value )['__sentry_override_normalization_depth__'] )\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value ;\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) ;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value );\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value,\n) {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value )._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n if (isVueViewModel(value)) {\n return '[VueViewModel]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && !Number.isFinite(value)) {\n return `[${value}]`;\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value) {\n const prototype = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value) {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value) {\n return utf8Length(JSON.stringify(value));\n}\n\n/**\n * Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint\n * across platforms and working directory.\n *\n * @param url The URL to be normalized.\n * @param basePath The application base path.\n * @returns The normalized URL.\n */\nfunction normalizeUrlToBase(url, basePath) {\n const escapedBase = basePath\n // Backslash to forward\n .replace(/\\\\/g, '/')\n // Escape RegExp special characters\n .replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n let newUrl = url;\n try {\n newUrl = decodeURI(url);\n } catch (_Oo) {\n // Sometime this breaks\n }\n return (\n newUrl\n .replace(/\\\\/g, '/')\n .replace(/webpack:\\/?/g, '') // Remove intermediate base path\n // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor\n .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///')\n );\n}\n\nexport { normalize, normalizeToSize, normalizeUrlToBase };\n//# sourceMappingURL=normalize.js.map\n","import { dsnToString } from './dsn.js';\nimport { normalize } from './normalize.js';\nimport { dropUndefinedKeys } from './object.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nfunction createEnvelope(headers, items = []) {\n return [headers, items] ;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nfunction addItemToEnvelope(envelope, newItem) {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] ;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nfunction forEachEnvelopeItem(\n envelope,\n callback,\n) {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nfunction envelopeContainsItemType(envelope, types) {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8 array.\n */\nfunction encodeUTF8(input) {\n return GLOBAL_OBJ.__SENTRY__ && GLOBAL_OBJ.__SENTRY__.encodePolyfill\n ? GLOBAL_OBJ.__SENTRY__.encodePolyfill(input)\n : new TextEncoder().encode(input);\n}\n\n/**\n * Decode a UTF8 array to string.\n */\nfunction decodeUTF8(input) {\n return GLOBAL_OBJ.__SENTRY__ && GLOBAL_OBJ.__SENTRY__.decodePolyfill\n ? GLOBAL_OBJ.__SENTRY__.decodePolyfill(input)\n : new TextDecoder().decode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nfunction serializeEnvelope(envelope) {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts = JSON.stringify(envHeaders);\n\n function append(next) {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.stringify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers) {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\n/**\n * Parses an envelope\n */\nfunction parseEnvelope(env) {\n let buffer = typeof env === 'string' ? encodeUTF8(env) : env;\n\n function readBinary(length) {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson() {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(decodeUTF8(readBinary(i))) ;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates envelope item for a single span\n */\nfunction createSpanEnvelopeItem(spanJson) {\n const spanHeaders = {\n type: 'span',\n };\n\n return [spanHeaders, spanJson];\n}\n\n/**\n * Creates attachment envelope items\n */\nfunction createAttachmentEnvelopeItem(attachment) {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n profile_chunk: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n feedback: 'feedback',\n span: 'span',\n statsd: 'metric_bucket',\n raw_security: 'security',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nfunction envelopeItemTypeToDataCategory(type) {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nfunction getSdkMetadataForEnvelopeHeader(metadataOrEvent) {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nfunction createEventEnvelopeHeaders(\n event,\n sdkInfo,\n tunnel,\n dsn,\n) {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n return {\n event_id: event.event_id ,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n\nexport { addItemToEnvelope, createAttachmentEnvelopeItem, createEnvelope, createEventEnvelopeHeaders, createSpanEnvelopeItem, envelopeContainsItemType, envelopeItemTypeToDataCategory, forEachEnvelopeItem, getSdkMetadataForEnvelopeHeader, parseEnvelope, serializeEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { getDynamicSamplingContextFromSpan } from './tracing/dynamicSamplingContext.js';\nimport { dsnToString } from './utils-hoist/dsn.js';\nimport { getSdkMetadataForEnvelopeHeader, createEnvelope, createEventEnvelopeHeaders, createSpanEnvelopeItem } from './utils-hoist/envelope.js';\nimport './utils-hoist/version.js';\nimport './utils-hoist/debug-build.js';\nimport './utils-hoist/logger.js';\nimport { spanToJSON, showSpanDropWarning } from './utils/spanUtils.js';\n\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n **/\nfunction enhanceEventWithSdkInfo(event, sdkInfo) {\n if (!sdkInfo) {\n return event;\n }\n event.sdk = event.sdk || {};\n event.sdk.name = event.sdk.name || sdkInfo.name;\n event.sdk.version = event.sdk.version || sdkInfo.version;\n event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])];\n event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])];\n return event;\n}\n\n/** Creates an envelope from a Session */\nfunction createSessionEnvelope(\n session,\n dsn,\n metadata,\n tunnel,\n) {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n const envelopeHeaders = {\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n };\n\n const envelopeItem =\n 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session.toJSON()];\n\n return createEnvelope(envelopeHeaders, [envelopeItem]);\n}\n\n/**\n * Create an Envelope from an event.\n */\nfunction createEventEnvelope(\n event,\n dsn,\n metadata,\n tunnel,\n) {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n\n /*\n Note: Due to TS, event.type may be `replay_event`, theoretically.\n In practice, we never call `createEventEnvelope` with `replay_event` type,\n and we'd have to adjust a looot of types to make this work properly.\n We want to avoid casting this around, as that could lead to bugs (e.g. when we add another type)\n So the safe choice is to really guard against the replay_event type here.\n */\n const eventType = event.type && event.type !== 'replay_event' ? event.type : 'event';\n\n enhanceEventWithSdkInfo(event, metadata && metadata.sdk);\n\n const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete event.sdkProcessingMetadata;\n\n const eventItem = [{ type: eventType }, event];\n return createEnvelope(envelopeHeaders, [eventItem]);\n}\n\n/**\n * Create envelope from Span item.\n *\n * Takes an optional client and runs spans through `beforeSendSpan` if available.\n */\nfunction createSpanEnvelope(spans, client) {\n function dscHasRequiredProps(dsc) {\n return !!dsc.trace_id && !!dsc.public_key;\n }\n\n // For the moment we'll obtain the DSC from the first span in the array\n // This might need to be changed if we permit sending multiple spans from\n // different segments in one envelope\n const dsc = getDynamicSamplingContextFromSpan(spans[0]);\n\n const dsn = client && client.getDsn();\n const tunnel = client && client.getOptions().tunnel;\n\n const headers = {\n sent_at: new Date().toISOString(),\n ...(dscHasRequiredProps(dsc) && { trace: dsc }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n };\n\n const beforeSendSpan = client && client.getOptions().beforeSendSpan;\n const convertToSpanJSON = beforeSendSpan\n ? (span) => {\n const spanJson = beforeSendSpan(spanToJSON(span) );\n if (!spanJson) {\n showSpanDropWarning();\n }\n return spanJson;\n }\n : (span) => spanToJSON(span);\n\n const items = [];\n for (const span of spans) {\n const spanJson = convertToSpanJSON(span);\n if (spanJson) {\n items.push(createSpanEnvelopeItem(spanJson));\n }\n }\n\n return createEnvelope(headers, items);\n}\n\nexport { createEventEnvelope, createSessionEnvelope, createSpanEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { isThenable } from './utils-hoist/is.js';\nimport { logger } from './utils-hoist/logger.js';\nimport { SyncPromise } from './utils-hoist/syncpromise.js';\n\n/**\n * Process an array of event processors, returning the processed event (or `null` if the event was dropped).\n */\nfunction notifyEventProcessors(\n processors,\n event,\n hint,\n index = 0,\n) {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) ;\n\n DEBUG_BUILD && processor.id && result === null && logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n}\n\nexport { notifyEventProcessors };\n//# sourceMappingURL=eventProcessors.js.map\n","import { GLOBAL_OBJ } from './worldwide.js';\n\nlet parsedStackResults;\nlet lastKeysCount;\nlet cachedFilenameDebugIds;\n\n/**\n * Returns a map of filenames to debug identifiers.\n */\nfunction getFilenameToDebugIdMap(stackParser) {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n if (!debugIdMap) {\n return {};\n }\n\n const debugIdKeys = Object.keys(debugIdMap);\n\n // If the count of registered globals hasn't changed since the last call, we\n // can just return the cached result.\n if (cachedFilenameDebugIds && debugIdKeys.length === lastKeysCount) {\n return cachedFilenameDebugIds;\n }\n\n lastKeysCount = debugIdKeys.length;\n\n // Build a map of filename -> debug_id.\n cachedFilenameDebugIds = debugIdKeys.reduce((acc, stackKey) => {\n if (!parsedStackResults) {\n parsedStackResults = {};\n }\n\n const result = parsedStackResults[stackKey];\n\n if (result) {\n acc[result[0]] = result[1];\n } else {\n const parsedStack = stackParser(stackKey);\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n const filename = stackFrame && stackFrame.filename;\n const debugId = debugIdMap[stackKey];\n\n if (filename && debugId) {\n acc[filename] = debugId;\n parsedStackResults[stackKey] = [filename, debugId];\n break;\n }\n }\n }\n\n return acc;\n }, {});\n\n return cachedFilenameDebugIds;\n}\n\n/**\n * Returns a list of debug images for the given resources.\n */\nfunction getDebugImagesForResources(\n stackParser,\n resource_paths,\n) {\n const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);\n\n if (!filenameDebugIdMap) {\n return [];\n }\n\n const images = [];\n for (const path of resource_paths) {\n if (path && filenameDebugIdMap[path]) {\n images.push({\n type: 'sourcemap',\n code_file: path,\n debug_id: filenameDebugIdMap[path] ,\n });\n }\n }\n\n return images;\n}\n\nexport { getDebugImagesForResources, getFilenameToDebugIdMap };\n//# sourceMappingURL=debug-ids.js.map\n","import { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext.js';\nimport { dropUndefinedKeys } from '../utils-hoist/object.js';\nimport { merge } from './merge.js';\nimport { spanToTraceContext, getRootSpan, spanToJSON } from './spanUtils.js';\n\n/**\n * Applies data from the scope to the event and runs all event processors on it.\n */\nfunction applyScopeDataToEvent(event, data) {\n const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;\n\n // Apply general data\n applyDataToEvent(event, data);\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (span) {\n applySpanToEvent(event, span);\n }\n\n applyFingerprintToEvent(event, fingerprint);\n applyBreadcrumbsToEvent(event, breadcrumbs);\n applySdkMetadataToEvent(event, sdkProcessingMetadata);\n}\n\n/** Merge data of two scopes together. */\nfunction mergeScopeData(data, mergeData) {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n sdkProcessingMetadata,\n breadcrumbs,\n fingerprint,\n eventProcessors,\n attachments,\n propagationContext,\n transactionName,\n span,\n } = mergeData;\n\n mergeAndOverwriteScopeData(data, 'extra', extra);\n mergeAndOverwriteScopeData(data, 'tags', tags);\n mergeAndOverwriteScopeData(data, 'user', user);\n mergeAndOverwriteScopeData(data, 'contexts', contexts);\n\n data.sdkProcessingMetadata = merge(data.sdkProcessingMetadata, sdkProcessingMetadata, 2);\n\n if (level) {\n data.level = level;\n }\n\n if (transactionName) {\n data.transactionName = transactionName;\n }\n\n if (span) {\n data.span = span;\n }\n\n if (breadcrumbs.length) {\n data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];\n }\n\n if (fingerprint.length) {\n data.fingerprint = [...data.fingerprint, ...fingerprint];\n }\n\n if (eventProcessors.length) {\n data.eventProcessors = [...data.eventProcessors, ...eventProcessors];\n }\n\n if (attachments.length) {\n data.attachments = [...data.attachments, ...attachments];\n }\n\n data.propagationContext = { ...data.propagationContext, ...propagationContext };\n}\n\n/**\n * Merges certain scope data. Undefined values will overwrite any existing values.\n * Exported only for tests.\n */\nfunction mergeAndOverwriteScopeData\n\n(data, prop, mergeVal) {\n data[prop] = merge(data[prop], mergeVal, 1);\n}\n\nfunction applyDataToEvent(event, data) {\n const { extra, tags, user, contexts, level, transactionName } = data;\n\n const cleanedExtra = dropUndefinedKeys(extra);\n if (cleanedExtra && Object.keys(cleanedExtra).length) {\n event.extra = { ...cleanedExtra, ...event.extra };\n }\n\n const cleanedTags = dropUndefinedKeys(tags);\n if (cleanedTags && Object.keys(cleanedTags).length) {\n event.tags = { ...cleanedTags, ...event.tags };\n }\n\n const cleanedUser = dropUndefinedKeys(user);\n if (cleanedUser && Object.keys(cleanedUser).length) {\n event.user = { ...cleanedUser, ...event.user };\n }\n\n const cleanedContexts = dropUndefinedKeys(contexts);\n if (cleanedContexts && Object.keys(cleanedContexts).length) {\n event.contexts = { ...cleanedContexts, ...event.contexts };\n }\n\n if (level) {\n event.level = level;\n }\n\n // transaction events get their `transaction` from the root span name\n if (transactionName && event.type !== 'transaction') {\n event.transaction = transactionName;\n }\n}\n\nfunction applyBreadcrumbsToEvent(event, breadcrumbs) {\n const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];\n event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;\n}\n\nfunction applySdkMetadataToEvent(event, sdkProcessingMetadata) {\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n ...sdkProcessingMetadata,\n };\n}\n\nfunction applySpanToEvent(event, span) {\n event.contexts = {\n trace: spanToTraceContext(span),\n ...event.contexts,\n };\n\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),\n ...event.sdkProcessingMetadata,\n };\n\n const rootSpan = getRootSpan(span);\n const transactionName = spanToJSON(rootSpan).description;\n if (transactionName && !event.transaction && event.type === 'transaction') {\n event.transaction = transactionName;\n }\n}\n\n/**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\nfunction applyFingerprintToEvent(event, fingerprint) {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint\n ? Array.isArray(event.fingerprint)\n ? event.fingerprint\n : [event.fingerprint]\n : [];\n\n // If we have something on the scope, then merge it with event\n if (fingerprint) {\n event.fingerprint = event.fingerprint.concat(fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n}\n\nexport { applyScopeDataToEvent, mergeAndOverwriteScopeData, mergeScopeData };\n//# sourceMappingURL=applyScopeDataToEvent.js.map\n","import { DEFAULT_ENVIRONMENT } from '../constants.js';\nimport { getGlobalScope } from '../currentScopes.js';\nimport { notifyEventProcessors } from '../eventProcessors.js';\nimport { Scope } from '../scope.js';\nimport { getFilenameToDebugIdMap } from '../utils-hoist/debug-ids.js';\nimport { uuid4, addExceptionMechanism } from '../utils-hoist/misc.js';\nimport { normalize } from '../utils-hoist/normalize.js';\nimport { truncate } from '../utils-hoist/string.js';\nimport { dateTimestampInSeconds } from '../utils-hoist/time.js';\nimport { mergeScopeData, applyScopeDataToEvent } from './applyScopeDataToEvent.js';\n\n/**\n * This type makes sure that we get either a CaptureContext, OR an EventHint.\n * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:\n * { user: { id: '123' }, mechanism: { handled: false } }\n */\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nfunction prepareEvent(\n options,\n event,\n hint,\n scope,\n client,\n isolationScope,\n) {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = options;\n const prepared = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n if (client) {\n client.emit('applyFrameMetadata', event);\n }\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n const finalScope = getFinalScope(scope, hint.captureContext);\n\n if (hint.mechanism) {\n addExceptionMechanism(prepared, hint.mechanism);\n }\n\n const clientEventProcessors = client ? client.getEventProcessors() : [];\n\n // This should be the last thing called, since we want that\n // {@link Scope.addEventProcessor} gets the finished prepared event.\n // Merge scope data together\n const data = getGlobalScope().getScopeData();\n\n if (isolationScope) {\n const isolationData = isolationScope.getScopeData();\n mergeScopeData(data, isolationData);\n }\n\n if (finalScope) {\n const finalScopeData = finalScope.getScopeData();\n mergeScopeData(data, finalScopeData);\n }\n\n const attachments = [...(hint.attachments || []), ...data.attachments];\n if (attachments.length) {\n hint.attachments = attachments;\n }\n\n applyScopeDataToEvent(prepared, data);\n\n const eventProcessors = [\n ...clientEventProcessors,\n // Run scope event processors _after_ all other processors\n ...data.eventProcessors,\n ];\n\n const result = notifyEventProcessors(eventProcessors, prepared, hint);\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n *\n * Only exported for tests.\n *\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event, options) {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n // empty strings do not make sense for environment, release, and dist\n // so we handle them the same as if they were not provided\n event.environment = event.environment || environment || DEFAULT_ENVIRONMENT;\n\n if (!event.release && release) {\n event.release = release;\n }\n\n if (!event.dist && dist) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nfunction applyDebugIds(event, stackParser) {\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception.values.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace.frames.forEach(frame => {\n if (filenameDebugIdMap && frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nfunction applyDebugMeta(event) {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap = {};\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception.values.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace.frames.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.entries(filenameDebugIdMap).forEach(([filename, debug_id]) => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id,\n });\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event, integrationNames) {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event, depth, maxBreadth) {\n if (!event) {\n return null;\n }\n\n const normalized = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n return {\n ...span,\n ...(span.data && {\n data: normalize(span.data, depth, maxBreadth),\n }),\n };\n });\n }\n\n // event.contexts.flags (FeatureFlagContext) stores context for our feature\n // flag integrations. It has a greater nesting depth than our other typed\n // Contexts, so we re-normalize with a fixed depth of 3 here. We do not want\n // to skip this in case of conflicting, user-provided context.\n if (event.contexts && event.contexts.flags && normalized.contexts) {\n normalized.contexts.flags = normalize(event.contexts.flags, 3, maxBreadth);\n }\n\n return normalized;\n}\n\nfunction getFinalScope(\n scope,\n captureContext,\n) {\n if (!captureContext) {\n return scope;\n }\n\n const finalScope = scope ? scope.clone() : new Scope();\n finalScope.update(captureContext);\n return finalScope;\n}\n\n/**\n * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.\n * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.\n */\nfunction parseEventHintOrCaptureContext(\n hint,\n) {\n if (!hint) {\n return undefined;\n }\n\n // If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext\n if (hintIsScopeOrFunction(hint)) {\n return { captureContext: hint };\n }\n\n if (hintIsScopeContext(hint)) {\n return {\n captureContext: hint,\n };\n }\n\n return hint;\n}\n\nfunction hintIsScopeOrFunction(\n hint,\n) {\n return hint instanceof Scope || typeof hint === 'function';\n}\n\nconst captureContextKeys = [\n 'user',\n 'level',\n 'extra',\n 'contexts',\n 'tags',\n 'fingerprint',\n 'requestSession',\n 'propagationContext',\n] ;\n\nfunction hintIsScopeContext(hint) {\n return Object.keys(hint).some(key => captureContextKeys.includes(key ));\n}\n\nexport { applyClientOptions, applyDebugIds, applyDebugMeta, parseEventHintOrCaptureContext, prepareEvent };\n//# sourceMappingURL=prepareEvent.js.map\n","import { DEFAULT_ENVIRONMENT } from './constants.js';\nimport { getCurrentScope, getIsolationScope, getClient, withIsolationScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { makeSession, updateSession, closeSession } from './session.js';\nimport { isThenable } from './utils-hoist/is.js';\nimport { logger } from './utils-hoist/logger.js';\nimport { uuid4 } from './utils-hoist/misc.js';\nimport { timestampInSeconds } from './utils-hoist/time.js';\nimport { GLOBAL_OBJ } from './utils-hoist/worldwide.js';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent.js';\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\nfunction captureException(exception, hint) {\n return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\n * @param captureContext Define the level of the message or pass in additional data to attach to the message.\n * @returns the id of the captured message.\n */\nfunction captureMessage(message, captureContext) {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n return getCurrentScope().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event The event to send to Sentry.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\nfunction captureEvent(event, hint) {\n return getCurrentScope().captureEvent(event, hint);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\nfunction setContext(name, context) {\n getIsolationScope().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nfunction setExtras(extras) {\n getIsolationScope().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nfunction setExtra(key, extra) {\n getIsolationScope().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nfunction setTags(tags) {\n getIsolationScope().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nfunction setTag(key, value) {\n getIsolationScope().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nfunction setUser(user) {\n getIsolationScope().setUser(user);\n}\n\n/**\n * The last error event id of the isolation scope.\n *\n * Warning: This function really returns the last recorded error event id on the current\n * isolation scope. If you call this function after handling a certain error and another error\n * is captured in between, the last one is returned instead of the one you might expect.\n * Also, ids of events that were never sent to Sentry (for example because\n * they were dropped in `beforeSend`) could be returned.\n *\n * @returns The last event id of the isolation scope.\n */\nfunction lastEventId() {\n return getIsolationScope().lastEventId();\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nfunction captureCheckIn(checkIn, upsertMonitorConfig) {\n const scope = getCurrentScope();\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n }\n\n return uuid4();\n}\n\n/**\n * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.\n *\n * @param monitorSlug The distinct slug of the monitor.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nfunction withMonitor(\n monitorSlug,\n callback,\n upsertMonitorConfig,\n) {\n const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);\n const now = timestampInSeconds();\n\n function finishCheckIn(status) {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n }\n\n return withIsolationScope(() => {\n let maybePromiseResult;\n try {\n maybePromiseResult = callback();\n } catch (e) {\n finishCheckIn('error');\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n finishCheckIn('ok');\n },\n e => {\n finishCheckIn('error');\n throw e;\n },\n );\n } else {\n finishCheckIn('ok');\n }\n\n return maybePromiseResult;\n });\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nasync function flush(timeout) {\n const client = getClient();\n if (client) {\n return client.flush(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nasync function close(timeout) {\n const client = getClient();\n if (client) {\n return client.close(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nfunction isInitialized() {\n return !!getClient();\n}\n\n/** If the SDK is initialized & enabled. */\nfunction isEnabled() {\n const client = getClient();\n return !!client && client.getOptions().enabled !== false && !!client.getTransport();\n}\n\n/**\n * Add an event processor.\n * This will be added to the current isolation scope, ensuring any event that is processed in the current execution\n * context will have the processor applied.\n */\nfunction addEventProcessor(callback) {\n getIsolationScope().addEventProcessor(callback);\n}\n\n/**\n * Start a session on the current isolation scope.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns the new active session\n */\nfunction startSession(context) {\n const client = getClient();\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: currentScope.getUser() || isolationScope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = isolationScope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n\n endSession();\n\n // Afterwards we set the new session on the scope\n isolationScope.setSession(session);\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession(session);\n\n return session;\n}\n\n/**\n * End the session on the current isolation scope.\n */\nfunction endSession() {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session) {\n closeSession(session);\n }\n _sendSessionUpdate();\n\n // the session is over; take it off of the scope\n isolationScope.setSession();\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession();\n}\n\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate() {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n const client = getClient();\n // TODO (v8): Remove currentScope and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session && client) {\n client.captureSession(session);\n }\n}\n\n/**\n * Sends the current session on the scope to Sentry\n *\n * @param end If set the session will be marked as exited and removed from the scope.\n * Defaults to `false`.\n */\nfunction captureSession(end = false) {\n // both send the update and pull the session from the scope\n if (end) {\n endSession();\n return;\n }\n\n // only send the update\n _sendSessionUpdate();\n}\n\nexport { addEventProcessor, captureCheckIn, captureEvent, captureException, captureMessage, captureSession, close, endSession, flush, isEnabled, isInitialized, lastEventId, setContext, setExtra, setExtras, setTag, setTags, setUser, startSession, withMonitor };\n//# sourceMappingURL=exports.js.map\n","import { makeDsn, dsnToString } from './utils-hoist/dsn.js';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn) {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn) {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn, sdkInfo) {\n const params = {\n sentry_version: SENTRY_API_VERSION,\n };\n\n if (dsn.publicKey) {\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n params.sentry_key = dsn.publicKey;\n }\n\n if (sdkInfo) {\n params.sentry_client = `${sdkInfo.name}/${sdkInfo.version}`;\n }\n\n return new URLSearchParams(params).toString();\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nfunction getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel, sdkInfo) {\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nfunction getReportDialogEndpoint(\n dsnLike,\n dialogOptions\n\n,\n) {\n const dsn = makeDsn(dsnLike);\n if (!dsn) {\n return '';\n }\n\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'onClose') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] )}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n\nexport { getEnvelopeEndpointWithUrlEncodedAuth, getReportDialogEndpoint };\n//# sourceMappingURL=api.js.map\n","import { getClient } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { logger } from './utils-hoist/logger.js';\n\nconst installedIntegrations = [];\n\n/** Map of integrations assigned to a client */\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preserve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations) {\n const integrationsByName = {};\n\n integrations.forEach((currentInstance) => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.values(integrationsByName);\n}\n\n/** Gets integrations to install */\nfunction getIntegrationsToSetup(options) {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach((integration) => {\n integration.isDefaultInstance = true;\n });\n\n let integrations;\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n const resolvedUserIntegrations = userIntegrations(defaultIntegrations);\n integrations = Array.isArray(resolvedUserIntegrations) ? resolvedUserIntegrations : [resolvedUserIntegrations];\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = finalIntegrations.findIndex(integration => integration.name === 'Debug');\n if (debugIndex > -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1) ;\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nfunction setupIntegrations(client, integrations) {\n const integrationIndex = {};\n\n integrations.forEach(integration => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(client, integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/**\n * Execute the `afterAllSetup` hooks of the given integrations.\n */\nfunction afterSetupIntegrations(client, integrations) {\n for (const integration of integrations) {\n // guard against empty provided integrations\n if (integration && integration.afterAllSetup) {\n integration.afterAllSetup(client);\n }\n }\n}\n\n/** Setup a single integration. */\nfunction setupIntegration(client, integration, integrationIndex) {\n if (integrationIndex[integration.name]) {\n DEBUG_BUILD && logger.log(`Integration skipped because it was already installed: ${integration.name}`);\n return;\n }\n integrationIndex[integration.name] = integration;\n\n // `setupOnce` is only called the first time\n if (installedIntegrations.indexOf(integration.name) === -1 && typeof integration.setupOnce === 'function') {\n integration.setupOnce();\n installedIntegrations.push(integration.name);\n }\n\n // `setup` is run for each client\n if (integration.setup && typeof integration.setup === 'function') {\n integration.setup(client);\n }\n\n if (typeof integration.preprocessEvent === 'function') {\n const callback = integration.preprocessEvent.bind(integration) ;\n client.on('preprocessEvent', (event, hint) => callback(event, hint, client));\n }\n\n if (typeof integration.processEvent === 'function') {\n const callback = integration.processEvent.bind(integration) ;\n\n const processor = Object.assign((event, hint) => callback(event, hint, client), {\n id: integration.name,\n });\n\n client.addEventProcessor(processor);\n }\n\n DEBUG_BUILD && logger.log(`Integration installed: ${integration.name}`);\n}\n\n/** Add an integration to the current scope's client. */\nfunction addIntegration(integration) {\n const client = getClient();\n\n if (!client) {\n DEBUG_BUILD && logger.warn(`Cannot add integration \"${integration.name}\" because no SDK Client is available.`);\n return;\n }\n\n client.addIntegration(integration);\n}\n\n/**\n * Define an integration function that can be used to create an integration instance.\n * Note that this by design hides the implementation details of the integration, as they are considered internal.\n */\nfunction defineIntegration(fn) {\n return fn;\n}\n\nexport { addIntegration, afterSetupIntegrations, defineIntegration, getIntegrationsToSetup, installedIntegrations, setupIntegration, setupIntegrations };\n//# sourceMappingURL=integration.js.map\n","import { createEnvelope } from './envelope.js';\nimport { dateTimestampInSeconds } from './time.js';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nfunction createClientReportEnvelope(\n discarded_events,\n dsn,\n timestamp,\n) {\n const clientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n\nexport { createClientReportEnvelope };\n//# sourceMappingURL=clientreport.js.map\n","/** An error emitted by Sentry SDKs and related utilities. */\nclass SentryError extends Error {\n /** Display name of this error instance. */\n\n constructor(\n message,\n logLevel = 'warn',\n ) {\n super(message);this.message = message;\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n\nexport { SentryError };\n//# sourceMappingURL=error.js.map\n","import { getEnvelopeEndpointWithUrlEncodedAuth } from './api.js';\nimport { getTraceContextFromScope, getCurrentScope, getIsolationScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope.js';\nimport { setupIntegration, afterSetupIntegrations, setupIntegrations } from './integration.js';\nimport { updateSession } from './session.js';\nimport { getDynamicSamplingContextFromScope } from './tracing/dynamicSamplingContext.js';\nimport { createClientReportEnvelope } from './utils-hoist/clientreport.js';\nimport { makeDsn, dsnToString } from './utils-hoist/dsn.js';\nimport { addItemToEnvelope, createAttachmentEnvelopeItem } from './utils-hoist/envelope.js';\nimport { SentryError } from './utils-hoist/error.js';\nimport { isPrimitive, isThenable, isPlainObject, isParameterizedString } from './utils-hoist/is.js';\nimport { logger, consoleSandbox } from './utils-hoist/logger.js';\nimport { uuid4, checkOrSetAlreadyCaught } from './utils-hoist/misc.js';\nimport { resolvedSyncPromise, SyncPromise, rejectedSyncPromise } from './utils-hoist/syncpromise.js';\nimport { parseSampleRate } from './utils/parseSampleRate.js';\nimport { prepareEvent } from './utils/prepareEvent.js';\nimport { showSpanDropWarning } from './utils/spanUtils.js';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nclass BaseClient {\n /** Options passed to the SDK. */\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n\n /** Array of set up integrations. */\n\n /** Number of calls being processed */\n\n /** Holds flushable */\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n constructor(options) {\n this._options = options;\n this._integrations = {};\n this._numProcessing = 0;\n this._outcomes = {};\n this._hooks = {};\n this._eventProcessors = [];\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n DEBUG_BUILD && logger.warn('No DSN provided, client will not send events.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(\n this._dsn,\n options.tunnel,\n options._metadata ? options._metadata.sdk : undefined,\n );\n this._transport = options.transport({\n tunnel: this._options.tunnel,\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n\n // TODO(v9): Remove this deprecation warning\n const tracingOptions = ['enableTracing', 'tracesSampleRate', 'tracesSampler'] ;\n const undefinedOption = tracingOptions.find(option => option in options && options[option] == undefined);\n if (undefinedOption) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n `[Sentry] Deprecation warning: \\`${undefinedOption}\\` is set to undefined, which leads to tracing being enabled. In v9, a value of \\`undefined\\` will result in tracing being disabled.`,\n );\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n captureException(exception, hint, scope) {\n const eventId = uuid4();\n\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return eventId;\n }\n\n const hintWithEventId = {\n event_id: eventId,\n ...hint,\n };\n\n this._process(\n this.eventFromException(exception, hintWithEventId).then(event =>\n this._captureEvent(event, hintWithEventId, scope),\n ),\n );\n\n return hintWithEventId.event_id;\n }\n\n /**\n * @inheritDoc\n */\n captureMessage(\n message,\n level,\n hint,\n currentScope,\n ) {\n const hintWithEventId = {\n event_id: uuid4(),\n ...hint,\n };\n\n const eventMessage = isParameterizedString(message) ? message : String(message);\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(eventMessage, level, hintWithEventId)\n : this.eventFromException(message, hintWithEventId);\n\n this._process(promisedEvent.then(event => this._captureEvent(event, hintWithEventId, currentScope)));\n\n return hintWithEventId.event_id;\n }\n\n /**\n * @inheritDoc\n */\n captureEvent(event, hint, currentScope) {\n const eventId = uuid4();\n\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return eventId;\n }\n\n const hintWithEventId = {\n event_id: eventId,\n ...hint,\n };\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanScope = sdkProcessingMetadata.capturedSpanScope;\n\n this._process(this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope));\n\n return hintWithEventId.event_id;\n }\n\n /**\n * @inheritDoc\n */\n captureSession(session) {\n if (!(typeof session.release === 'string')) {\n DEBUG_BUILD && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n getDsn() {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n getOptions() {\n return this._options;\n }\n\n /**\n * @see SdkMetadata\n *\n * @return The metadata of the SDK\n */\n getSdkMetadata() {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n getTransport() {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n flush(timeout) {\n const transport = this._transport;\n if (transport) {\n this.emit('flush');\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n close(timeout) {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n this.emit('close');\n return result;\n });\n }\n\n /** Get all installed event processors. */\n getEventProcessors() {\n return this._eventProcessors;\n }\n\n /** @inheritDoc */\n addEventProcessor(eventProcessor) {\n this._eventProcessors.push(eventProcessor);\n }\n\n /** @inheritdoc */\n init() {\n if (\n this._isEnabled() ||\n // Force integrations to be setup even if no DSN was set when we have\n // Spotlight enabled. This is particularly important for browser as we\n // don't support the `spotlight` option there and rely on the users\n // adding the `spotlightBrowserIntegration()` to their integrations which\n // wouldn't get initialized with the check below when there's no DSN set.\n this._options.integrations.some(({ name }) => name.startsWith('Spotlight'))\n ) {\n this._setupIntegrations();\n }\n }\n\n /**\n * Gets an installed integration by its name.\n *\n * @returns The installed integration or `undefined` if no integration with that `name` was installed.\n */\n getIntegrationByName(integrationName) {\n return this._integrations[integrationName] ;\n }\n\n /**\n * @inheritDoc\n */\n addIntegration(integration) {\n const isAlreadyInstalled = this._integrations[integration.name];\n\n // This hook takes care of only installing if not already installed\n setupIntegration(this, integration, this._integrations);\n // Here we need to check manually to make sure to not run this multiple times\n if (!isAlreadyInstalled) {\n afterSetupIntegrations(this, [integration]);\n }\n }\n\n /**\n * @inheritDoc\n */\n sendEvent(event, hint = {}) {\n this.emit('beforeSendEvent', event, hint);\n\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(env, createAttachmentEnvelopeItem(attachment));\n }\n\n const promise = this.sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n\n /**\n * @inheritDoc\n */\n sendSession(session) {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(env);\n }\n\n /**\n * @inheritDoc\n */\n recordDroppedEvent(reason, category, eventOrCount) {\n if (this._options.sendClientReports) {\n // TODO v9: We do not need the `event` passed as third argument anymore, and can possibly remove this overload\n // If event is passed as third argument, we assume this is a count of 1\n const count = typeof eventOrCount === 'number' ? eventOrCount : 1;\n\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n DEBUG_BUILD && logger.log(`Recording outcome: \"${key}\"${count > 1 ? ` (${count} times)` : ''}`);\n this._outcomes[key] = (this._outcomes[key] || 0) + count;\n }\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n /* eslint-disable @typescript-eslint/unified-signatures */\n\n /** @inheritdoc */\n\n /** @inheritdoc */\n on(hook, callback) {\n const hooks = (this._hooks[hook] = this._hooks[hook] || []);\n\n // @ts-expect-error We assume the types are correct\n hooks.push(callback);\n\n // This function returns a callback execution handler that, when invoked,\n // deregisters a callback. This is crucial for managing instances where callbacks\n // need to be unregistered to prevent self-referencing in callback closures,\n // ensuring proper garbage collection.\n return () => {\n // @ts-expect-error We assume the types are correct\n const cbIndex = hooks.indexOf(callback);\n if (cbIndex > -1) {\n hooks.splice(cbIndex, 1);\n }\n };\n }\n\n /** @inheritdoc */\n\n /** @inheritdoc */\n emit(hook, ...rest) {\n const callbacks = this._hooks[hook];\n if (callbacks) {\n callbacks.forEach(callback => callback(...rest));\n }\n }\n\n /**\n * @inheritdoc\n */\n sendEnvelope(envelope) {\n this.emit('beforeEnvelope', envelope);\n\n if (this._isEnabled() && this._transport) {\n return this._transport.send(envelope).then(null, reason => {\n DEBUG_BUILD && logger.error('Error while sending envelope:', reason);\n return reason;\n });\n }\n\n DEBUG_BUILD && logger.error('Transport disabled');\n\n return resolvedSyncPromise({});\n }\n\n /* eslint-enable @typescript-eslint/unified-signatures */\n\n /** Setup integrations for this client. */\n _setupIntegrations() {\n const { integrations } = this._options;\n this._integrations = setupIntegrations(this, integrations);\n afterSetupIntegrations(this, integrations);\n }\n\n /** Updates existing session based on the provided event */\n _updateSessionFromEvent(session, event) {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n _isClientDoneProcessing(timeout) {\n return new SyncPromise(resolve => {\n let ticked = 0;\n const tick = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a transport is present. */\n _isEnabled() {\n return this.getOptions().enabled !== false && this._transport !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param currentScope A scope containing event metadata.\n * @returns A new event with more information.\n */\n _prepareEvent(\n event,\n hint,\n currentScope = getCurrentScope(),\n isolationScope = getIsolationScope(),\n ) {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n\n this.emit('preprocessEvent', event, hint);\n\n if (!event.type) {\n isolationScope.setLastEventId(event.event_id || hint.event_id);\n }\n\n return prepareEvent(options, event, hint, currentScope, this, isolationScope).then(evt => {\n if (evt === null) {\n return evt;\n }\n\n evt.contexts = {\n trace: getTraceContextFromScope(currentScope),\n ...evt.contexts,\n };\n\n const dynamicSamplingContext = getDynamicSamplingContextFromScope(this, currentScope);\n\n evt.sdkProcessingMetadata = {\n dynamicSamplingContext,\n ...evt.sdkProcessingMetadata,\n };\n\n return evt;\n });\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n _captureEvent(event, hint = {}, scope) {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (DEBUG_BUILD) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason ;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param currentScope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n _processEvent(event, hint, currentScope) {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n const parsedSampleRate = typeof sampleRate === 'undefined' ? undefined : parseSampleRate(sampleRate);\n if (isError && typeof parsedSampleRate === 'number' && Math.random() > parsedSampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanIsolationScope = sdkProcessingMetadata.capturedSpanIsolationScope;\n\n return this._prepareEvent(event, hint, currentScope, capturedSpanIsolationScope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data ).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(this, options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n if (isTransaction) {\n const spans = event.spans || [];\n // the transaction itself counts as one span, plus all the child spans that are added\n const spanCount = 1 + spans.length;\n this.recordDroppedEvent('before_send', 'span', spanCount);\n }\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = currentScope && currentScope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n if (isTransaction) {\n const spanCountBefore =\n (processedEvent.sdkProcessingMetadata && processedEvent.sdkProcessingMetadata.spanCountBeforeProcessing) ||\n 0;\n const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0;\n\n const droppedSpanCount = spanCountBefore - spanCountAfter;\n if (droppedSpanCount > 0) {\n this.recordDroppedEvent('before_send', 'span', droppedSpanCount);\n }\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n _process(promise) {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n _clearOutcomes() {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.entries(outcomes).map(([key, quantity]) => {\n const [reason, category] = key.split(':') ;\n return {\n reason,\n category,\n quantity,\n };\n });\n }\n\n /**\n * Sends client reports as an envelope.\n */\n _flushOutcomes() {\n DEBUG_BUILD && logger.log('Flushing outcomes...');\n\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n DEBUG_BUILD && logger.log('No outcomes to send');\n return;\n }\n\n // This is really the only place where we want to check for a DSN and only send outcomes then\n if (!this._dsn) {\n DEBUG_BUILD && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n DEBUG_BUILD && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult,\n beforeSendLabel,\n) {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n client,\n options,\n event,\n hint,\n) {\n const { beforeSend, beforeSendTransaction, beforeSendSpan } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event)) {\n if (event.spans && beforeSendSpan) {\n const processedSpans = [];\n for (const span of event.spans) {\n const processedSpan = beforeSendSpan(span);\n if (processedSpan) {\n processedSpans.push(processedSpan);\n } else {\n showSpanDropWarning();\n client.recordDroppedEvent('before_send', 'span');\n }\n }\n event.spans = processedSpans;\n }\n\n if (beforeSendTransaction) {\n if (event.spans) {\n // We store the # of spans before processing in SDK metadata,\n // so we can compare it afterwards to determine how many spans were dropped\n const spanCountBefore = event.spans.length;\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n spanCountBeforeProcessing: spanCountBefore,\n };\n }\n return beforeSendTransaction(event, hint);\n }\n }\n\n return event;\n}\n\nfunction isErrorEvent(event) {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event) {\n return event.type === 'transaction';\n}\n\nexport { BaseClient };\n//# sourceMappingURL=baseclient.js.map\n","import { getCurrentScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { logger, consoleSandbox } from './utils-hoist/logger.js';\n\n/** A class object that can instantiate Client objects. */\n\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\nfunction initAndBind(\n clientClass,\n options,\n) {\n if (options.debug === true) {\n if (DEBUG_BUILD) {\n logger.enable();\n } else {\n // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n });\n }\n }\n const scope = getCurrentScope();\n scope.update(options.initialScope);\n\n const client = new clientClass(options);\n setCurrentClient(client);\n client.init();\n return client;\n}\n\n/**\n * Make the given client the current client.\n */\nfunction setCurrentClient(client) {\n getCurrentScope().setClient(client);\n}\n\nexport { initAndBind, setCurrentClient };\n//# sourceMappingURL=sdk.js.map\n","import { SentryError } from './error.js';\nimport { rejectedSyncPromise, SyncPromise, resolvedSyncPromise } from './syncpromise.js';\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nfunction makePromiseBuffer(limit) {\n const buffer = [];\n\n function isReady() {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task) {\n return buffer.splice(buffer.indexOf(task), 1)[0] || Promise.resolve(undefined);\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer) {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout) {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n\nexport { makePromiseBuffer };\n//# sourceMappingURL=promisebuffer.js.map\n","// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\n\nconst DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nfunction parseRetryAfterHeader(header, now = Date.now()) {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nfunction disabledUntil(limits, dataCategory) {\n return limits[dataCategory] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nfunction isRateLimited(limits, dataCategory, now = Date.now()) {\n return disabledUntil(limits, dataCategory) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nfunction updateRateLimits(\n limits,\n { statusCode, headers },\n now = Date.now(),\n) {\n const updatedRateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n * Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected.\n * Only present if rate limit applies to the metric_bucket data category.\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories, , , namespaces] = limit.split(':', 5) ;\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n if (category === 'metric_bucket') {\n // namespaces will be present when category === 'metric_bucket'\n if (!namespaces || namespaces.split(';').includes('custom')) {\n updatedRateLimits[category] = now + delay;\n }\n } else {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n\nexport { DEFAULT_RETRY_AFTER, disabledUntil, isRateLimited, parseRetryAfterHeader, updateRateLimits };\n//# sourceMappingURL=ratelimit.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { forEachEnvelopeItem, envelopeItemTypeToDataCategory, createEnvelope, serializeEnvelope } from '../utils-hoist/envelope.js';\nimport { SentryError } from '../utils-hoist/error.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { makePromiseBuffer } from '../utils-hoist/promisebuffer.js';\nimport { isRateLimited, updateRateLimits } from '../utils-hoist/ratelimit.js';\nimport { resolvedSyncPromise } from '../utils-hoist/syncpromise.js';\n\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 64;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nfunction createTransport(\n options,\n makeRequest,\n buffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n) {\n let rateLimits = {};\n const flush = (timeout) => buffer.drain(timeout);\n\n function send(envelope) {\n const filteredEnvelopeItems = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const dataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, dataCategory)) {\n const event = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', dataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise({});\n }\n\n const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems );\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason) => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = () =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n DEBUG_BUILD && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n DEBUG_BUILD && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise({});\n } else {\n throw error;\n }\n },\n );\n }\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item, type) {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item )[1] : undefined;\n}\n\nexport { DEFAULT_TRANSPORT_BUFFER_SIZE, createTransport };\n//# sourceMappingURL=base.js.map\n","import { SDK_VERSION } from '../utils-hoist/version.js';\n\n/**\n * A builder for the SDK metadata in the options for the SDK initialization.\n *\n * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.\n * We don't extract it for bundle size reasons.\n * @see https://github.com/getsentry/sentry-javascript/pull/7404\n * @see https://github.com/getsentry/sentry-javascript/pull/4196\n *\n * If you make changes to this function consider updating the others as well.\n *\n * @param options SDK options object that gets mutated\n * @param names list of package names\n */\nfunction applySdkMetadata(options, name, names = [name], source = 'npm') {\n const metadata = options._metadata || {};\n\n if (!metadata.sdk) {\n metadata.sdk = {\n name: `sentry.javascript.${name}`,\n packages: names.map(name => ({\n name: `${source}:@sentry/${name}`,\n version: SDK_VERSION,\n })),\n version: SDK_VERSION,\n };\n }\n\n options._metadata = metadata;\n}\n\nexport { applySdkMetadata };\n//# sourceMappingURL=sdkMetadata.js.map\n","import { getClient, getIsolationScope } from './currentScopes.js';\nimport { consoleSandbox } from './utils-hoist/logger.js';\nimport { dateTimestampInSeconds } from './utils-hoist/time.js';\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n */\nfunction addBreadcrumb(breadcrumb, hint) {\n const client = getClient();\n const isolationScope = getIsolationScope();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client.getOptions();\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) )\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n isolationScope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n}\n\nexport { addBreadcrumb };\n//# sourceMappingURL=breadcrumbs.js.map\n","import { getClient } from '../currentScopes.js';\nimport { defineIntegration } from '../integration.js';\nimport { getOriginalFunction } from '../utils-hoist/object.js';\n\nlet originalFunctionToString;\n\nconst INTEGRATION_NAME = 'FunctionToString';\n\nconst SETUP_CLIENTS = new WeakMap();\n\nconst _functionToStringIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n Function.prototype.toString = function ( ...args) {\n const originalFunction = getOriginalFunction(this);\n const context =\n SETUP_CLIENTS.has(getClient() ) && originalFunction !== undefined ? originalFunction : this;\n return originalFunctionToString.apply(context, args);\n };\n } catch (e) {\n // ignore errors here, just don't patch this\n }\n },\n setup(client) {\n SETUP_CLIENTS.set(client, true);\n },\n };\n}) ;\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * ```js\n * Sentry.init({\n * integrations: [\n * functionToStringIntegration(),\n * ],\n * });\n * ```\n */\nconst functionToStringIntegration = defineIntegration(_functionToStringIntegration);\n\nexport { functionToStringIntegration };\n//# sourceMappingURL=functiontostring.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { defineIntegration } from '../integration.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { getEventDescription } from '../utils-hoist/misc.js';\nimport { stringMatchesSomePattern } from '../utils-hoist/string.js';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [\n /^Script error\\.?$/,\n /^Javascript error: Script error\\.? on line 0$/,\n /^ResizeObserver loop completed with undelivered notifications.$/, // The browser logs this when a ResizeObserver handler takes a bit longer. Usually this is not an actual issue though. It indicates slowness.\n /^Cannot redefine property: googletag$/, // This is thrown when google tag manager is used in combination with an ad blocker\n \"undefined is not an object (evaluating 'a.L')\", // Random error that happens but not actionable or noticeable to end-users.\n 'can\\'t redefine non-configurable property \"solana\"', // Probably a browser extension or custom browser (Brave) throwing this error\n \"vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)\", // Error thrown by GTM, seemingly not affecting end-users\n \"Can't find variable: _AutofillCallbackHandler\", // Unactionable error in instagram webview https://developers.facebook.com/community/threads/320013549791141/\n /^Non-Error promise rejection captured with value: Object Not Found Matching Id:\\d+, MethodName:simulateEvent, ParamCount:\\d+$/, // unactionable error from CEFSharp, a .NET library that embeds chromium in .NET apps\n];\n\n/** Options for the InboundFilters integration */\n\nconst INTEGRATION_NAME = 'InboundFilters';\nconst _inboundFiltersIntegration = ((options = {}) => {\n return {\n name: INTEGRATION_NAME,\n processEvent(event, _hint, client) {\n const clientOptions = client.getOptions();\n const mergedOptions = _mergeOptions(options, clientOptions);\n return _shouldDropEvent(event, mergedOptions) ? null : event;\n },\n };\n}) ;\n\nconst inboundFiltersIntegration = defineIntegration(_inboundFiltersIntegration);\n\nfunction _mergeOptions(\n internalOptions = {},\n clientOptions = {},\n) {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [...(internalOptions.ignoreTransactions || []), ...(clientOptions.ignoreTransactions || [])],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\nfunction _shouldDropEvent(event, options) {\n if (options.ignoreInternal && _isSentryError(event)) {\n DEBUG_BUILD &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isUselessError(event)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to not having an error message, error type or stacktrace.\\nEvent: ${getEventDescription(\n event,\n )}`,\n );\n return true;\n }\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event, ignoreErrors) {\n // If event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event, ignoreTransactions) {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event, denyUrls) {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event, allowUrls) {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event) {\n const possibleMessages = [];\n\n if (event.message) {\n possibleMessages.push(event.message);\n }\n\n let lastException;\n try {\n // @ts-expect-error Try catching to save bundle size\n lastException = event.exception.values[event.exception.values.length - 1];\n } catch (e) {\n // try catching to save bundle size checking existence of variables\n }\n\n if (lastException) {\n if (lastException.value) {\n possibleMessages.push(lastException.value);\n if (lastException.type) {\n possibleMessages.push(`${lastException.type}: ${lastException.value}`);\n }\n }\n }\n\n return possibleMessages;\n}\n\nfunction _isSentryError(event) {\n try {\n // @ts-expect-error can't be a sentry error if undefined\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames = []) {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event) {\n try {\n let frames;\n try {\n // @ts-expect-error we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n DEBUG_BUILD && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n\nfunction _isUselessError(event) {\n if (event.type) {\n // event is not an error\n return false;\n }\n\n // We only want to consider events for dropping that actually have recorded exception values.\n if (!event.exception || !event.exception.values || event.exception.values.length === 0) {\n return false;\n }\n\n return (\n // No top-level message\n !event.message &&\n // There are no exception values that have a stacktrace, a non-generic-Error type or value\n !event.exception.values.some(value => value.stacktrace || (value.type && value.type !== 'Error') || value.value)\n );\n}\n\nexport { inboundFiltersIntegration };\n//# sourceMappingURL=inboundfilters.js.map\n","import { isInstanceOf } from './is.js';\nimport { truncate } from './string.js';\n\n/**\n * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter.\n */\nfunction applyAggregateErrorsToEvent(\n exceptionFromErrorImplementation,\n parser,\n maxValueLimit = 250,\n key,\n limit,\n event,\n hint,\n) {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return;\n }\n\n // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error\n const originalException =\n event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined;\n\n // We only create exception grouping if there is an exception in the event.\n if (originalException) {\n event.exception.values = truncateAggregateExceptions(\n aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n hint.originalException ,\n key,\n event.exception.values,\n originalException,\n 0,\n ),\n maxValueLimit,\n );\n }\n}\n\nfunction aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error,\n key,\n prevExceptions,\n exception,\n exceptionId,\n) {\n if (prevExceptions.length >= limit + 1) {\n return prevExceptions;\n }\n\n let newExceptions = [...prevExceptions];\n\n // Recursively call this function in order to walk down a chain of errors\n if (isInstanceOf(error[key], Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, error[key]);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error[key],\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n\n // This will create exception grouping for AggregateErrors\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError\n if (Array.isArray(error.errors)) {\n error.errors.forEach((childError, i) => {\n if (isInstanceOf(childError, Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, childError);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n childError,\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n });\n }\n\n return newExceptions;\n}\n\nfunction applyExceptionGroupFieldsForParentException(exception, exceptionId) {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n ...(exception.type === 'AggregateError' && { is_exception_group: true }),\n exception_id: exceptionId,\n };\n}\n\nfunction applyExceptionGroupFieldsForChildException(\n exception,\n source,\n exceptionId,\n parentId,\n) {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n type: 'chained',\n source,\n exception_id: exceptionId,\n parent_id: parentId,\n };\n}\n\n/**\n * Truncate the message (exception.value) of all exceptions in the event.\n * Because this event processor is ran after `applyClientOptions`,\n * we need to truncate the message of the added exceptions here.\n */\nfunction truncateAggregateExceptions(exceptions, maxValueLength) {\n return exceptions.map(exception => {\n if (exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n return exception;\n });\n}\n\nexport { applyAggregateErrorsToEvent };\n//# sourceMappingURL=aggregate-errors.js.map\n","/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nfunction parseUrl(url) {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nfunction stripUrlQueryAndFragment(urlPath) {\n return (urlPath.split(/[?#]/, 1) )[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n *\n * @deprecated This function will be removed in the next major version.\n */\n// TODO(v9): Hoist this function into the places where we use it. (as it stands only react router v6 instrumentation)\nfunction getNumberOfUrlSegments(url) {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span name\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nfunction getSanitizedUrlString(url) {\n const { protocol, host, path } = url;\n\n const filteredHost =\n (host &&\n host\n // Always filter out authority\n .replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n // TODO: Use new URL global if it exists\n .replace(/(:80)$/, '')\n .replace(/(:443)$/, '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n\nexport { getNumberOfUrlSegments, getSanitizedUrlString, parseUrl, stripUrlQueryAndFragment };\n//# sourceMappingURL=url.js.map\n","import { CONSOLE_LEVELS, originalConsoleMethods } from '../logger.js';\nimport { fill } from '../object.js';\nimport { GLOBAL_OBJ } from '../worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\n/**\n * Add an instrumentation handler for when a console.xxx method is called.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addConsoleInstrumentationHandler(handler) {\n const type = 'console';\n addHandler(type, handler);\n maybeInstrument(type, instrumentConsole);\n}\n\nfunction instrumentConsole() {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level) {\n if (!(level in GLOBAL_OBJ.console)) {\n return;\n }\n\n fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod) {\n originalConsoleMethods[level] = originalConsoleMethod;\n\n return function (...args) {\n const handlerData = { args, level };\n triggerHandlers('console', handlerData);\n\n const log = originalConsoleMethods[level];\n log && log.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n\nexport { addConsoleInstrumentationHandler };\n//# sourceMappingURL=console.js.map\n","/**\n * @deprecated This variable has been deprecated and will be removed in the next major version.\n */\nconst validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nfunction severityLevelFromString(level) {\n return (\n level === 'warn' ? 'warning' : ['fatal', 'error', 'warning', 'log', 'info', 'debug'].includes(level) ? level : 'log'\n ) ;\n}\n\nexport { severityLevelFromString, validSeverityLevels };\n//# sourceMappingURL=severity.js.map\n","import { defineIntegration } from '../integration.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { getFramesFromEvent } from '../utils-hoist/stacktrace.js';\n\nconst INTEGRATION_NAME = 'Dedupe';\n\nconst _dedupeIntegration = (() => {\n let previousEvent;\n\n return {\n name: INTEGRATION_NAME,\n processEvent(currentEvent) {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, previousEvent)) {\n DEBUG_BUILD && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n return (previousEvent = currentEvent);\n },\n };\n}) ;\n\n/**\n * Deduplication filter.\n */\nconst dedupeIntegration = defineIntegration(_dedupeIntegration);\n\n/** only exported for tests. */\nfunction _shouldDropEvent(currentEvent, previousEvent) {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\nfunction _isSameMessageEvent(currentEvent, previousEvent) {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameExceptionEvent(currentEvent, previousEvent) {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameStacktrace(currentEvent, previousEvent) {\n let currentFrames = getFramesFromEvent(currentEvent);\n let previousFrames = getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames ;\n previousFrames = previousFrames ;\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const frameA = previousFrames[i];\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction _isSameFingerprint(currentEvent, previousEvent) {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint ;\n previousFingerprint = previousFingerprint ;\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\nfunction _getExceptionFromEvent(event) {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\nexport { _shouldDropEvent, dedupeIntegration };\n//# sourceMappingURL=dedupe.js.map\n","/**\n * Determine a breadcrumb's log level (only `warning` or `error`) based on an HTTP status code.\n */\nfunction getBreadcrumbLogLevelFromHttpStatusCode(statusCode) {\n // NOTE: undefined defaults to 'info' in Sentry\n if (statusCode === undefined) {\n return undefined;\n } else if (statusCode >= 400 && statusCode < 500) {\n return 'warning';\n } else if (statusCode >= 500) {\n return 'error';\n } else {\n return undefined;\n }\n}\n\nexport { getBreadcrumbLogLevelFromHttpStatusCode };\n//# sourceMappingURL=breadcrumb-log-level.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { logger } from './logger.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nconst WINDOW = GLOBAL_OBJ ;\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsErrorEvent() {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMError() {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-expect-error It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMException() {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsFetch() {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * isNative checks if the given function is a native implementation\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isNativeFunction(func) {\n return func && /^function\\s+\\w+\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nfunction supportsNativeFetch() {\n if (typeof EdgeRuntime === 'string') {\n return true;\n }\n\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFunction(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement ) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFunction(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n DEBUG_BUILD &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsReportingObserver() {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsReferrerPolicy() {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' ,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n\nexport { isNativeFunction, supportsDOMError, supportsDOMException, supportsErrorEvent, supportsFetch, supportsNativeFetch, supportsReferrerPolicy, supportsReportingObserver };\n//# sourceMappingURL=supports.js.map\n","import { isError } from '../is.js';\nimport { fill, addNonEnumerableProperty } from '../object.js';\nimport { supportsNativeFetch } from '../supports.js';\nimport { timestampInSeconds } from '../time.js';\nimport { GLOBAL_OBJ } from '../worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addFetchInstrumentationHandler(\n handler,\n skipNativeFetchCheck,\n) {\n const type = 'fetch';\n addHandler(type, handler);\n maybeInstrument(type, () => instrumentFetch(undefined, skipNativeFetchCheck));\n}\n\n/**\n * Add an instrumentation handler for long-lived fetch requests, like consuming server-sent events (SSE) via fetch.\n * The handler will resolve the request body and emit the actual `endTimestamp`, so that the\n * span can be updated accordingly.\n *\n * Only used internally\n * @hidden\n */\nfunction addFetchEndInstrumentationHandler(handler) {\n const type = 'fetch-body-resolved';\n addHandler(type, handler);\n maybeInstrument(type, () => instrumentFetch(streamHandler));\n}\n\nfunction instrumentFetch(onFetchResolved, skipNativeFetchCheck = false) {\n if (skipNativeFetchCheck && !supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch) {\n return function (...args) {\n // We capture the error right here and not in the Promise error callback because Safari (and probably other\n // browsers too) will wipe the stack trace up to this point, only leaving us with this file which is useless.\n\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the error, that was caused by your fetch call did not\n // have a stack trace, so the SDK backfilled the stack trace so\n // you can see which fetch call failed.\n const virtualError = new Error();\n\n const { method, url } = parseFetchArgs(args);\n const handlerData = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: timestampInSeconds() * 1000,\n // // Adding the error to be able to fingerprint the failed fetch event in HttpClient instrumentation\n virtualError,\n };\n\n // if there is no callback, fetch is instrumented directly\n if (!onFetchResolved) {\n triggerHandlers('fetch', {\n ...handlerData,\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(GLOBAL_OBJ, args).then(\n async (response) => {\n if (onFetchResolved) {\n onFetchResolved(response);\n } else {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: timestampInSeconds() * 1000,\n response,\n });\n }\n\n return response;\n },\n (error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: timestampInSeconds() * 1000,\n error,\n });\n\n if (isError(error) && error.stack === undefined) {\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the error, that was caused by your fetch call did not\n // have a stack trace, so the SDK backfilled the stack trace so\n // you can see which fetch call failed.\n error.stack = virtualError.stack;\n addNonEnumerableProperty(error, 'framesToPop', 1);\n }\n\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nasync function resolveResponse(res, onFinishedResolving) {\n if (res && res.body) {\n const body = res.body;\n const responseReader = body.getReader();\n\n // Define a maximum duration after which we just cancel\n const maxFetchDurationTimeout = setTimeout(\n () => {\n body.cancel().then(null, () => {\n // noop\n });\n },\n 90 * 1000, // 90s\n );\n\n let readingActive = true;\n while (readingActive) {\n let chunkTimeout;\n try {\n // abort reading if read op takes more than 5s\n chunkTimeout = setTimeout(() => {\n body.cancel().then(null, () => {\n // noop on error\n });\n }, 5000);\n\n // This .read() call will reject/throw when we abort due to timeouts through `body.cancel()`\n const { done } = await responseReader.read();\n\n clearTimeout(chunkTimeout);\n\n if (done) {\n onFinishedResolving();\n readingActive = false;\n }\n } catch (error) {\n readingActive = false;\n } finally {\n clearTimeout(chunkTimeout);\n }\n }\n\n clearTimeout(maxFetchDurationTimeout);\n\n responseReader.releaseLock();\n body.cancel().then(null, () => {\n // noop on error\n });\n }\n}\n\nfunction streamHandler(response) {\n // clone response for awaiting stream\n let clonedResponseForResolving;\n try {\n clonedResponseForResolving = response.clone();\n } catch (e) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n resolveResponse(clonedResponseForResolving, () => {\n triggerHandlers('fetch-body-resolved', {\n endTimestamp: timestampInSeconds() * 1000,\n response,\n });\n });\n}\n\nfunction hasProp(obj, prop) {\n return !!obj && typeof obj === 'object' && !!(obj )[prop];\n}\n\nfunction getUrlFromResource(resource) {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request.\n * Exported for tests only.\n */\nfunction parseFetchArgs(fetchArgs) {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs ;\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg ),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n\nexport { addFetchEndInstrumentationHandler, addFetchInstrumentationHandler, parseFetchArgs };\n//# sourceMappingURL=fetch.js.map\n","/*\n * This module exists for optimizations in the build process through rollup and terser. We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `logger` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nfunction isBrowserBundle() {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nfunction getSDKSource() {\n // This comment is used to identify this line in the CDN bundle build step and replace this with \"return 'cdn';\"\n /* __SENTRY_SDK_SOURCE__ */ return 'npm';\n}\n\nexport { getSDKSource, isBrowserBundle };\n//# sourceMappingURL=env.js.map\n","import { GLOBAL_OBJ } from '../worldwide.js';\n\n// Based on https://github.com/angular/angular.js/pull/13945/files\n// The MIT License\n\n\nconst WINDOW = GLOBAL_OBJ ;\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsHistory() {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n // TODO(v9): Remove this custom check, it is pretty old and likely not needed anymore\n const chromeVar = (WINDOW ).chrome;\n const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime;\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n\nexport { supportsHistory };\n//# sourceMappingURL=supportsHistory.js.map\n","import { GLOBAL_OBJ, getOriginalFunction, markFunctionWrapped, addNonEnumerableProperty, withScope, addExceptionTypeValue, addExceptionMechanism, captureException } from '@sentry/core';\n\nconst WINDOW = GLOBAL_OBJ ;\n\nlet ignoreOnError = 0;\n\n/**\n * @hidden\n */\nfunction shouldIgnoreOnError() {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nfunction ignoreNextOnError() {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nfunction wrap(\n fn,\n options\n\n = {},\n) {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n function isFunction(fn) {\n return typeof fn === 'function';\n }\n\n if (!isFunction(fn)) {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = (fn ).__sentry_wrapped__;\n if (wrapper) {\n if (typeof wrapper === 'function') {\n return wrapper;\n } else {\n // If we find that the `__sentry_wrapped__` function is not a function at the time of accessing it, it means\n // that something messed with it. In that case we want to return the originally passed function.\n return fn;\n }\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n // Wrap the function itself\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped = function ( ...args) {\n try {\n // Also wrap arguments that are themselves functions\n const wrappedArguments = args.map(arg => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n } ;\n\n // Wrap the wrapped function in a proxy, to ensure any other properties of the original function remain available\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property ] = fn[property ];\n }\n }\n } catch (e2) {\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n }\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name');\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get() {\n return fn.name;\n },\n });\n }\n } catch (e3) {\n // This may throw if e.g. the descriptor does not exist, or a browser does not allow redefining `name`.\n // to save some bytes we simply try-catch this\n }\n\n return sentryWrapped;\n}\n\nexport { WINDOW, ignoreNextOnError, shouldIgnoreOnError, wrap };\n//# sourceMappingURL=helpers.js.map\n","/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nexport { DEBUG_BUILD };\n//# sourceMappingURL=debug-build.js.map\n","import { addExceptionMechanism, resolvedSyncPromise, isErrorEvent, isDOMError, isDOMException, addExceptionTypeValue, isError, isPlainObject, isEvent, isParameterizedString, getClient, normalizeToSize, extractExceptionKeysForMessage } from '@sentry/core';\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nfunction exceptionFromError(stackParser, ex) {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception = {\n type: extractType(ex),\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\nfunction eventFromPlainObject(\n stackParser,\n exception,\n syntheticException,\n isUnhandledRejection,\n) {\n const client = getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n\n // If we can, we extract an exception from the object properties\n const errorFromProp = getErrorPropertyFromObject(exception);\n\n const extra = {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n };\n\n if (errorFromProp) {\n return {\n exception: {\n values: [exceptionFromError(stackParser, errorFromProp)],\n },\n extra,\n };\n }\n\n const event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }),\n } ,\n ],\n },\n extra,\n } ;\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception.values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\nfunction eventFromError(stackParser, ex) {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nfunction parseStackFrames(\n stackParser,\n ex,\n) {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const skipLines = getSkipFirstStackStringLines(ex);\n const framesToPop = getPopFirstTopFrames(ex);\n\n try {\n return stackParser(stacktrace, skipLines, framesToPop);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\n/**\n * Certain known React errors contain links that would be falsely\n * parsed as frames. This function check for these errors and\n * returns number of the stack string lines to skip.\n */\nfunction getSkipFirstStackStringLines(ex) {\n if (ex && reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n\n return 0;\n}\n\n/**\n * If error has `framesToPop` property, it means that the\n * creator tells us the first x frames will be useless\n * and should be discarded. Typically error from wrapper function\n * which don't point to the actual location in the developer's code.\n *\n * Example: https://github.com/zertosh/invariant/blob/master/invariant.js#L46\n */\nfunction getPopFirstTopFrames(ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n return 0;\n}\n\n// https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Exception\n// @ts-expect-error - WebAssembly.Exception is a valid class\nfunction isWebAssemblyException(exception) {\n // Check for support\n // @ts-expect-error - WebAssembly.Exception is a valid class\n if (typeof WebAssembly !== 'undefined' && typeof WebAssembly.Exception !== 'undefined') {\n // @ts-expect-error - WebAssembly.Exception is a valid class\n return exception instanceof WebAssembly.Exception;\n } else {\n return false;\n }\n}\n\n/**\n * Extracts from errors what we use as the exception `type` in error events.\n *\n * Usually, this is the `name` property on Error objects but WASM errors need to be treated differently.\n */\nfunction extractType(ex) {\n const name = ex && ex.name;\n\n // The name for WebAssembly.Exception Errors needs to be extracted differently.\n // Context: https://github.com/getsentry/sentry-javascript/issues/13787\n if (!name && isWebAssemblyException(ex)) {\n // Emscripten sets array[type, message] to the \"message\" property on the WebAssembly.Exception object\n const hasTypeInMessage = ex.message && Array.isArray(ex.message) && ex.message.length == 2;\n return hasTypeInMessage ? ex.message[0] : 'WebAssembly.Exception';\n }\n\n return name;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex) {\n const message = ex && ex.message;\n\n if (!message) {\n return 'No error message';\n }\n\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n\n // Emscripten sets array[type, message] to the \"message\" property on the WebAssembly.Exception object\n if (isWebAssemblyException(ex) && Array.isArray(ex.message) && ex.message.length == 2) {\n return ex.message[1];\n }\n\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nfunction eventFromException(\n stackParser,\n exception,\n hint,\n attachStacktrace,\n) {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nfunction eventFromMessage(\n stackParser,\n message,\n level = 'info',\n hint,\n attachStacktrace,\n) {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nfunction eventFromUnknownInput(\n stackParser,\n exception,\n syntheticException,\n attachStacktrace,\n isUnhandledRejection,\n) {\n let event;\n\n if (isErrorEvent(exception ) && (exception ).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception ;\n return eventFromError(stackParser, errorEvent.error );\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception) || isDOMException(exception )) {\n const domException = exception ;\n\n if ('stack' in (exception )) {\n event = eventFromError(stackParser, exception );\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n // eslint-disable-next-line deprecation/deprecation\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception ;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception , syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\nfunction eventFromString(\n stackParser,\n message,\n syntheticException,\n attachStacktrace,\n) {\n const event = {};\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: message, stacktrace: { frames } }],\n };\n }\n addExceptionMechanism(event, { synthetic: true });\n }\n\n if (isParameterizedString(message)) {\n const { __sentry_template_string__, __sentry_template_values__ } = message;\n\n event.logentry = {\n message: __sentry_template_string__,\n params: __sentry_template_values__,\n };\n return event;\n }\n\n event.message = message;\n return event;\n}\n\nfunction getNonErrorObjectExceptionValue(\n exception,\n { isUnhandledRejection },\n) {\n const keys = extractExceptionKeysForMessage(exception);\n const captureType = isUnhandledRejection ? 'promise rejection' : 'exception';\n\n // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before\n // We still want to try to get a decent message for these cases\n if (isErrorEvent(exception)) {\n return `Event \\`ErrorEvent\\` captured as ${captureType} with message \\`${exception.message}\\``;\n }\n\n if (isEvent(exception)) {\n const className = getObjectClassName(exception);\n return `Event \\`${className}\\` (type=${exception.type}) captured as ${captureType}`;\n }\n\n return `Object captured as ${captureType} with keys: ${keys}`;\n}\n\nfunction getObjectClassName(obj) {\n try {\n const prototype = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : undefined;\n } catch (e) {\n // ignore errors here\n }\n}\n\n/** If a plain object has a property that is an `Error`, return this error. */\nfunction getErrorPropertyFromObject(obj) {\n for (const prop in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n const value = obj[prop];\n if (value instanceof Error) {\n return value;\n }\n }\n }\n\n return undefined;\n}\n\nexport { eventFromException, eventFromMessage, eventFromUnknownInput, exceptionFromError, extractMessage, extractType };\n//# sourceMappingURL=eventbuilder.js.map\n","import { dsnToString, createEnvelope } from '@sentry/core';\n\n/**\n * Creates an envelope from a user feedback.\n */\nfunction createUserFeedbackEnvelope(\n feedback,\n {\n metadata,\n tunnel,\n dsn,\n }\n\n,\n) {\n const headers = {\n event_id: feedback.event_id,\n sent_at: new Date().toISOString(),\n ...(metadata &&\n metadata.sdk && {\n sdk: {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n },\n }),\n ...(!!tunnel && !!dsn && { dsn: dsnToString(dsn) }),\n };\n const item = createUserFeedbackEnvelopeItem(feedback);\n\n return createEnvelope(headers, [item]);\n}\n\nfunction createUserFeedbackEnvelopeItem(feedback) {\n const feedbackHeaders = {\n type: 'user_report',\n };\n return [feedbackHeaders, feedback];\n}\n\nexport { createUserFeedbackEnvelope };\n//# sourceMappingURL=userfeedback.js.map\n","import { BaseClient, getSDKSource, applySdkMetadata, logger } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { eventFromException, eventFromMessage } from './eventbuilder.js';\nimport { WINDOW } from './helpers.js';\nimport { createUserFeedbackEnvelope } from './userfeedback.js';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/core Options for more information.\n */\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nclass BrowserClient extends BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n constructor(options) {\n const opts = {\n // We default this to true, as it is the safer scenario\n parentSpanIsAlwaysRootSpan: true,\n ...options,\n };\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n applySdkMetadata(opts, 'browser', ['browser'], sdkSource);\n\n super(opts);\n\n if (opts.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n eventFromException(exception, hint) {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n eventFromMessage(\n message,\n level = 'info',\n hint,\n ) {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * Sends user feedback to Sentry.\n *\n * @deprecated Use `captureFeedback` instead.\n */\n captureUserFeedback(feedback) {\n if (!this._isEnabled()) {\n DEBUG_BUILD && logger.warn('SDK not enabled, will not capture user feedback.');\n return;\n }\n\n const envelope = createUserFeedbackEnvelope(feedback, {\n metadata: this.getSdkMetadata(),\n dsn: this.getDsn(),\n tunnel: this.getOptions().tunnel,\n });\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n _prepareEvent(event, hint, scope) {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n}\n\nexport { BrowserClient };\n//# sourceMappingURL=client.js.map\n","/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nexport { DEBUG_BUILD };\n//# sourceMappingURL=debug-build.js.map\n","import { GLOBAL_OBJ } from '@sentry/core';\n\nconst WINDOW = GLOBAL_OBJ\n\n;\n\nexport { WINDOW };\n//# sourceMappingURL=types.js.map\n","import { addHandler, maybeInstrument, triggerHandlers, fill, addNonEnumerableProperty, uuid4 } from '@sentry/core';\nimport { WINDOW } from '../types.js';\n\nconst DEBOUNCE_DURATION = 1000;\n\nlet debounceTimerID;\nlet lastCapturedEventType;\nlet lastCapturedEventTargetId;\n\n/**\n * Add an instrumentation handler for when a click or a keypress happens.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addClickKeypressInstrumentationHandler(handler) {\n const type = 'dom';\n addHandler(type, handler);\n maybeInstrument(type, instrumentDOM);\n}\n\n/** Exported for tests only. */\nfunction instrumentDOM() {\n if (!WINDOW.document) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target) => {\n const globalObject = WINDOW ;\n const targetObj = globalObject[target];\n const proto = targetObj && targetObj.prototype;\n\n // eslint-disable-next-line no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener) {\n return function ( type, listener, options) {\n if (type === 'click' || type == 'keypress') {\n try {\n const handlers = (this.__sentry_instrumentation_handlers__ =\n this.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListeners` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener) {\n return function ( type, listener, options) {\n if (type === 'click' || type == 'keypress') {\n try {\n const handlers = this.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete this.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListeners` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\n/**\n * Check whether the event is similar to the last captured one. For example, two click events on the same button.\n */\nfunction isSimilarToLastCapturedEvent(event) {\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (event.type !== lastCapturedEventType) {\n return false;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (!event.target || (event.target )._sentryId !== lastCapturedEventTargetId) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return true;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(eventType, target) {\n // We are only interested in filtering `keypress` events for now.\n if (eventType !== 'keypress') {\n return false;\n }\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n */\nfunction makeDOMEventHandler(\n handler,\n globalListener = false,\n) {\n return (event) => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || event['_sentryCaptured']) {\n return;\n }\n\n const target = getEventTarget(event);\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event.type, target)) {\n return;\n }\n\n // Mark event as \"seen\"\n addNonEnumerableProperty(event, '_sentryCaptured', true);\n\n if (target && !target._sentryId) {\n // Add UUID to event target so we can identify if\n addNonEnumerableProperty(target, '_sentryId', uuid4());\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no last captured event, it means that we can safely capture the new event and store it for future comparisons.\n // If there is a last captured event, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n if (!isSimilarToLastCapturedEvent(event)) {\n const handlerData = { event, name, global: globalListener };\n handler(handlerData);\n lastCapturedEventType = event.type;\n lastCapturedEventTargetId = target ? target._sentryId : undefined;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n lastCapturedEventTargetId = undefined;\n lastCapturedEventType = undefined;\n }, DEBOUNCE_DURATION);\n };\n}\n\nfunction getEventTarget(event) {\n try {\n return event.target ;\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n return null;\n }\n}\n\nexport { addClickKeypressInstrumentationHandler, instrumentDOM };\n//# sourceMappingURL=dom.js.map\n","import { addHandler, maybeInstrument, supportsHistory, triggerHandlers, fill } from '@sentry/core';\nimport { WINDOW } from '../types.js';\n\nlet lastHref;\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addHistoryInstrumentationHandler(handler) {\n const type = 'history';\n addHandler(type, handler);\n maybeInstrument(type, instrumentHistory);\n}\n\nfunction instrumentHistory() {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function ( ...args) {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n const handlerData = { from, to };\n triggerHandlers('history', handlerData);\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n function historyReplacementFunction(originalHistoryFunction) {\n return function ( ...args) {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n const handlerData = { from, to };\n triggerHandlers('history', handlerData);\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n\nexport { addHistoryInstrumentationHandler };\n//# sourceMappingURL=history.js.map\n","import { isNativeFunction, logger } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { WINDOW } from './types.js';\n\n/**\n * We generally want to use window.fetch / window.setTimeout.\n * However, in some cases this may be wrapped (e.g. by Zone.js for Angular),\n * so we try to get an unpatched version of this from a sandboxed iframe.\n */\n\nconst cachedImplementations = {};\n\n/**\n * Get the native implementation of a browser function.\n *\n * This can be used to ensure we get an unwrapped version of a function, in cases where a wrapped function can lead to problems.\n *\n * The following methods can be retrieved:\n * - `setTimeout`: This can be wrapped by e.g. Angular, causing change detection to be triggered.\n * - `fetch`: This can be wrapped by e.g. ad-blockers, causing an infinite loop when a request is blocked.\n */\nfunction getNativeImplementation(\n name,\n) {\n const cached = cachedImplementations[name];\n if (cached) {\n return cached;\n }\n\n let impl = WINDOW[name] ;\n\n // Fast path to avoid DOM I/O\n if (isNativeFunction(impl)) {\n return (cachedImplementations[name] = impl.bind(WINDOW) );\n }\n\n const document = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow[name]) {\n impl = contentWindow[name] ;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n // Could not create sandbox iframe, just use window.xxx\n DEBUG_BUILD && logger.warn(`Could not create sandbox iframe for ${name} check, bailing to window.${name}: `, e);\n }\n }\n\n // Sanity check: This _should_ not happen, but if it does, we just skip caching...\n // This can happen e.g. in tests where fetch may not be available in the env, or similar.\n if (!impl) {\n return impl;\n }\n\n return (cachedImplementations[name] = impl.bind(WINDOW) );\n}\n\n/** Clear a cached implementation. */\nfunction clearCachedImplementation(name) {\n cachedImplementations[name] = undefined;\n}\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nfunction fetch(...rest) {\n return getNativeImplementation('fetch')(...rest);\n}\n\n/**\n * Get an unwrapped `setTimeout` method.\n * This ensures that even if e.g. Angular wraps `setTimeout`, we get the native implementation,\n * avoiding triggering change detection.\n */\nfunction setTimeout(...rest) {\n return getNativeImplementation('setTimeout')(...rest);\n}\n\nexport { clearCachedImplementation, fetch, getNativeImplementation, setTimeout };\n//# sourceMappingURL=getNativeImplementation.js.map\n","import { addHandler, maybeInstrument, timestampInSeconds, isString, triggerHandlers } from '@sentry/core';\nimport { WINDOW } from '../types.js';\n\nconst SENTRY_XHR_DATA_KEY = '__sentry_xhr_v3__';\n\n/**\n * Add an instrumentation handler for when an XHR request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addXhrInstrumentationHandler(handler) {\n const type = 'xhr';\n addHandler(type, handler);\n maybeInstrument(type, instrumentXHR);\n}\n\n/** Exported only for tests. */\nfunction instrumentXHR() {\n if (!(WINDOW ).XMLHttpRequest) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n xhrproto.open = new Proxy(xhrproto.open, {\n apply(originalOpen, xhrOpenThisArg, xhrOpenArgArray) {\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the error, that was caused by your XHR call did not\n // have a stack trace. If you are using HttpClient integration,\n // this is the expected behavior, as we are using this virtual error to capture\n // the location of your XHR call, and group your HttpClient events accordingly.\n const virtualError = new Error();\n\n const startTimestamp = timestampInSeconds() * 1000;\n\n // open() should always be called with two or more arguments\n // But to be on the safe side, we actually validate this and bail out if we don't have a method & url\n const method = isString(xhrOpenArgArray[0]) ? xhrOpenArgArray[0].toUpperCase() : undefined;\n const url = parseUrl(xhrOpenArgArray[1]);\n\n if (!method || !url) {\n return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray);\n }\n\n xhrOpenThisArg[SENTRY_XHR_DATA_KEY] = {\n method,\n url,\n request_headers: {},\n };\n\n // if Sentry key appears in URL, don't capture it as a request\n if (method === 'POST' && url.match(/sentry_key/)) {\n xhrOpenThisArg.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = xhrOpenThisArg[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (xhrOpenThisArg.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = xhrOpenThisArg.status;\n } catch (e) {\n /* do nothing */\n }\n\n const handlerData = {\n endTimestamp: timestampInSeconds() * 1000,\n startTimestamp,\n xhr: xhrOpenThisArg,\n virtualError,\n };\n triggerHandlers('xhr', handlerData);\n }\n };\n\n if ('onreadystatechange' in xhrOpenThisArg && typeof xhrOpenThisArg.onreadystatechange === 'function') {\n xhrOpenThisArg.onreadystatechange = new Proxy(xhrOpenThisArg.onreadystatechange, {\n apply(originalOnreadystatechange, onreadystatechangeThisArg, onreadystatechangeArgArray) {\n onreadystatechangeHandler();\n return originalOnreadystatechange.apply(onreadystatechangeThisArg, onreadystatechangeArgArray);\n },\n });\n } else {\n xhrOpenThisArg.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n xhrOpenThisArg.setRequestHeader = new Proxy(xhrOpenThisArg.setRequestHeader, {\n apply(\n originalSetRequestHeader,\n setRequestHeaderThisArg,\n setRequestHeaderArgArray,\n ) {\n const [header, value] = setRequestHeaderArgArray;\n\n const xhrInfo = setRequestHeaderThisArg[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo && isString(header) && isString(value)) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return originalSetRequestHeader.apply(setRequestHeaderThisArg, setRequestHeaderArgArray);\n },\n });\n\n return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray);\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n xhrproto.send = new Proxy(xhrproto.send, {\n apply(originalSend, sendThisArg, sendArgArray) {\n const sentryXhrData = sendThisArg[SENTRY_XHR_DATA_KEY];\n\n if (!sentryXhrData) {\n return originalSend.apply(sendThisArg, sendArgArray);\n }\n\n if (sendArgArray[0] !== undefined) {\n sentryXhrData.body = sendArgArray[0];\n }\n\n const handlerData = {\n startTimestamp: timestampInSeconds() * 1000,\n xhr: sendThisArg,\n };\n triggerHandlers('xhr', handlerData);\n\n return originalSend.apply(sendThisArg, sendArgArray);\n },\n });\n}\n\nfunction parseUrl(url) {\n if (isString(url)) {\n return url;\n }\n\n try {\n // url can be a string or URL\n // but since URL is not available in IE11, we do not check for it,\n // but simply assume it is an URL and return `toString()` from it (which returns the full URL)\n // If that fails, we just return undefined\n return (url ).toString();\n } catch (e2) {} // eslint-disable-line no-empty\n\n return undefined;\n}\n\nexport { SENTRY_XHR_DATA_KEY, addXhrInstrumentationHandler, instrumentXHR };\n//# sourceMappingURL=xhr.js.map\n","import { getNativeImplementation, clearCachedImplementation } from '@sentry-internal/browser-utils';\nimport { createTransport, rejectedSyncPromise } from '@sentry/core';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nfunction makeFetchTransport(\n options,\n nativeFetch = getNativeImplementation('fetch'),\n) {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n function makeRequest(request) {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. when finishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):\n // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.\n // We will therefore only activate the flag when we're below that limit.\n // There is also a limit of requests that can be open at the same time, so we also limit this to 15\n // See https://github.com/getsentry/sentry-javascript/pull/7553 for details\n keepalive: pendingBodySize <= 60000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n if (!nativeFetch) {\n clearCachedImplementation('fetch');\n return rejectedSyncPromise('No fetch implementation available');\n }\n\n try {\n // TODO: This may need a `suppressTracing` call in the future when we switch the browser SDK to OTEL\n return nativeFetch(options.url, requestOptions).then(response => {\n pendingBodySize -= requestSize;\n pendingCount--;\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n } catch (e) {\n clearCachedImplementation('fetch');\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n\nexport { makeFetchTransport };\n//# sourceMappingURL=fetch.js.map\n","import { createStackParser, UNKNOWN_FUNCTION } from '@sentry/core';\n\n// This was originally forked from https://github.com/csnover/TraceKit, and was largely\n// re - written as part of raven - js.\n//\n// This code was later copied to the JavaScript mono - repo and further modified and\n// refactored over the years.\n\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename, func, lineno, colno) {\n const frame = {\n filename,\n function: func === '' ? UNKNOWN_FUNCTION : func,\n in_app: true, // All browser frames are considered in_app\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// This regex matches frames that have no function name (ie. are at the top level of a module).\n// For example \"at http://localhost:5000//script.js:1:126\"\n// Frames _with_ function names usually look as follows: \"at commitLayoutEffects (react-dom.development.js:23426:1)\"\nconst chromeRegexNoFnName = /^\\s*at (\\S+?)(?::(\\d+))(?::(\\d+))\\s*$/i;\n\n// This regex matches all the frames that have a function name.\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\n\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\n// We cannot call this variable `chrome` because it can conflict with global `chrome` variable in certain environments\n// See: https://github.com/getsentry/sentry-javascript/issues/6880\nconst chromeStackParserFn = line => {\n // If the stack line has no function name, we need to parse it differently\n const noFnParts = chromeRegexNoFnName.exec(line) ;\n\n if (noFnParts) {\n const [, filename, line, col] = noFnParts;\n return createFrame(filename, UNKNOWN_FUNCTION, +line, +col);\n }\n\n const parts = chromeRegex.exec(line) ;\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]) ;\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nconst chromeStackLineParser = [CHROME_PRIORITY, chromeStackParserFn];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko = line => {\n const parts = geckoREgex.exec(line) ;\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]) ;\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nconst geckoStackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs = line => {\n const parts = winjsRegex.exec(line) ;\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nconst winjsStackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10 = line => {\n const parts = opera10Regex.exec(line) ;\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nconst opera10StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11 = line => {\n const parts = opera11Regex.exec(line) ;\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nconst opera11StackLineParser = [OPERA11_PRIORITY, opera11];\n\nconst defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser];\n\nconst defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func, filename) => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? (func.split('@')[0] ) : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n\nexport { chromeStackLineParser, defaultStackLineParsers, defaultStackParser, geckoStackLineParser, opera10StackLineParser, opera11StackLineParser, winjsStackLineParser };\n//# sourceMappingURL=stack-parsers.js.map\n","import { addClickKeypressInstrumentationHandler, addXhrInstrumentationHandler, addHistoryInstrumentationHandler, SENTRY_XHR_DATA_KEY } from '@sentry-internal/browser-utils';\nimport { defineIntegration, addConsoleInstrumentationHandler, addFetchInstrumentationHandler, getClient, addBreadcrumb, getEventDescription, logger, htmlTreeAsString, getComponentName, severityLevelFromString, safeJoin, getBreadcrumbLogLevelFromHttpStatusCode, parseUrl } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { WINDOW } from '../helpers.js';\n\n/* eslint-disable max-lines */\n\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nconst INTEGRATION_NAME = 'Breadcrumbs';\n\nconst _breadcrumbsIntegration = ((options = {}) => {\n const _options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n if (_options.console) {\n addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client));\n }\n if (_options.dom) {\n addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom));\n }\n if (_options.xhr) {\n addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client));\n }\n if (_options.fetch) {\n addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client));\n }\n if (_options.history) {\n addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client));\n }\n if (_options.sentry) {\n client.on('beforeSendEvent', _getSentryBreadcrumbHandler(client));\n }\n },\n };\n}) ;\n\nconst breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);\n\n/**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\nfunction _getSentryBreadcrumbHandler(client) {\n return function addSentryBreadcrumb(event) {\n if (getClient() !== client) {\n return;\n }\n\n addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n };\n}\n\n/**\n * A HOC that creates a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _getDomBreadcrumbHandler(\n client,\n dom,\n) {\n return function _innerDomBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n let target;\n let componentName;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event ;\n const element = _isEvent(event) ? event.target : event;\n\n target = htmlTreeAsString(element, { keyAttrs, maxStringLength });\n componentName = getComponentName(element);\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n const breadcrumb = {\n category: `ui.${handlerData.name}`,\n message: target,\n };\n\n if (componentName) {\n breadcrumb.data = { 'ui.component_name': componentName };\n }\n\n addBreadcrumb(breadcrumb, {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _getConsoleBreadcrumbHandler(client) {\n return function _consoleBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _getXhrBreadcrumbHandler(client) {\n return function _xhrBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data = {\n method,\n url,\n status_code,\n };\n\n const hint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n const level = getBreadcrumbLogLevelFromHttpStatusCode(status_code);\n\n addBreadcrumb(\n {\n category: 'xhr',\n data,\n type: 'http',\n level,\n },\n hint,\n );\n };\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _getFetchBreadcrumbHandler(client) {\n return function _fetchBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const data = handlerData.fetchData;\n const hint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const response = handlerData.response ;\n const data = {\n ...handlerData.fetchData,\n status_code: response && response.status,\n };\n const hint = {\n input: handlerData.args,\n response,\n startTimestamp,\n endTimestamp,\n };\n const level = getBreadcrumbLogLevelFromHttpStatusCode(data.status_code);\n\n addBreadcrumb(\n {\n category: 'fetch',\n data,\n type: 'http',\n level,\n },\n hint,\n );\n }\n };\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _getHistoryBreadcrumbHandler(client) {\n return function _historyBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n let from = handlerData.from;\n let to = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = from ? parseUrl(from) : undefined;\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom || !parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n };\n}\n\nfunction _isEvent(event) {\n return !!event && !!(event ).target;\n}\n\nexport { breadcrumbsIntegration };\n//# sourceMappingURL=breadcrumbs.js.map\n","import { defineIntegration, fill, getFunctionName, getOriginalFunction } from '@sentry/core';\nimport { WINDOW, wrap } from '../helpers.js';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'BroadcastChannel',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'SharedWorker',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\nconst INTEGRATION_NAME = 'BrowserApiErrors';\n\nconst _browserApiErrorsIntegration = ((options = {}) => {\n const _options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO: This currently only works for the first client this is setup\n // We may want to adjust this to check for client etc.\n setupOnce() {\n if (_options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (_options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (_options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (_options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = _options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n },\n };\n}) ;\n\n/**\n * Wrap timer functions and event targets to catch errors and provide better meta data.\n */\nconst browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration);\n\nfunction _wrapTimeFunction(original) {\n return function ( ...args) {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: false,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\nfunction _wrapRAF(original) {\n return function ( callback) {\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\nfunction _wrapXHR(originalSend) {\n return function ( ...args) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n fill(xhr, prop, function (original) {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before BrowserApiErrors, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\nfunction _wrapEventTarget(target) {\n const globalObject = WINDOW ;\n const targetObj = globalObject[target];\n const proto = targetObj && targetObj.prototype;\n\n // eslint-disable-next-line no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original)\n\n {\n return function ( eventName, fn, options) {\n try {\n if (isEventListenerObject(fn)) {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n });\n }\n } catch (e2) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n wrap(fn, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(proto, 'removeEventListener', function (originalRemoveEventListener)\n\n {\n return function ( eventName, fn, options) {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n try {\n const originalEventHandler = (fn ).__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, fn, options);\n };\n });\n}\n\nfunction isEventListenerObject(obj) {\n return typeof (obj ).handleEvent === 'function';\n}\n\nexport { browserApiErrorsIntegration };\n//# sourceMappingURL=browserapierrors.js.map\n","import { addHistoryInstrumentationHandler } from '@sentry-internal/browser-utils';\nimport { defineIntegration, logger, startSession, captureSession } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { WINDOW } from '../helpers.js';\n\n/**\n * When added, automatically creates sessions which allow you to track adoption and crashes (crash free rate) in your Releases in Sentry.\n * More information: https://docs.sentry.io/product/releases/health/\n *\n * Note: In order for session tracking to work, you need to set up Releases: https://docs.sentry.io/product/releases/\n */\nconst browserSessionIntegration = defineIntegration(() => {\n return {\n name: 'BrowserSession',\n setupOnce() {\n if (typeof WINDOW.document === 'undefined') {\n DEBUG_BUILD &&\n logger.warn('Using the `browserSessionIntegration` in non-browser environments is not supported.');\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSession({ ignoreDuration: true });\n captureSession();\n\n // We want to create a session for every navigation as well\n addHistoryInstrumentationHandler(({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (from !== undefined && from !== to) {\n startSession({ ignoreDuration: true });\n captureSession();\n }\n });\n },\n };\n});\n\nexport { browserSessionIntegration };\n//# sourceMappingURL=browsersession.js.map\n","import { defineIntegration, addGlobalErrorInstrumentationHandler, getClient, captureEvent, addGlobalUnhandledRejectionInstrumentationHandler, isPrimitive, isString, getLocationHref, UNKNOWN_FUNCTION, logger } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { eventFromUnknownInput } from '../eventbuilder.js';\nimport { shouldIgnoreOnError } from '../helpers.js';\n\nconst INTEGRATION_NAME = 'GlobalHandlers';\n\nconst _globalHandlersIntegration = ((options = {}) => {\n const _options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n Error.stackTraceLimit = 50;\n },\n setup(client) {\n if (_options.onerror) {\n _installGlobalOnErrorHandler(client);\n globalHandlerLog('onerror');\n }\n if (_options.onunhandledrejection) {\n _installGlobalOnUnhandledRejectionHandler(client);\n globalHandlerLog('onunhandledrejection');\n }\n },\n };\n}) ;\n\nconst globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);\n\nfunction _installGlobalOnErrorHandler(client) {\n addGlobalErrorInstrumentationHandler(data => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const { msg, url, line, column, error } = data;\n\n const event = _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onerror',\n },\n });\n });\n}\n\nfunction _installGlobalOnUnhandledRejectionHandler(client) {\n addGlobalUnhandledRejectionInstrumentationHandler(e => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const error = _getUnhandledRejectionError(e );\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onunhandledrejection',\n },\n });\n });\n}\n\nfunction _getUnhandledRejectionError(error) {\n if (isPrimitive(error)) {\n return error;\n }\n\n // dig the object of the rejection out of known event types\n try {\n\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in (error )) {\n return (error ).reason;\n }\n\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n if ('detail' in (error ) && 'reason' in (error ).detail) {\n return (error ).detail.reason;\n }\n } catch (e2) {} // eslint-disable-line no-empty\n\n return error;\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason) {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\nfunction _enhanceEventWithInitialFrame(\n event,\n url,\n line,\n column,\n) {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = column;\n const lineno = line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: UNKNOWN_FUNCTION,\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type) {\n DEBUG_BUILD && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction getOptions() {\n const client = getClient();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return options;\n}\n\nexport { globalHandlersIntegration };\n//# sourceMappingURL=globalhandlers.js.map\n","import { defineIntegration } from '@sentry/core';\nimport { WINDOW } from '../helpers.js';\n\n/**\n * Collects information about HTTP request headers and\n * attaches them to the event.\n */\nconst httpContextIntegration = defineIntegration(() => {\n return {\n name: 'HttpContext',\n preprocessEvent(event) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n event.request = request;\n },\n };\n});\n\nexport { httpContextIntegration };\n//# sourceMappingURL=httpcontext.js.map\n","import { defineIntegration, applyAggregateErrorsToEvent } from '@sentry/core';\nimport { exceptionFromError } from '../eventbuilder.js';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\nconst INTEGRATION_NAME = 'LinkedErrors';\n\nconst _linkedErrorsIntegration = ((options = {}) => {\n const limit = options.limit || DEFAULT_LIMIT;\n const key = options.key || DEFAULT_KEY;\n\n return {\n name: INTEGRATION_NAME,\n preprocessEvent(event, hint, client) {\n const options = client.getOptions();\n\n applyAggregateErrorsToEvent(\n // This differs from the LinkedErrors integration in core by using a different exceptionFromError function\n exceptionFromError,\n options.stackParser,\n options.maxValueLength,\n key,\n limit,\n event,\n hint,\n );\n },\n };\n}) ;\n\n/**\n * Aggregrate linked errors in an event.\n */\nconst linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);\n\nexport { linkedErrorsIntegration };\n//# sourceMappingURL=linkederrors.js.map\n","import { inboundFiltersIntegration, functionToStringIntegration, dedupeIntegration, consoleSandbox, supportsFetch, logger, stackParserFromStackParserOptions, getIntegrationsToSetup, initAndBind, getCurrentScope, lastEventId, getReportDialogEndpoint, getClient } from '@sentry/core';\nimport { BrowserClient } from './client.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { WINDOW } from './helpers.js';\nimport { breadcrumbsIntegration } from './integrations/breadcrumbs.js';\nimport { browserApiErrorsIntegration } from './integrations/browserapierrors.js';\nimport { browserSessionIntegration } from './integrations/browsersession.js';\nimport { globalHandlersIntegration } from './integrations/globalhandlers.js';\nimport { httpContextIntegration } from './integrations/httpcontext.js';\nimport { linkedErrorsIntegration } from './integrations/linkederrors.js';\nimport { defaultStackParser } from './stack-parsers.js';\nimport { makeFetchTransport } from './transports/fetch.js';\n\n/** Get the default integrations for the browser SDK. */\nfunction getDefaultIntegrations(options) {\n /**\n * Note: Please make sure this stays in sync with Angular SDK, which re-exports\n * `getDefaultIntegrations` but with an adjusted set of integrations.\n */\n const integrations = [\n inboundFiltersIntegration(),\n functionToStringIntegration(),\n browserApiErrorsIntegration(),\n breadcrumbsIntegration(),\n globalHandlersIntegration(),\n linkedErrorsIntegration(),\n dedupeIntegration(),\n httpContextIntegration(),\n ];\n\n // eslint-disable-next-line deprecation/deprecation\n if (options.autoSessionTracking !== false) {\n integrations.push(browserSessionIntegration());\n }\n\n return integrations;\n}\n\nfunction applyDefaultOptions(optionsArg = {}) {\n const defaultOptions = {\n defaultIntegrations: getDefaultIntegrations(optionsArg),\n release:\n typeof __SENTRY_RELEASE__ === 'string' // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n ? __SENTRY_RELEASE__\n : WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id // This supports the variable that sentry-webpack-plugin injects\n ? WINDOW.SENTRY_RELEASE.id\n : undefined,\n autoSessionTracking: true,\n sendClientReports: true,\n };\n\n // TODO: Instead of dropping just `defaultIntegrations`, we should simply\n // call `dropUndefinedKeys` on the entire `optionsArg`.\n // However, for this to work we need to adjust the `hasTracingEnabled()` logic\n // first as it differentiates between `undefined` and the key not being in the object.\n if (optionsArg.defaultIntegrations == null) {\n delete optionsArg.defaultIntegrations;\n }\n\n return { ...defaultOptions, ...optionsArg };\n}\n\nfunction shouldShowBrowserExtensionError() {\n const windowWithMaybeExtension =\n typeof WINDOW.window !== 'undefined' && (WINDOW );\n if (!windowWithMaybeExtension) {\n // No need to show the error if we're not in a browser window environment (e.g. service workers)\n return false;\n }\n\n const extensionKey = windowWithMaybeExtension.chrome ? 'chrome' : 'browser';\n const extensionObject = windowWithMaybeExtension[extensionKey];\n\n const runtimeId = extensionObject && extensionObject.runtime && extensionObject.runtime.id;\n const href = (WINDOW.location && WINDOW.location.href) || '';\n\n const extensionProtocols = ['chrome-extension:', 'moz-extension:', 'ms-browser-extension:', 'safari-web-extension:'];\n\n // Running the SDK in a dedicated extension page and calling Sentry.init is fine; no risk of data leakage\n const isDedicatedExtensionPage =\n !!runtimeId && WINDOW === WINDOW.top && extensionProtocols.some(protocol => href.startsWith(`${protocol}//`));\n\n // Running the SDK in NW.js, which appears like a browser extension but isn't, is also fine\n // see: https://github.com/getsentry/sentry-javascript/issues/12668\n const isNWjs = typeof windowWithMaybeExtension.nw !== 'undefined';\n\n return !!runtimeId && !isDedicatedExtensionPage && !isNWjs;\n}\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nfunction init(browserOptions = {}) {\n const options = applyDefaultOptions(browserOptions);\n\n if (!options.skipBrowserExtensionCheck && shouldShowBrowserExtensionError()) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(\n '[Sentry] You cannot run Sentry this way in a browser extension, check: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/',\n );\n });\n return;\n }\n\n if (DEBUG_BUILD) {\n if (!supportsFetch()) {\n logger.warn(\n 'No Fetch API detected. The Sentry SDK requires a Fetch API compatible environment to send events. Please add a Fetch API polyfill.',\n );\n }\n }\n const clientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || makeFetchTransport,\n };\n\n return initAndBind(BrowserClient, clientOptions);\n}\n\n/**\n * All properties the report dialog supports\n */\n\n/**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\nfunction showReportDialog(options = {}) {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n DEBUG_BUILD && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n const scope = getCurrentScope();\n const client = scope.getClient();\n const dsn = client && client.getDsn();\n\n if (!dsn) {\n DEBUG_BUILD && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n const eventId = lastEventId();\n if (eventId) {\n options.eventId = eventId;\n }\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.crossOrigin = 'anonymous';\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const { onClose } = options;\n if (onClose) {\n const reportDialogClosedMessageHandler = (event) => {\n if (event.data === '__sentry_reportdialog_closed__') {\n try {\n onClose();\n } finally {\n WINDOW.removeEventListener('message', reportDialogClosedMessageHandler);\n }\n }\n };\n WINDOW.addEventListener('message', reportDialogClosedMessageHandler);\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n DEBUG_BUILD && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nfunction forceLoad() {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nfunction onLoad(callback) {\n callback();\n}\n\n/**\n * Captures user feedback and sends it to Sentry.\n *\n * @deprecated Use `captureFeedback` instead.\n */\nfunction captureUserFeedback(feedback) {\n const client = getClient();\n if (client) {\n // eslint-disable-next-line deprecation/deprecation\n client.captureUserFeedback(feedback);\n }\n}\n\nexport { captureUserFeedback, forceLoad, getDefaultIntegrations, init, onLoad, showReportDialog };\n//# sourceMappingURL=sdk.js.map\n","import { setContext, init as init$1 } from '@sentry/browser';\nimport { applySdkMetadata } from '@sentry/core';\nimport { version } from 'react';\n\n/**\n * Inits the React SDK\n */\nfunction init(options) {\n const opts = {\n ...options,\n };\n\n applySdkMetadata(opts, 'react');\n setContext('react', { version });\n return init$1(opts);\n}\n\nexport { init };\n//# sourceMappingURL=sdk.js.map\n","import { captureException } from '@sentry/browser';\nimport { isError } from '@sentry/core';\nimport { version } from 'react';\n\n/**\n * See if React major version is 17+ by parsing version string.\n */\nfunction isAtLeastReact17(reactVersion) {\n const reactMajor = reactVersion.match(/^([^.]+)/);\n return reactMajor !== null && parseInt(reactMajor[0]) >= 17;\n}\n\n/**\n * Recurse through `error.cause` chain to set cause on an error.\n */\nfunction setCause(error, cause) {\n const seenErrors = new WeakSet();\n\n function recurse(error, cause) {\n // If we've already seen the error, there is a recursive loop somewhere in the error's\n // cause chain. Let's just bail out then to prevent a stack overflow.\n if (seenErrors.has(error)) {\n return;\n }\n if (error.cause) {\n seenErrors.add(error);\n return recurse(error.cause, cause);\n }\n error.cause = cause;\n }\n\n recurse(error, cause);\n}\n\n/**\n * Captures an error that was thrown by a React ErrorBoundary or React root.\n *\n * @param error The error to capture.\n * @param errorInfo The errorInfo provided by React.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\nfunction captureReactException(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n error,\n { componentStack },\n hint,\n) {\n // If on React version >= 17, create stack trace from componentStack param and links\n // to to the original error using `error.cause` otherwise relies on error param for stacktrace.\n // Linking errors requires the `LinkedErrors` integration be enabled.\n // See: https://reactjs.org/blog/2020/08/10/react-v17-rc.html#native-component-stacks\n //\n // Although `componentDidCatch` is typed to accept an `Error` object, it can also be invoked\n // with non-error objects. This is why we need to check if the error is an error-like object.\n // See: https://github.com/getsentry/sentry-javascript/issues/6167\n if (isAtLeastReact17(version) && isError(error) && componentStack) {\n const errorBoundaryError = new Error(error.message);\n errorBoundaryError.name = `React ErrorBoundary ${error.name}`;\n errorBoundaryError.stack = componentStack;\n\n // Using the `LinkedErrors` integration to link the errors together.\n setCause(error, errorBoundaryError);\n }\n\n return captureException(error, {\n ...hint,\n captureContext: {\n contexts: { react: { componentStack } },\n },\n });\n}\n\n/**\n * Creates an error handler that can be used with the `onCaughtError`, `onUncaughtError`,\n * and `onRecoverableError` options in `createRoot` and `hydrateRoot` React DOM methods.\n *\n * @param callback An optional callback that will be called after the error is captured.\n * Use this to add custom handling for errors.\n *\n * @example\n *\n * ```JavaScript\n * const root = createRoot(container, {\n * onCaughtError: Sentry.reactErrorHandler(),\n * onUncaughtError: Sentry.reactErrorHandler((error, errorInfo) => {\n * console.warn('Caught error', error, errorInfo.componentStack);\n * });\n * });\n * ```\n */\nfunction reactErrorHandler(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callback,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (error, errorInfo) => {\n const eventId = captureReactException(error, errorInfo);\n if (callback) {\n callback(error, errorInfo, eventId);\n }\n };\n}\n\nexport { captureReactException, isAtLeastReact17, reactErrorHandler, setCause };\n//# sourceMappingURL=error.js.map\n","/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nexport { DEBUG_BUILD };\n//# sourceMappingURL=debug-build.js.map\n","import { getClient, showReportDialog, withScope } from '@sentry/browser';\nimport { logger } from '@sentry/core';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport * as React from 'react';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { captureReactException } from './error.js';\n\nconst UNKNOWN_COMPONENT = 'unknown';\n\nconst INITIAL_STATE = {\n componentStack: null,\n error: null,\n eventId: null,\n};\n\n/**\n * A ErrorBoundary component that logs errors to Sentry.\n * NOTE: If you are a Sentry user, and you are seeing this stack frame, it means the\n * Sentry React SDK ErrorBoundary caught an error invoking your application code. This\n * is expected behavior and NOT indicative of a bug with the Sentry React SDK.\n */\nclass ErrorBoundary extends React.Component {\n\n constructor(props) {\n super(props);ErrorBoundary.prototype.__init.call(this);\n this.state = INITIAL_STATE;\n this._openFallbackReportDialog = true;\n\n const client = getClient();\n if (client && props.showDialog) {\n this._openFallbackReportDialog = false;\n this._cleanupHook = client.on('afterSendEvent', event => {\n if (!event.type && this._lastEventId && event.event_id === this._lastEventId) {\n showReportDialog({ ...props.dialogOptions, eventId: this._lastEventId });\n }\n });\n }\n }\n\n componentDidCatch(error, errorInfo) {\n const { componentStack } = errorInfo;\n // TODO(v9): Remove this check and type `componentStack` to be React.ErrorInfo['componentStack'].\n const passedInComponentStack = componentStack == null ? undefined : componentStack;\n\n const { beforeCapture, onError, showDialog, dialogOptions } = this.props;\n withScope(scope => {\n if (beforeCapture) {\n beforeCapture(scope, error, passedInComponentStack);\n }\n\n const eventId = captureReactException(error, errorInfo, { mechanism: { handled: !!this.props.fallback } });\n\n if (onError) {\n onError(error, passedInComponentStack, eventId);\n }\n if (showDialog) {\n this._lastEventId = eventId;\n if (this._openFallbackReportDialog) {\n showReportDialog({ ...dialogOptions, eventId });\n }\n }\n\n // componentDidCatch is used over getDerivedStateFromError\n // so that componentStack is accessible through state.\n this.setState({ error, componentStack, eventId });\n });\n }\n\n componentDidMount() {\n const { onMount } = this.props;\n if (onMount) {\n onMount();\n }\n }\n\n componentWillUnmount() {\n const { error, componentStack, eventId } = this.state;\n const { onUnmount } = this.props;\n if (onUnmount) {\n onUnmount(error, componentStack, eventId);\n }\n\n if (this._cleanupHook) {\n this._cleanupHook();\n this._cleanupHook = undefined;\n }\n }\n\n __init() {this.resetErrorBoundary = () => {\n const { onReset } = this.props;\n const { error, componentStack, eventId } = this.state;\n if (onReset) {\n onReset(error, componentStack, eventId);\n }\n this.setState(INITIAL_STATE);\n };}\n\n render() {\n const { fallback, children } = this.props;\n const state = this.state;\n\n if (state.error) {\n let element = undefined;\n if (typeof fallback === 'function') {\n element = React.createElement(fallback, {\n error: state.error,\n componentStack: state.componentStack ,\n resetError: this.resetErrorBoundary,\n eventId: state.eventId ,\n });\n } else {\n element = fallback;\n }\n\n if (React.isValidElement(element)) {\n return element;\n }\n\n if (fallback) {\n DEBUG_BUILD && logger.warn('fallback did not produce a valid ReactElement');\n }\n\n // Fail gracefully if no fallback provided or is not valid\n return null;\n }\n\n if (typeof children === 'function') {\n return (children )();\n }\n return children;\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction withErrorBoundary(\n WrappedComponent,\n errorBoundaryOptions,\n) {\n const componentDisplayName = WrappedComponent.displayName || WrappedComponent.name || UNKNOWN_COMPONENT;\n\n const Wrapped = (props) => (\n React.createElement(ErrorBoundary, { ...errorBoundaryOptions,}\n , React.createElement(WrappedComponent, { ...props,} )\n )\n );\n\n Wrapped.displayName = `errorBoundary(${componentDisplayName})`;\n\n // Copy over static methods from Wrapped component to Profiler HOC\n // See: https://reactjs.org/docs/higher-order-components.html#static-methods-must-be-copied-over\n hoistNonReactStatics(Wrapped, WrappedComponent);\n return Wrapped;\n}\n\nexport { ErrorBoundary, UNKNOWN_COMPONENT, withErrorBoundary };\n//# sourceMappingURL=errorboundary.js.map\n","// src/webauthn-json/base64url.ts\nfunction base64urlToBuffer(baseurl64String) {\n const padding = \"==\".slice(0, (4 - baseurl64String.length % 4) % 4);\n const base64String = baseurl64String.replace(/-/g, \"+\").replace(/_/g, \"/\") + padding;\n const str = atob(base64String);\n const buffer = new ArrayBuffer(str.length);\n const byteView = new Uint8Array(buffer);\n for (let i = 0; i < str.length; i++) {\n byteView[i] = str.charCodeAt(i);\n }\n return buffer;\n}\nfunction bufferToBase64url(buffer) {\n const byteView = new Uint8Array(buffer);\n let str = \"\";\n for (const charCode of byteView) {\n str += String.fromCharCode(charCode);\n }\n const base64String = btoa(str);\n const base64urlString = base64String.replace(/\\+/g, \"-\").replace(\n /\\//g,\n \"_\"\n ).replace(/=/g, \"\");\n return base64urlString;\n}\n\n// src/webauthn-json/convert.ts\nvar copyValue = \"copy\";\nvar convertValue = \"convert\";\nfunction convert(conversionFn, schema2, input) {\n if (schema2 === copyValue) {\n return input;\n }\n if (schema2 === convertValue) {\n return conversionFn(input);\n }\n if (schema2 instanceof Array) {\n return input.map((v) => convert(conversionFn, schema2[0], v));\n }\n if (schema2 instanceof Object) {\n const output = {};\n for (const [key, schemaField] of Object.entries(schema2)) {\n if (schemaField.derive) {\n const v = schemaField.derive(input);\n if (v !== void 0) {\n input[key] = v;\n }\n }\n if (!(key in input)) {\n if (schemaField.required) {\n throw new Error(`Missing key: ${key}`);\n }\n continue;\n }\n if (input[key] == null) {\n output[key] = null;\n continue;\n }\n output[key] = convert(\n conversionFn,\n schemaField.schema,\n input[key]\n );\n }\n return output;\n }\n}\nfunction derived(schema2, derive) {\n return {\n required: true,\n schema: schema2,\n derive\n };\n}\nfunction required(schema2) {\n return {\n required: true,\n schema: schema2\n };\n}\nfunction optional(schema2) {\n return {\n required: false,\n schema: schema2\n };\n}\n\n// src/webauthn-json/basic/schema.ts\nvar publicKeyCredentialDescriptorSchema = {\n type: required(copyValue),\n id: required(convertValue),\n transports: optional(copyValue)\n};\nvar simplifiedExtensionsSchema = {\n appid: optional(copyValue),\n appidExclude: optional(copyValue),\n credProps: optional(copyValue)\n};\nvar simplifiedClientExtensionResultsSchema = {\n appid: optional(copyValue),\n appidExclude: optional(copyValue),\n credProps: optional(copyValue)\n};\nvar credentialCreationOptions = {\n publicKey: required({\n rp: required(copyValue),\n user: required({\n id: required(convertValue),\n name: required(copyValue),\n displayName: required(copyValue)\n }),\n challenge: required(convertValue),\n pubKeyCredParams: required(copyValue),\n timeout: optional(copyValue),\n excludeCredentials: optional([publicKeyCredentialDescriptorSchema]),\n authenticatorSelection: optional(copyValue),\n attestation: optional(copyValue),\n extensions: optional(simplifiedExtensionsSchema)\n }),\n signal: optional(copyValue)\n};\nvar publicKeyCredentialWithAttestation = {\n type: required(copyValue),\n id: required(copyValue),\n rawId: required(convertValue),\n authenticatorAttachment: optional(copyValue),\n response: required({\n clientDataJSON: required(convertValue),\n attestationObject: required(convertValue),\n transports: derived(\n copyValue,\n (response) => {\n var _a;\n return ((_a = response.getTransports) == null ? void 0 : _a.call(response)) || [];\n }\n )\n }),\n clientExtensionResults: derived(\n simplifiedClientExtensionResultsSchema,\n (pkc) => pkc.getClientExtensionResults()\n )\n};\nvar credentialRequestOptions = {\n mediation: optional(copyValue),\n publicKey: required({\n challenge: required(convertValue),\n timeout: optional(copyValue),\n rpId: optional(copyValue),\n allowCredentials: optional([publicKeyCredentialDescriptorSchema]),\n userVerification: optional(copyValue),\n extensions: optional(simplifiedExtensionsSchema)\n }),\n signal: optional(copyValue)\n};\nvar publicKeyCredentialWithAssertion = {\n type: required(copyValue),\n id: required(copyValue),\n rawId: required(convertValue),\n authenticatorAttachment: optional(copyValue),\n response: required({\n clientDataJSON: required(convertValue),\n authenticatorData: required(convertValue),\n signature: required(convertValue),\n userHandle: required(convertValue)\n }),\n clientExtensionResults: derived(\n simplifiedClientExtensionResultsSchema,\n (pkc) => pkc.getClientExtensionResults()\n )\n};\nvar schema = {\n credentialCreationOptions,\n publicKeyCredentialWithAttestation,\n credentialRequestOptions,\n publicKeyCredentialWithAssertion\n};\n\n// src/webauthn-json/basic/api.ts\nfunction createRequestFromJSON(requestJSON) {\n return convert(base64urlToBuffer, credentialCreationOptions, requestJSON);\n}\nfunction createResponseToJSON(credential) {\n return convert(\n bufferToBase64url,\n publicKeyCredentialWithAttestation,\n credential\n );\n}\nasync function create(requestJSON) {\n const credential = await navigator.credentials.create(\n createRequestFromJSON(requestJSON)\n );\n return createResponseToJSON(credential);\n}\nfunction getRequestFromJSON(requestJSON) {\n return convert(base64urlToBuffer, credentialRequestOptions, requestJSON);\n}\nfunction getResponseToJSON(credential) {\n return convert(\n bufferToBase64url,\n publicKeyCredentialWithAssertion,\n credential\n );\n}\nasync function get(requestJSON) {\n const credential = await navigator.credentials.get(\n getRequestFromJSON(requestJSON)\n );\n return getResponseToJSON(credential);\n}\n\n// src/webauthn-json/basic/supported.ts\nfunction supported() {\n return !!(navigator.credentials && navigator.credentials.create && navigator.credentials.get && window.PublicKeyCredential);\n}\nexport {\n create,\n get,\n schema,\n supported\n};\n//# sourceMappingURL=webauthn-json.js.map\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.parse = parse;\nexports.serialize = serialize;\n/**\n * RegExp to match cookie-name in RFC 6265 sec 4.1.1\n * This refers out to the obsoleted definition of token in RFC 2616 sec 2.2\n * which has been replaced by the token definition in RFC 7230 appendix B.\n *\n * cookie-name = token\n * token = 1*tchar\n * tchar = \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" /\n * \"*\" / \"+\" / \"-\" / \".\" / \"^\" / \"_\" /\n * \"`\" / \"|\" / \"~\" / DIGIT / ALPHA\n *\n * Note: Allowing more characters - https://github.com/jshttp/cookie/issues/191\n * Allow same range as cookie value, except `=`, which delimits end of name.\n */\nconst cookieNameRegExp = /^[\\u0021-\\u003A\\u003C\\u003E-\\u007E]+$/;\n/**\n * RegExp to match cookie-value in RFC 6265 sec 4.1.1\n *\n * cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )\n * cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E\n * ; US-ASCII characters excluding CTLs,\n * ; whitespace DQUOTE, comma, semicolon,\n * ; and backslash\n *\n * Allowing more characters: https://github.com/jshttp/cookie/issues/191\n * Comma, backslash, and DQUOTE are not part of the parsing algorithm.\n */\nconst cookieValueRegExp = /^[\\u0021-\\u003A\\u003C-\\u007E]*$/;\n/**\n * RegExp to match domain-value in RFC 6265 sec 4.1.1\n *\n * domain-value = \n * ; defined in [RFC1034], Section 3.5, as\n * ; enhanced by [RFC1123], Section 2.1\n * =