@revenuecat/purchases-js 1.4.2 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11376,7 +11376,7 @@ function Ig(e) {
11376
11376
  }
11377
11377
  return r;
11378
11378
  }
11379
- const Ei = "1.4.2", qg = "https://api.revenuecat.com", zg = "https://e.revenue.cat";
11379
+ const Ei = "1.4.3", qg = "https://api.revenuecat.com", zg = "https://e.revenue.cat";
11380
11380
  var ea;
11381
11381
  (function(e) {
11382
11382
  e[e.CONTINUE = 100] = "CONTINUE", e[e.SWITCHING_PROTOCOLS = 101] = "SWITCHING_PROTOCOLS", e[e.PROCESSING = 102] = "PROCESSING", e[e.EARLY_HINTS = 103] = "EARLY_HINTS", e[e.OK = 200] = "OK", e[e.CREATED = 201] = "CREATED", e[e.ACCEPTED = 202] = "ACCEPTED", e[e.NON_AUTHORITATIVE_INFORMATION = 203] = "NON_AUTHORITATIVE_INFORMATION", e[e.NO_CONTENT = 204] = "NO_CONTENT", e[e.RESET_CONTENT = 205] = "RESET_CONTENT", e[e.PARTIAL_CONTENT = 206] = "PARTIAL_CONTENT", e[e.MULTI_STATUS = 207] = "MULTI_STATUS", e[e.MULTIPLE_CHOICES = 300] = "MULTIPLE_CHOICES", e[e.MOVED_PERMANENTLY = 301] = "MOVED_PERMANENTLY", e[e.MOVED_TEMPORARILY = 302] = "MOVED_TEMPORARILY", e[e.SEE_OTHER = 303] = "SEE_OTHER", e[e.NOT_MODIFIED = 304] = "NOT_MODIFIED", e[e.USE_PROXY = 305] = "USE_PROXY", e[e.TEMPORARY_REDIRECT = 307] = "TEMPORARY_REDIRECT", e[e.PERMANENT_REDIRECT = 308] = "PERMANENT_REDIRECT", e[e.BAD_REQUEST = 400] = "BAD_REQUEST", e[e.UNAUTHORIZED = 401] = "UNAUTHORIZED", e[e.PAYMENT_REQUIRED = 402] = "PAYMENT_REQUIRED", e[e.FORBIDDEN = 403] = "FORBIDDEN", e[e.NOT_FOUND = 404] = "NOT_FOUND", e[e.METHOD_NOT_ALLOWED = 405] = "METHOD_NOT_ALLOWED", e[e.NOT_ACCEPTABLE = 406] = "NOT_ACCEPTABLE", e[e.PROXY_AUTHENTICATION_REQUIRED = 407] = "PROXY_AUTHENTICATION_REQUIRED", e[e.REQUEST_TIMEOUT = 408] = "REQUEST_TIMEOUT", e[e.CONFLICT = 409] = "CONFLICT", e[e.GONE = 410] = "GONE", e[e.LENGTH_REQUIRED = 411] = "LENGTH_REQUIRED", e[e.PRECONDITION_FAILED = 412] = "PRECONDITION_FAILED", e[e.REQUEST_TOO_LONG = 413] = "REQUEST_TOO_LONG", e[e.REQUEST_URI_TOO_LONG = 414] = "REQUEST_URI_TOO_LONG", e[e.UNSUPPORTED_MEDIA_TYPE = 415] = "UNSUPPORTED_MEDIA_TYPE", e[e.REQUESTED_RANGE_NOT_SATISFIABLE = 416] = "REQUESTED_RANGE_NOT_SATISFIABLE", e[e.EXPECTATION_FAILED = 417] = "EXPECTATION_FAILED", e[e.IM_A_TEAPOT = 418] = "IM_A_TEAPOT", e[e.INSUFFICIENT_SPACE_ON_RESOURCE = 419] = "INSUFFICIENT_SPACE_ON_RESOURCE", e[e.METHOD_FAILURE = 420] = "METHOD_FAILURE", e[e.MISDIRECTED_REQUEST = 421] = "MISDIRECTED_REQUEST", e[e.UNPROCESSABLE_ENTITY = 422] = "UNPROCESSABLE_ENTITY", e[e.LOCKED = 423] = "LOCKED", e[e.FAILED_DEPENDENCY = 424] = "FAILED_DEPENDENCY", e[e.UPGRADE_REQUIRED = 426] = "UPGRADE_REQUIRED", e[e.PRECONDITION_REQUIRED = 428] = "PRECONDITION_REQUIRED", e[e.TOO_MANY_REQUESTS = 429] = "TOO_MANY_REQUESTS", e[e.REQUEST_HEADER_FIELDS_TOO_LARGE = 431] = "REQUEST_HEADER_FIELDS_TOO_LARGE", e[e.UNAVAILABLE_FOR_LEGAL_REASONS = 451] = "UNAVAILABLE_FOR_LEGAL_REASONS", e[e.INTERNAL_SERVER_ERROR = 500] = "INTERNAL_SERVER_ERROR", e[e.NOT_IMPLEMENTED = 501] = "NOT_IMPLEMENTED", e[e.BAD_GATEWAY = 502] = "BAD_GATEWAY", e[e.SERVICE_UNAVAILABLE = 503] = "SERVICE_UNAVAILABLE", e[e.GATEWAY_TIMEOUT = 504] = "GATEWAY_TIMEOUT", e[e.HTTP_VERSION_NOT_SUPPORTED = 505] = "HTTP_VERSION_NOT_SUPPORTED", e[e.INSUFFICIENT_STORAGE = 507] = "INSUFFICIENT_STORAGE", e[e.NETWORK_AUTHENTICATION_REQUIRED = 511] = "NETWORK_AUTHENTICATION_REQUIRED";
@@ -11688,10 +11688,11 @@ class Vg {
11688
11688
  }
11689
11689
  }
11690
11690
  function Hg(e) {
11691
- if (!/^rcb_[a-zA-Z0-9_.-]+$/.test(e))
11691
+ const r = /^rcb_[a-zA-Z0-9_.-]+$/, t = /^pdl_[a-zA-Z0-9_.-]+$/;
11692
+ if (!r.test(e) && !t.test(e))
11692
11693
  throw new fe(
11693
11694
  ke.InvalidCredentialsError,
11694
- "Invalid API key. Use your Web Billing API key."
11695
+ "Invalid API key. Use your Web Billing or Paddle API key."
11695
11696
  );
11696
11697
  }
11697
11698
  function so(e) {
@@ -334,7 +334,7 @@
334
334
  }
335
335
 
336
336
  @container layout-query-container (width >= 768px) {.rcb-close-wrapper.svelte-11zapuq {display:none;}.rcb-back-wrapper.svelte-11zapuq {position:absolute;left:-48px;margin-left:0;}
337
- }`};function _g(e,r){V(r,!0),B(e,pg);const t=k=>k==null||k==null||k==""?null:k,a=E(()=>{var k;return t((k=r.brandingInfo)==null?void 0:k.app_icon)}),n=E(()=>{var k;return t((k=r.brandingInfo)==null?void 0:k.app_icon_webp)}),o=E(()=>{var k;return t((k=r.brandingInfo)==null?void 0:k.app_wordmark)}),i=E(()=>{var k;return t((k=r.brandingInfo)==null?void 0:k.app_wordmark_webp)}),s=E(()=>d(a)?Ut(d(a)):null),l=E(()=>d(n)?Ut(d(n)):null),c=E(()=>d(o)?Ut(d(o)):null),u=E(()=>d(i)?Ut(d(i)):null),_=()=>{r.onClose&&r.onClose()};var p=ug(),g=x(p);{var m=k=>{var w=cg(),A=x(w);ng(A,{$$events:{click:_}}),b(k,w)};N(g,k=>{r.showCloseButton&&k(m)})}var f=O(g,2),v=x(f),h=x(v);{var y=k=>{lg(k,{get src(){return d(c)},get srcWebp(){return d(u)}})},P=k=>{var w=te(),A=Y(w);{var Z=G=>{rg(G,{get src(){return d(s)},get srcWebp(){return d(l)}})};N(A,G=>{d(s)!==null&&d(l)!==null&&G(Z)},!0)}b(k,w)};N(h,k=>{d(c)!==null?k(y):k(P,!1)})}var T=O(h,2);{var S=k=>{se(k,{size:"body-base",children:(w,A)=>{var Z=de();z(()=>{var G;return ne(Z,(G=r.brandingInfo)==null?void 0:G.app_name)}),b(w,Z)},$$slots:{default:!0}})};N(T,k=>{d(c)===null&&k(S)})}var D=O(f,2);{var W=k=>{var w=dg(),A=x(w);Ti(A,{$$events:{click:_}}),b(k,w)};N(D,k=>{r.showCloseButton&&k(W)})}z(()=>kr(p,"rcb-with-close-button",r.showCloseButton)),b(e,p),H()}var gg=I("<!> <!> <!> <!>",1);function mg(e,r){V(r,!0);const t=R(r,"onClose",3,void 0);let a=J(U(r.defaultPriceBreakdown??{currency:r.productDetails.currentPrice.currency,totalAmountInMicros:r.productDetails.currentPrice.amountMicros,totalExcludingTaxInMicros:r.productDetails.currentPrice.amountMicros,taxCalculationStatus:"unavailable",taxAmountInMicros:null,taxBreakdown:null}));const n=o=>{F(a,U(o))};K_(e,{get brandingInfo(){return r.brandingInfo},get isInElement(){return r.isInElement},get isSandbox(){return r.isSandbox},get onClose(){return t()},navbarHeaderContent:l=>{var c=E(()=>!r.isInElement&&!!t());_g(l,{get brandingInfo(){return r.brandingInfo},get onClose(){return t()},get showCloseButton(){return d(c)}})},navbarBodyContent:l=>{var c=E(()=>{var u,_;return((_=(u=r.brandingInfo)==null?void 0:u.appearance)==null?void 0:_.show_product_description)??!1});k_(l,{get productDetails(){return r.productDetails},get purchaseOption(){return r.purchaseOptionToUse},get showProductDescription(){return d(c)},get priceBreakdown(){return d(a)}})},mainContent:l=>{var c=gg(),u=Y(c);{var _=y=>{Zp(y)};N(u,y=>{r.currentPage==="payment-entry-loading"&&y(_)})}var p=O(u,2);{var g=y=>{gp(y,{get productDetails(){return r.productDetails},get purchaseOption(){return r.purchaseOptionToUse},get brandingInfo(){return r.brandingInfo},get purchaseOperationHelper(){return r.purchaseOperationHelper},get gatewayParams(){return r.gatewayParams},get customerEmail(){return r.customerEmail},get defaultPriceBreakdown(){return r.defaultPriceBreakdown},get onContinue(){return r.onContinue},get onError(){return r.onError},onPriceBreakdownUpdated:n})};N(p,y=>{r.currentPage==="payment-entry"&&y(g)})}var m=O(p,2);{var f=y=>{var P=E(()=>{var S;return((S=r.brandingInfo)==null?void 0:S.support_email)??null}),T=E(()=>{var S;return((S=r.brandingInfo)==null?void 0:S.app_name)??null});Gp(y,{get lastError(){return r.lastError},get productDetails(){return r.productDetails},get supportEmail(){return d(P)},get onDismiss(){return r.closeWithError},get appName(){return d(T)}})};N(m,y=>{r.currentPage==="error"&&y(f)})}var v=O(m,2);{var h=y=>{Xp(y,{get onContinue(){return r.onContinue}})};N(v,y=>{r.currentPage==="success"&&y(h)})}b(l,c)},$$slots:{navbarHeaderContent:!0,navbarBodyContent:!0,mainContent:!0}}),H()}function fg(e){return e.trim()===""?"You need to provide your email address to continue.":e.match(/^[^@]+@[^@]+\.[^@]+$/)?null:"Email is not valid. Please provide a valid email address."}function yg(e){if(e&&!e.match(/^[A-Z]{3}$/)){const r=`Currency code ${e} is not valid. Please provide a valid ISO 4217 currency code.`;throw Q.errorLog(r),new ve(Se.ConfigurationError,r)}}function bg(e,r){V(r,!0);const t=R(r,"customTranslations",19,()=>({})),a=r.customerEmail?fg(r.customerEmail):null;let n=J(U(a?void 0:r.customerEmail)),o=r.rcPackage.webBillingProduct,i=J(null);const s=r.rcPackage.webBillingProduct.identifier??null;let l=J("payment-entry-loading"),c=J(null),u=J(null),_=J(U({})),p=new ya(t(),r.selectedLocale,r.defaultLocale);var g=Xo(p);ko(We,g),He(()=>{r.isInElement||(document.documentElement.style.height="100%",document.body.style.height="100%",document.documentElement.style.overflow="hidden")}),Ft(()=>{r.isInElement||(document.documentElement.style.height="auto",document.body.style.height="auto",document.documentElement.style.overflow="auto")}),ko(bn,r.eventsTracker),He(async()=>{if(s===null){f(new ge(ue.ErrorSettingUpPurchase,"Product ID was not set before purchase."));return}r.purchaseOperationHelper.checkoutStart(r.appUserId,s,r.purchaseOption,r.rcPackage.webBillingProduct.presentedOfferingContext,d(n),r.metadata).then(P=>{F(i,null),F(l,"payment-entry"),F(_,U(P.gateway_params))}).catch(P=>{if(P.errorCode===ue.MissingEmailError)return F(n,void 0),r.purchaseOperationHelper.checkoutStart(r.appUserId,s,r.purchaseOption,r.rcPackage.webBillingProduct.presentedOfferingContext,d(n),r.metadata).then(T=>{F(i,null),F(l,"payment-entry"),F(_,U(T.gateway_params))}).catch(T=>{f(T)});f(P)})});const m=()=>{if(d(l)==="payment-entry"){r.purchaseOperationHelper.pollCurrentPurchaseForCompletion().then(P=>{F(l,"success"),F(c,U(P.redemptionInfo)),F(u,U(P.operationSessionId))}).catch(P=>{f(P)});return}if(d(l)==="success"||d(l)==="error"){r.onFinished(d(u),d(c));return}F(l,"success")},f=P=>{const T=_u({errorCode:P.getErrorCode().toString(),errorMessage:P.message});r.eventsTracker.trackSDKEvent(T),F(i,U(P)),F(l,"error")},v=()=>{r.onError(d(i)??new ge(ue.UnknownError,"Unknown error without state set."))};var h=E(()=>r.purchases.isSandbox()),y=E(()=>d(n)??null);mg(e,{get isSandbox(){return d(h)},get currentPage(){return d(l)},get brandingInfo(){return r.brandingInfo},productDetails:o,get purchaseOptionToUse(){return r.purchaseOption},get lastError(){return d(i)},get gatewayParams(){return d(_)},get purchaseOperationHelper(){return r.purchaseOperationHelper},get isInElement(){return r.isInElement},get customerEmail(){return d(y)},closeWithError:v,onContinue:m,onError:f,get onClose(){return r.onClose}}),H()}function Ii(e){return e==null?!0:new Date(e)>new Date}function hg(e,r,t,a){const n=r.product_identifier;if(n in t)return vg(e,r,t[n]);if(n in a)return kg(e,r,a[n]);throw new ve(Se.CustomerInfoError,"Could not find entitlement product in subscriptions or non-subscriptions.")}function vg(e,r,t){return{identifier:e,isActive:Ii(r.expires_date),willRenew:qi(r.expires_date,t),store:(t==null?void 0:t.store)??"unknown",latestPurchaseDate:new Date(r.purchase_date),originalPurchaseDate:new Date(r.purchase_date),expirationDate:fr(r.expires_date),productIdentifier:r.product_identifier,productPlanIdentifier:r.product_plan_identifier??null,unsubscribeDetectedAt:fr(t==null?void 0:t.unsubscribe_detected_at),billingIssueDetectedAt:fr(t==null?void 0:t.billing_issues_detected_at),isSandbox:(t==null?void 0:t.is_sandbox)??!1,periodType:(t==null?void 0:t.period_type)??"normal",ownershipType:(t==null?void 0:t.ownership_type)??"UNKNOWN"}}function kg(e,r,t){return{identifier:e,isActive:!0,willRenew:!1,store:t.store,latestPurchaseDate:new Date(r.purchase_date),originalPurchaseDate:new Date(t.original_purchase_date),expirationDate:null,productIdentifier:r.product_identifier,productPlanIdentifier:null,unsubscribeDetectedAt:null,billingIssueDetectedAt:null,isSandbox:t.is_sandbox,periodType:"normal",ownershipType:"UNKNOWN"}}function wg(e,r,t){const a={},n={};for(const o in e){const i=hg(o,e[o],r,t);a[o]=i,i.isActive&&(n[o]=i)}return{all:a,active:n}}function fr(e){return e==null?null:new Date(e)}function xg(e){const r=Sg(e),t=e.subscriber,a=Tg(t.non_subscriptions),n=Object.entries(e.subscriber.non_subscriptions).flatMap(([s,l])=>l.map(c=>({transactionIdentifier:c.id,productIdentifier:s,purchaseDate:new Date(c.purchase_date||c.original_purchase_date),storeTransactionId:c.store_transaction_id||null,store:c.store}))),o=new Date(e.request_date),i=Object.fromEntries(Object.entries(e.subscriber.subscriptions).map(([s,l])=>[s,{productIdentifier:s,purchaseDate:new Date(l.purchase_date),originalPurchaseDate:fr(l.original_purchase_date),expiresDate:fr(l.expires_date),store:l.store,unsubscribeDetectedAt:fr(l.unsubscribe_detected_at),isSandbox:l.is_sandbox,billingIssuesDetectedAt:fr(l.billing_issues_detected_at),gracePeriodExpiresDate:fr(l.grace_period_expires_date),ownershipType:l.ownership_type??"UNKNOWN",periodType:l.period_type,refundedAt:fr(l.refunded_at),storeTransactionId:l.store_transaction_id||null,isActive:Ii(l.expires_date),willRenew:qi(l.expires_date,l)}]));return{entitlements:wg(t.entitlements,t.subscriptions,a),allExpirationDatesByProduct:r,allPurchaseDatesByProduct:Pg(e,a),activeSubscriptions:Eg(r),managementURL:t.management_url,requestDate:o,firstSeenDate:new Date(t.first_seen),originalPurchaseDate:fr(t.original_purchase_date),originalAppUserId:e.subscriber.original_app_user_id,nonSubscriptionTransactions:n,subscriptionsByProductIdentifier:i}}function qi(e,r){if(r==null)return!1;const t=r.store=="promotional",a=e==null,n=r.unsubscribe_detected_at!=null,o=r.billing_issues_detected_at!=null;return!(t||a||n||o)}function Pg(e,r){const t={};for(const a in e.subscriber.subscriptions){const n=e.subscriber.subscriptions[a];t[a]=new Date(n.purchase_date)}for(const a in r){const n=r[a].purchase_date;n==null?t[a]=null:t[a]=new Date(n)}return t}function Sg(e){const r={};for(const t in e.subscriber.subscriptions){const a=e.subscriber.subscriptions[t];a.expires_date==null?r[t]=null:r[t]=new Date(a.expires_date)}return r}function Eg(e){const r=new Set,t=new Date;for(const a in e){const n=e[a];(n==null||n>t)&&r.add(a)}return r}function Tg(e){const r={};for(const t in e){if(e[t].length===0)continue;const a=e[t].length;r[t]=e[t][a-1]}return r}const zi="1.4.2",Ig="https://api.revenuecat.com",qg="https://e.revenue.cat";var qa;(function(e){e[e.CONTINUE=100]="CONTINUE",e[e.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",e[e.PROCESSING=102]="PROCESSING",e[e.EARLY_HINTS=103]="EARLY_HINTS",e[e.OK=200]="OK",e[e.CREATED=201]="CREATED",e[e.ACCEPTED=202]="ACCEPTED",e[e.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",e[e.NO_CONTENT=204]="NO_CONTENT",e[e.RESET_CONTENT=205]="RESET_CONTENT",e[e.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",e[e.MULTI_STATUS=207]="MULTI_STATUS",e[e.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",e[e.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",e[e.MOVED_TEMPORARILY=302]="MOVED_TEMPORARILY",e[e.SEE_OTHER=303]="SEE_OTHER",e[e.NOT_MODIFIED=304]="NOT_MODIFIED",e[e.USE_PROXY=305]="USE_PROXY",e[e.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",e[e.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.UNAUTHORIZED=401]="UNAUTHORIZED",e[e.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",e[e.FORBIDDEN=403]="FORBIDDEN",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",e[e.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",e[e.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",e[e.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",e[e.CONFLICT=409]="CONFLICT",e[e.GONE=410]="GONE",e[e.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",e[e.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",e[e.REQUEST_TOO_LONG=413]="REQUEST_TOO_LONG",e[e.REQUEST_URI_TOO_LONG=414]="REQUEST_URI_TOO_LONG",e[e.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",e[e.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",e[e.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",e[e.IM_A_TEAPOT=418]="IM_A_TEAPOT",e[e.INSUFFICIENT_SPACE_ON_RESOURCE=419]="INSUFFICIENT_SPACE_ON_RESOURCE",e[e.METHOD_FAILURE=420]="METHOD_FAILURE",e[e.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",e[e.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",e[e.LOCKED=423]="LOCKED",e[e.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",e[e.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",e[e.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",e[e.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",e[e.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",e[e.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",e[e.BAD_GATEWAY=502]="BAD_GATEWAY",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",e[e.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",e[e.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",e[e.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",e[e.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED"})(qa||(qa={}));function za(e){return e?e.startsWith("rcb_sb_"):!1}async function Sr(e,r,t){const{apiKey:a,body:n,headers:o,httpConfig:i}=r,l=`${(i==null?void 0:i.proxyURL)??Ig}${e.urlPath()}`;try{const c=await fetch(l,{method:e.method,headers:Li(a,o,i==null?void 0:i.additionalHeaders),body:Dg(n),signal:t});return await zg(c,e),await c.json()}catch(c){throw c instanceof TypeError?new ve(Se.NetworkError,jt.getPublicMessage(Se.NetworkError),c.message):c}}async function zg(e,r){const t=e.status;if(t>=qa.INTERNAL_SERVER_ERROR)En(r,t,await e.text());else if(t>=qa.BAD_REQUEST){const a=await e.json(),n=a?JSON.stringify(a):null,o=a==null?void 0:a.code,i=a==null?void 0:a.message;if(o!=null){const s=jt.convertCodeToBackendErrorCode(o);if(s==null)En(r,t,n,o);else throw ve.getForBackendError(s,i)}else En(r,t,n)}}function En(e,r,t,a){throw new ve(Se.UnknownBackendError,"Unknown backend error.",`Request: ${e.name}. Status code: ${r}. Body: ${t}.`,{backendErrorCode:a})}function Dg(e){return e==null?null:JSON.stringify(e)}const Di="Authorization",Ai="Content-Type",Fi="Accept",ji="X-Platform",Mi="X-Version",Ni="X-Platform-Flavor",Ci="X-Platform-Flavor-Version",Oi="X-Is-Sandbox",Ag=new Set([Di,Ai,Fi,ji,Mi,Oi,Ni,Ci]);function Li(e,r,t){let a={[Di]:`Bearer ${e}`,[Ai]:"application/json",[Fi]:"application/json",[ji]:"web",[Mi]:zi,[Oi]:`${za(e)}`};const n=Da.getPlatformInfo();if(n){const o={[Ni]:n.flavor,[Ci]:n.version};a={...a,...o}}return r&&(a={...a,...r}),t&&(a={...t,...a}),a}const Tn="/v1/subscribers",mt="/rcbilling/v1";class Fg{constructor(r){j(this,"appUserId");j(this,"method","GET");j(this,"name","getOfferings");this.appUserId=r}urlPath(){const r=encodeURIComponent(this.appUserId);return`${Tn}/${r}/offerings`}}class jg{constructor(r,t,a){j(this,"method","GET");j(this,"name","getProducts");j(this,"appUserId");j(this,"productIds");j(this,"currency");this.appUserId=r,this.productIds=t,this.currency=a}urlPath(){const r=encodeURIComponent(this.appUserId),t=this.productIds.map(encodeURIComponent).join("&id="),a=this.currency?`&currency=${this.currency}`:"";return`${mt}/subscribers/${r}/products?id=${t}${a}`}}class Mg{constructor(r){j(this,"method","GET");j(this,"name","getCustomerInfo");j(this,"appUserId");this.appUserId=r}urlPath(){const r=encodeURIComponent(this.appUserId);return`${Tn}/${r}`}}class Ng{constructor(){j(this,"method","GET");j(this,"name","getBrandingInfo")}urlPath(){return`${mt}/branding`}}class Cg{constructor(){j(this,"method","POST");j(this,"name","postCheckoutStart")}urlPath(){return`${mt}/checkout/start`}}class Og{constructor(r){j(this,"method","POST");j(this,"name","postCheckoutCalculateTax");j(this,"operationSessionId");this.operationSessionId=r}urlPath(){return`${mt}/checkout/${this.operationSessionId}/calculate_taxes`}}class Lg{constructor(r){j(this,"method","POST");j(this,"name","postCheckoutComplete");j(this,"operationSessionId");this.operationSessionId=r}urlPath(){return`${mt}/checkout/${this.operationSessionId}/complete`}}class Bg{constructor(r){j(this,"method","GET");j(this,"name","getCheckoutStatus");j(this,"operationSessionId");this.operationSessionId=r}urlPath(){return`${mt}/checkout/${this.operationSessionId}`}}class Rg{constructor(r){j(this,"method","POST");j(this,"name","setAttributes");j(this,"appUserId");this.appUserId=r}urlPath(){const r=encodeURIComponent(this.appUserId);return`${Tn}/${r}/attributes`}}const In={};class Ug{constructor(r,t=In){j(this,"API_KEY");j(this,"httpConfig");j(this,"isSandbox");this.API_KEY=r,this.httpConfig=t,this.isSandbox=za(r)}getIsSandbox(){return this.isSandbox}async getOfferings(r){return await Sr(new Fg(r),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getCustomerInfo(r){return await Sr(new Mg(r),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getProducts(r,t,a){return await Sr(new jg(r,t,a),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getBrandingInfo(){return await Sr(new Ng,{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async postCheckoutStart(r,t,a,n,o,i,s=void 0){const l={app_user_id:r,product_id:t,email:i,price_id:n.priceId,presented_offering_identifier:a.offeringIdentifier,trace_id:o};return s&&(l.metadata=s),n.id!=="base_option"&&(l.offer_id=n.id),a.targetingContext&&(l.applied_targeting_rule={rule_id:a.targetingContext.ruleId,revision:a.targetingContext.revision}),a.placementIdentifier&&(l.presented_placement_identifier=a.placementIdentifier),await Sr(new Cg,{apiKey:this.API_KEY,body:l,httpConfig:this.httpConfig})}async postCheckoutCalculateTax(r,t,a,n){const o={country_code:t,postal_code:a};return await Sr(new Og(r),{apiKey:this.API_KEY,body:o,httpConfig:this.httpConfig},n)}async postCheckoutComplete(r,t){const a={email:t};return await Sr(new Lg(r),{apiKey:this.API_KEY,body:a,httpConfig:this.httpConfig})}async getCheckoutStatus(r){return await Sr(new Bg(r),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async setAttributes(r,t){const a=Date.now(),n={};for(const[i,s]of Object.entries(t))n[i]={value:s,updated_at_ms:a};const o={attributes:n};return await Sr(new Rg(r),{apiKey:this.API_KEY,body:o,httpConfig:this.httpConfig})}}function Vg(e){if(!/^rcb_[a-zA-Z0-9_.-]+$/.test(e))throw new ve(Se.InvalidCredentialsError,"Invalid API key. Use your Web Billing API key.")}function Bi(e){if(!e||new Set(["no_user","null","none","nil","(null)","NaN","\\x00","","unidentified","undefined","unknown"]).has(e)||e.includes("/"))throw new ve(Se.InvalidAppUserIdError,'Provided user id: "'+(e??"[Not provided]")+'" is not valid. See https://www.revenuecat.com/docs/customers/user-ids#tips-for-setting-app-user-ids for more information.')}function Hg(e){if(e!=null&&e.endsWith("/"))throw new ve(Se.ConfigurationError,"Invalid proxy URL. The proxy URL should not end with a trailing slash.")}function Wg(e){if(e){for(const r in e)if(Ag.has(r))throw new ve(Se.ConfigurationError,"Invalid additional headers. Some headers are reserved for internal use.")}}var qn=(e=>(e.Current="current",e))(qn||{});function Yg(e,r){async function t(...a){return await this.preload(),await e.call(this,...a)}return t}const Ri=(e,r)=>{const t={...e.webBillingProduct,presentedOfferingContext:{...e.webBillingProduct.presentedOfferingContext,placementIdentifier:r}};return{...e,webBillingProduct:t,rcBillingProduct:t}},Zr=(e,r)=>e==null?null:Ri(e,r),Gg=(e,r,t)=>{const a=e.offering_ids_by_placement??null;if(a==null)return null;const n=e.fallback_offering_id??null;let o;if(t in a){const s=a[t]??null;if(s==null)return null;o=r[s],o==null&&(o=r[n])}else o=r[n];if(o==null)return null;const i=Object.fromEntries(Object.entries(o.packagesById).map(([s,l])=>[s,Ri(l,t)]));return{...o,packagesById:i,availablePackages:Object.values(i),weekly:Zr(o.weekly,t),monthly:Zr(o.monthly,t),twoMonth:Zr(o.twoMonth,t),threeMonth:Zr(o.threeMonth,t),sixMonth:Zr(o.sixMonth,t),annual:Zr(o.annual,t),lifetime:Zr(o.lifetime,t)}};function Xg(e,r){const t={};r.product_details.forEach(o=>{t[o.identifier]=o});const a={};e.offerings.forEach(o=>{const i=o.identifier===e.current_offering_id,s=xp(i,o,t,e.targeting);s!=null&&(a[o.identifier]=s)});const n=e.current_offering_id?a[e.current_offering_id]??null:null;return Object.keys(a).length==0&&Q.debugLog("Empty offerings. Please make sure you've configured offerings correctly in the RevenueCat dashboard and that the products are properly configured."),{all:a,current:n}}const Zg=1000001;function Kg(e){return e.webBillingProduct.defaultPurchaseOption}function Ui(e,r,t,a=!1){return t.translate(L.PaywallVariablesPricePerPeriod,{formattedPrice:e,period:r.base.period?t.translatePeriod(r.base.period.number,r.base.period.unit,{noWhitespace:!0,short:!a}):""})}function Jg(e,r){return e.unit==="year"?r.translatePeriod(e.number*12,Ye.Month):r.translatePeriod(e.number,e.unit)}function Qg({price:e,period:r,translator:t}){const a=t.formatPrice(e.amountMicros,e.currency);return r?r.unit==="year"?t.formatPrice(e.amountMicros/12/4,e.currency):r.unit==="month"||r.unit==="week"&&r.number>1?t.formatPrice(e.amountMicros/r.number,e.currency):r.unit==="day"?t.formatPrice(e.amountMicros*7/r.number,e.currency):a:a}function $g({price:e,period:r,translator:t}){const a=t.formatPrice(e.amountMicros,e.currency);return!r||!r.number?a:r.unit==="year"?t.formatPrice(e.amountMicros/12,e.currency):r.unit==="month"&&r.number>1?t.formatPrice(e.amountMicros/r.number,e.currency):r.unit==="week"?t.formatPrice(e.amountMicros*4/r.number,e.currency):r.unit==="day"?t.formatPrice(e.amountMicros*30/r.number,e.currency):a}function Vi({price:e,period:r,full:t=!1,translator:a}){if(!r||!r.number||r.unit===Ye.Month&&r.number==1)return a.formatPrice(e.amountMicros,e.currency);let n="";switch(r.unit){case Ye.Year:n=a.formatPrice(e.amountMicros/12,e.currency);break;case Ye.Month:n=a.formatPrice(e.amountMicros/r.number,e.currency);break;case Ye.Week:n=a.formatPrice(e.amountMicros*4/r.number,e.currency);break;case Ye.Day:n=a.formatPrice(e.amountMicros*30/r.number,e.currency);break}return a.translate(L.PaywallVariablesTotalPriceAndPerMonth,{formattedPrice:a.formatPrice(e.amountMicros,e.currency),period:a.translatePeriod(r.number,r.unit,{noWhitespace:!0,short:!t}),formattedPricePerMonth:n,monthPeriod:a.translatePeriodUnit(Ye.Month,{noWhitespace:!0,short:!t})})}function em(e,r){const t=e.availablePackages,a=t.reduce((n,o)=>n.webBillingProduct.currentPrice.amountMicros>o.webBillingProduct.currentPrice.amountMicros?n:o);return t.reduce((n,o)=>(n[o.identifier]=rm(o,a,r),n),{})}function rm(e,r,t){const a=e.webBillingProduct,n=t.formatPrice(a.currentPrice.amountMicros,a.currentPrice.currency),o=Kg(e),i=a.productType,s={product_name:a.title,price:n,price_per_period:"",price_per_period_full:"",total_price_and_per_month:"",total_price_and_per_month_full:"",sub_price_per_month:"",sub_price_per_week:"",sub_duration:"",sub_duration_in_months:"",sub_period:"",sub_period_length:"",sub_period_abbreviated:"",sub_offer_duration:void 0,sub_offer_duration_2:void 0,sub_offer_price:void 0,sub_offer_price_2:void 0,sub_relative_discount:""};if(i===Or.Subscription&&o){s.price_per_period=Ui(n,o,t),s.price_per_period_full=Ui(n,o,t,!0);const l=o.base.period;s.total_price_and_per_month=Vi({price:a.currentPrice,period:l,translator:t}),s.total_price_and_per_month_full=Vi({price:a.currentPrice,period:l,full:!0,translator:t}),s.sub_price_per_month=$g({price:a.currentPrice,period:l,translator:t}),s.sub_price_per_week=Qg({price:a.currentPrice,period:l,translator:t}),s.sub_duration=t.translatePeriod(l==null?void 0:l.number,l==null?void 0:l.unit),s.sub_duration_in_months=Jg(l,t),s.sub_period=t.translatePeriodFrequency(l==null?void 0:l.number,l==null?void 0:l.unit),s.sub_period_length=l?t.translatePeriodUnit(l.unit,{noWhitespace:!0}):void 0,s.sub_period_abbreviated=l?t.translatePeriodUnit(l.unit,{noWhitespace:!0,short:!0}):void 0;const c=a.currentPrice.amountMicros,u=r.webBillingProduct.currentPrice.amountMicros,_=((u-c)*100/u).toFixed(0);s.sub_relative_discount=c===u?"":t.translate(L.PaywallVariablesSubRelativeDiscount,{discount:_})}return(i===Or.NonConsumable||i===Or.Consumable)&&o&&(s.price=n,s.price_per_period=n,s.price_per_period_full=n,s.total_price_and_per_month=n,s.sub_price_per_month=n,s.sub_duration=t.translate(L.PeriodsLifetime),s.sub_duration_in_months=t.translate(L.PeriodsLifetime),s.sub_period=t.translate(L.PeriodsLifetime),s.sub_price_per_week=void 0,s.sub_relative_discount=void 0,s.price_per_period_full=n,s.total_price_and_per_month_full=n,s.sub_period_length=void 0,s.sub_period_abbreviated=void 0),s}const Ee=[];for(let e=0;e<256;++e)Ee.push((e+256).toString(16).slice(1));function tm(e,r=0){return(Ee[e[r+0]]+Ee[e[r+1]]+Ee[e[r+2]]+Ee[e[r+3]]+"-"+Ee[e[r+4]]+Ee[e[r+5]]+"-"+Ee[e[r+6]]+Ee[e[r+7]]+"-"+Ee[e[r+8]]+Ee[e[r+9]]+"-"+Ee[e[r+10]]+Ee[e[r+11]]+Ee[e[r+12]]+Ee[e[r+13]]+Ee[e[r+14]]+Ee[e[r+15]]).toLowerCase()}let zn;const am=new Uint8Array(16);function nm(){if(!zn){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");zn=crypto.getRandomValues.bind(crypto)}return zn(am)}const Hi={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Wi(e,r,t){var n;if(Hi.randomUUID&&!e)return Hi.randomUUID();e=e||{};const a=e.random??((n=e.rng)==null?void 0:n.call(e))??nm();if(a.length<16)throw new Error("Random bytes length must be >= 16");return a[6]=a[6]&15|64,a[8]=a[8]&63|128,tm(a)}var om=/(%?)(%([sdijo]))/g;function im(e,r){switch(r){case"s":return e;case"d":case"i":return Number(e);case"j":return JSON.stringify(e);case"o":{if(typeof e=="string")return e;const t=JSON.stringify(e);return t==="{}"||t==="[]"||/^\[object .+?\]$/.test(t)?e:t}}}function Dn(e,...r){if(r.length===0)return e;let t=0,a=e.replace(om,(n,o,i,s)=>{const l=r[t],c=im(l,s);return o?n:(t++,c)});return t<r.length&&(a+=` ${r.slice(t).join(" ")}`),a=a.replace(/%{2,2}/g,"%"),a}var sm=2;function lm(e){if(!e.stack)return;const r=e.stack.split(`
337
+ }`};function _g(e,r){V(r,!0),B(e,pg);const t=k=>k==null||k==null||k==""?null:k,a=E(()=>{var k;return t((k=r.brandingInfo)==null?void 0:k.app_icon)}),n=E(()=>{var k;return t((k=r.brandingInfo)==null?void 0:k.app_icon_webp)}),o=E(()=>{var k;return t((k=r.brandingInfo)==null?void 0:k.app_wordmark)}),i=E(()=>{var k;return t((k=r.brandingInfo)==null?void 0:k.app_wordmark_webp)}),s=E(()=>d(a)?Ut(d(a)):null),l=E(()=>d(n)?Ut(d(n)):null),c=E(()=>d(o)?Ut(d(o)):null),u=E(()=>d(i)?Ut(d(i)):null),_=()=>{r.onClose&&r.onClose()};var p=ug(),g=x(p);{var m=k=>{var w=cg(),A=x(w);ng(A,{$$events:{click:_}}),b(k,w)};N(g,k=>{r.showCloseButton&&k(m)})}var f=O(g,2),v=x(f),h=x(v);{var y=k=>{lg(k,{get src(){return d(c)},get srcWebp(){return d(u)}})},P=k=>{var w=te(),A=Y(w);{var Z=G=>{rg(G,{get src(){return d(s)},get srcWebp(){return d(l)}})};N(A,G=>{d(s)!==null&&d(l)!==null&&G(Z)},!0)}b(k,w)};N(h,k=>{d(c)!==null?k(y):k(P,!1)})}var T=O(h,2);{var S=k=>{se(k,{size:"body-base",children:(w,A)=>{var Z=de();z(()=>{var G;return ne(Z,(G=r.brandingInfo)==null?void 0:G.app_name)}),b(w,Z)},$$slots:{default:!0}})};N(T,k=>{d(c)===null&&k(S)})}var D=O(f,2);{var W=k=>{var w=dg(),A=x(w);Ti(A,{$$events:{click:_}}),b(k,w)};N(D,k=>{r.showCloseButton&&k(W)})}z(()=>kr(p,"rcb-with-close-button",r.showCloseButton)),b(e,p),H()}var gg=I("<!> <!> <!> <!>",1);function mg(e,r){V(r,!0);const t=R(r,"onClose",3,void 0);let a=J(U(r.defaultPriceBreakdown??{currency:r.productDetails.currentPrice.currency,totalAmountInMicros:r.productDetails.currentPrice.amountMicros,totalExcludingTaxInMicros:r.productDetails.currentPrice.amountMicros,taxCalculationStatus:"unavailable",taxAmountInMicros:null,taxBreakdown:null}));const n=o=>{F(a,U(o))};K_(e,{get brandingInfo(){return r.brandingInfo},get isInElement(){return r.isInElement},get isSandbox(){return r.isSandbox},get onClose(){return t()},navbarHeaderContent:l=>{var c=E(()=>!r.isInElement&&!!t());_g(l,{get brandingInfo(){return r.brandingInfo},get onClose(){return t()},get showCloseButton(){return d(c)}})},navbarBodyContent:l=>{var c=E(()=>{var u,_;return((_=(u=r.brandingInfo)==null?void 0:u.appearance)==null?void 0:_.show_product_description)??!1});k_(l,{get productDetails(){return r.productDetails},get purchaseOption(){return r.purchaseOptionToUse},get showProductDescription(){return d(c)},get priceBreakdown(){return d(a)}})},mainContent:l=>{var c=gg(),u=Y(c);{var _=y=>{Zp(y)};N(u,y=>{r.currentPage==="payment-entry-loading"&&y(_)})}var p=O(u,2);{var g=y=>{gp(y,{get productDetails(){return r.productDetails},get purchaseOption(){return r.purchaseOptionToUse},get brandingInfo(){return r.brandingInfo},get purchaseOperationHelper(){return r.purchaseOperationHelper},get gatewayParams(){return r.gatewayParams},get customerEmail(){return r.customerEmail},get defaultPriceBreakdown(){return r.defaultPriceBreakdown},get onContinue(){return r.onContinue},get onError(){return r.onError},onPriceBreakdownUpdated:n})};N(p,y=>{r.currentPage==="payment-entry"&&y(g)})}var m=O(p,2);{var f=y=>{var P=E(()=>{var S;return((S=r.brandingInfo)==null?void 0:S.support_email)??null}),T=E(()=>{var S;return((S=r.brandingInfo)==null?void 0:S.app_name)??null});Gp(y,{get lastError(){return r.lastError},get productDetails(){return r.productDetails},get supportEmail(){return d(P)},get onDismiss(){return r.closeWithError},get appName(){return d(T)}})};N(m,y=>{r.currentPage==="error"&&y(f)})}var v=O(m,2);{var h=y=>{Xp(y,{get onContinue(){return r.onContinue}})};N(v,y=>{r.currentPage==="success"&&y(h)})}b(l,c)},$$slots:{navbarHeaderContent:!0,navbarBodyContent:!0,mainContent:!0}}),H()}function fg(e){return e.trim()===""?"You need to provide your email address to continue.":e.match(/^[^@]+@[^@]+\.[^@]+$/)?null:"Email is not valid. Please provide a valid email address."}function yg(e){if(e&&!e.match(/^[A-Z]{3}$/)){const r=`Currency code ${e} is not valid. Please provide a valid ISO 4217 currency code.`;throw Q.errorLog(r),new ve(Se.ConfigurationError,r)}}function bg(e,r){V(r,!0);const t=R(r,"customTranslations",19,()=>({})),a=r.customerEmail?fg(r.customerEmail):null;let n=J(U(a?void 0:r.customerEmail)),o=r.rcPackage.webBillingProduct,i=J(null);const s=r.rcPackage.webBillingProduct.identifier??null;let l=J("payment-entry-loading"),c=J(null),u=J(null),_=J(U({})),p=new ya(t(),r.selectedLocale,r.defaultLocale);var g=Xo(p);ko(We,g),He(()=>{r.isInElement||(document.documentElement.style.height="100%",document.body.style.height="100%",document.documentElement.style.overflow="hidden")}),Ft(()=>{r.isInElement||(document.documentElement.style.height="auto",document.body.style.height="auto",document.documentElement.style.overflow="auto")}),ko(bn,r.eventsTracker),He(async()=>{if(s===null){f(new ge(ue.ErrorSettingUpPurchase,"Product ID was not set before purchase."));return}r.purchaseOperationHelper.checkoutStart(r.appUserId,s,r.purchaseOption,r.rcPackage.webBillingProduct.presentedOfferingContext,d(n),r.metadata).then(P=>{F(i,null),F(l,"payment-entry"),F(_,U(P.gateway_params))}).catch(P=>{if(P.errorCode===ue.MissingEmailError)return F(n,void 0),r.purchaseOperationHelper.checkoutStart(r.appUserId,s,r.purchaseOption,r.rcPackage.webBillingProduct.presentedOfferingContext,d(n),r.metadata).then(T=>{F(i,null),F(l,"payment-entry"),F(_,U(T.gateway_params))}).catch(T=>{f(T)});f(P)})});const m=()=>{if(d(l)==="payment-entry"){r.purchaseOperationHelper.pollCurrentPurchaseForCompletion().then(P=>{F(l,"success"),F(c,U(P.redemptionInfo)),F(u,U(P.operationSessionId))}).catch(P=>{f(P)});return}if(d(l)==="success"||d(l)==="error"){r.onFinished(d(u),d(c));return}F(l,"success")},f=P=>{const T=_u({errorCode:P.getErrorCode().toString(),errorMessage:P.message});r.eventsTracker.trackSDKEvent(T),F(i,U(P)),F(l,"error")},v=()=>{r.onError(d(i)??new ge(ue.UnknownError,"Unknown error without state set."))};var h=E(()=>r.purchases.isSandbox()),y=E(()=>d(n)??null);mg(e,{get isSandbox(){return d(h)},get currentPage(){return d(l)},get brandingInfo(){return r.brandingInfo},productDetails:o,get purchaseOptionToUse(){return r.purchaseOption},get lastError(){return d(i)},get gatewayParams(){return d(_)},get purchaseOperationHelper(){return r.purchaseOperationHelper},get isInElement(){return r.isInElement},get customerEmail(){return d(y)},closeWithError:v,onContinue:m,onError:f,get onClose(){return r.onClose}}),H()}function Ii(e){return e==null?!0:new Date(e)>new Date}function hg(e,r,t,a){const n=r.product_identifier;if(n in t)return vg(e,r,t[n]);if(n in a)return kg(e,r,a[n]);throw new ve(Se.CustomerInfoError,"Could not find entitlement product in subscriptions or non-subscriptions.")}function vg(e,r,t){return{identifier:e,isActive:Ii(r.expires_date),willRenew:qi(r.expires_date,t),store:(t==null?void 0:t.store)??"unknown",latestPurchaseDate:new Date(r.purchase_date),originalPurchaseDate:new Date(r.purchase_date),expirationDate:fr(r.expires_date),productIdentifier:r.product_identifier,productPlanIdentifier:r.product_plan_identifier??null,unsubscribeDetectedAt:fr(t==null?void 0:t.unsubscribe_detected_at),billingIssueDetectedAt:fr(t==null?void 0:t.billing_issues_detected_at),isSandbox:(t==null?void 0:t.is_sandbox)??!1,periodType:(t==null?void 0:t.period_type)??"normal",ownershipType:(t==null?void 0:t.ownership_type)??"UNKNOWN"}}function kg(e,r,t){return{identifier:e,isActive:!0,willRenew:!1,store:t.store,latestPurchaseDate:new Date(r.purchase_date),originalPurchaseDate:new Date(t.original_purchase_date),expirationDate:null,productIdentifier:r.product_identifier,productPlanIdentifier:null,unsubscribeDetectedAt:null,billingIssueDetectedAt:null,isSandbox:t.is_sandbox,periodType:"normal",ownershipType:"UNKNOWN"}}function wg(e,r,t){const a={},n={};for(const o in e){const i=hg(o,e[o],r,t);a[o]=i,i.isActive&&(n[o]=i)}return{all:a,active:n}}function fr(e){return e==null?null:new Date(e)}function xg(e){const r=Sg(e),t=e.subscriber,a=Tg(t.non_subscriptions),n=Object.entries(e.subscriber.non_subscriptions).flatMap(([s,l])=>l.map(c=>({transactionIdentifier:c.id,productIdentifier:s,purchaseDate:new Date(c.purchase_date||c.original_purchase_date),storeTransactionId:c.store_transaction_id||null,store:c.store}))),o=new Date(e.request_date),i=Object.fromEntries(Object.entries(e.subscriber.subscriptions).map(([s,l])=>[s,{productIdentifier:s,purchaseDate:new Date(l.purchase_date),originalPurchaseDate:fr(l.original_purchase_date),expiresDate:fr(l.expires_date),store:l.store,unsubscribeDetectedAt:fr(l.unsubscribe_detected_at),isSandbox:l.is_sandbox,billingIssuesDetectedAt:fr(l.billing_issues_detected_at),gracePeriodExpiresDate:fr(l.grace_period_expires_date),ownershipType:l.ownership_type??"UNKNOWN",periodType:l.period_type,refundedAt:fr(l.refunded_at),storeTransactionId:l.store_transaction_id||null,isActive:Ii(l.expires_date),willRenew:qi(l.expires_date,l)}]));return{entitlements:wg(t.entitlements,t.subscriptions,a),allExpirationDatesByProduct:r,allPurchaseDatesByProduct:Pg(e,a),activeSubscriptions:Eg(r),managementURL:t.management_url,requestDate:o,firstSeenDate:new Date(t.first_seen),originalPurchaseDate:fr(t.original_purchase_date),originalAppUserId:e.subscriber.original_app_user_id,nonSubscriptionTransactions:n,subscriptionsByProductIdentifier:i}}function qi(e,r){if(r==null)return!1;const t=r.store=="promotional",a=e==null,n=r.unsubscribe_detected_at!=null,o=r.billing_issues_detected_at!=null;return!(t||a||n||o)}function Pg(e,r){const t={};for(const a in e.subscriber.subscriptions){const n=e.subscriber.subscriptions[a];t[a]=new Date(n.purchase_date)}for(const a in r){const n=r[a].purchase_date;n==null?t[a]=null:t[a]=new Date(n)}return t}function Sg(e){const r={};for(const t in e.subscriber.subscriptions){const a=e.subscriber.subscriptions[t];a.expires_date==null?r[t]=null:r[t]=new Date(a.expires_date)}return r}function Eg(e){const r=new Set,t=new Date;for(const a in e){const n=e[a];(n==null||n>t)&&r.add(a)}return r}function Tg(e){const r={};for(const t in e){if(e[t].length===0)continue;const a=e[t].length;r[t]=e[t][a-1]}return r}const zi="1.4.3",Ig="https://api.revenuecat.com",qg="https://e.revenue.cat";var qa;(function(e){e[e.CONTINUE=100]="CONTINUE",e[e.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",e[e.PROCESSING=102]="PROCESSING",e[e.EARLY_HINTS=103]="EARLY_HINTS",e[e.OK=200]="OK",e[e.CREATED=201]="CREATED",e[e.ACCEPTED=202]="ACCEPTED",e[e.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",e[e.NO_CONTENT=204]="NO_CONTENT",e[e.RESET_CONTENT=205]="RESET_CONTENT",e[e.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",e[e.MULTI_STATUS=207]="MULTI_STATUS",e[e.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",e[e.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",e[e.MOVED_TEMPORARILY=302]="MOVED_TEMPORARILY",e[e.SEE_OTHER=303]="SEE_OTHER",e[e.NOT_MODIFIED=304]="NOT_MODIFIED",e[e.USE_PROXY=305]="USE_PROXY",e[e.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",e[e.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.UNAUTHORIZED=401]="UNAUTHORIZED",e[e.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",e[e.FORBIDDEN=403]="FORBIDDEN",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",e[e.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",e[e.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",e[e.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",e[e.CONFLICT=409]="CONFLICT",e[e.GONE=410]="GONE",e[e.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",e[e.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",e[e.REQUEST_TOO_LONG=413]="REQUEST_TOO_LONG",e[e.REQUEST_URI_TOO_LONG=414]="REQUEST_URI_TOO_LONG",e[e.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",e[e.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",e[e.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",e[e.IM_A_TEAPOT=418]="IM_A_TEAPOT",e[e.INSUFFICIENT_SPACE_ON_RESOURCE=419]="INSUFFICIENT_SPACE_ON_RESOURCE",e[e.METHOD_FAILURE=420]="METHOD_FAILURE",e[e.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",e[e.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",e[e.LOCKED=423]="LOCKED",e[e.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",e[e.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",e[e.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",e[e.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",e[e.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",e[e.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",e[e.BAD_GATEWAY=502]="BAD_GATEWAY",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",e[e.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",e[e.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",e[e.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",e[e.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED"})(qa||(qa={}));function za(e){return e?e.startsWith("rcb_sb_"):!1}async function Sr(e,r,t){const{apiKey:a,body:n,headers:o,httpConfig:i}=r,l=`${(i==null?void 0:i.proxyURL)??Ig}${e.urlPath()}`;try{const c=await fetch(l,{method:e.method,headers:Li(a,o,i==null?void 0:i.additionalHeaders),body:Dg(n),signal:t});return await zg(c,e),await c.json()}catch(c){throw c instanceof TypeError?new ve(Se.NetworkError,jt.getPublicMessage(Se.NetworkError),c.message):c}}async function zg(e,r){const t=e.status;if(t>=qa.INTERNAL_SERVER_ERROR)En(r,t,await e.text());else if(t>=qa.BAD_REQUEST){const a=await e.json(),n=a?JSON.stringify(a):null,o=a==null?void 0:a.code,i=a==null?void 0:a.message;if(o!=null){const s=jt.convertCodeToBackendErrorCode(o);if(s==null)En(r,t,n,o);else throw ve.getForBackendError(s,i)}else En(r,t,n)}}function En(e,r,t,a){throw new ve(Se.UnknownBackendError,"Unknown backend error.",`Request: ${e.name}. Status code: ${r}. Body: ${t}.`,{backendErrorCode:a})}function Dg(e){return e==null?null:JSON.stringify(e)}const Di="Authorization",Ai="Content-Type",Fi="Accept",ji="X-Platform",Mi="X-Version",Ni="X-Platform-Flavor",Ci="X-Platform-Flavor-Version",Oi="X-Is-Sandbox",Ag=new Set([Di,Ai,Fi,ji,Mi,Oi,Ni,Ci]);function Li(e,r,t){let a={[Di]:`Bearer ${e}`,[Ai]:"application/json",[Fi]:"application/json",[ji]:"web",[Mi]:zi,[Oi]:`${za(e)}`};const n=Da.getPlatformInfo();if(n){const o={[Ni]:n.flavor,[Ci]:n.version};a={...a,...o}}return r&&(a={...a,...r}),t&&(a={...t,...a}),a}const Tn="/v1/subscribers",mt="/rcbilling/v1";class Fg{constructor(r){j(this,"appUserId");j(this,"method","GET");j(this,"name","getOfferings");this.appUserId=r}urlPath(){const r=encodeURIComponent(this.appUserId);return`${Tn}/${r}/offerings`}}class jg{constructor(r,t,a){j(this,"method","GET");j(this,"name","getProducts");j(this,"appUserId");j(this,"productIds");j(this,"currency");this.appUserId=r,this.productIds=t,this.currency=a}urlPath(){const r=encodeURIComponent(this.appUserId),t=this.productIds.map(encodeURIComponent).join("&id="),a=this.currency?`&currency=${this.currency}`:"";return`${mt}/subscribers/${r}/products?id=${t}${a}`}}class Mg{constructor(r){j(this,"method","GET");j(this,"name","getCustomerInfo");j(this,"appUserId");this.appUserId=r}urlPath(){const r=encodeURIComponent(this.appUserId);return`${Tn}/${r}`}}class Ng{constructor(){j(this,"method","GET");j(this,"name","getBrandingInfo")}urlPath(){return`${mt}/branding`}}class Cg{constructor(){j(this,"method","POST");j(this,"name","postCheckoutStart")}urlPath(){return`${mt}/checkout/start`}}class Og{constructor(r){j(this,"method","POST");j(this,"name","postCheckoutCalculateTax");j(this,"operationSessionId");this.operationSessionId=r}urlPath(){return`${mt}/checkout/${this.operationSessionId}/calculate_taxes`}}class Lg{constructor(r){j(this,"method","POST");j(this,"name","postCheckoutComplete");j(this,"operationSessionId");this.operationSessionId=r}urlPath(){return`${mt}/checkout/${this.operationSessionId}/complete`}}class Bg{constructor(r){j(this,"method","GET");j(this,"name","getCheckoutStatus");j(this,"operationSessionId");this.operationSessionId=r}urlPath(){return`${mt}/checkout/${this.operationSessionId}`}}class Rg{constructor(r){j(this,"method","POST");j(this,"name","setAttributes");j(this,"appUserId");this.appUserId=r}urlPath(){const r=encodeURIComponent(this.appUserId);return`${Tn}/${r}/attributes`}}const In={};class Ug{constructor(r,t=In){j(this,"API_KEY");j(this,"httpConfig");j(this,"isSandbox");this.API_KEY=r,this.httpConfig=t,this.isSandbox=za(r)}getIsSandbox(){return this.isSandbox}async getOfferings(r){return await Sr(new Fg(r),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getCustomerInfo(r){return await Sr(new Mg(r),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getProducts(r,t,a){return await Sr(new jg(r,t,a),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getBrandingInfo(){return await Sr(new Ng,{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async postCheckoutStart(r,t,a,n,o,i,s=void 0){const l={app_user_id:r,product_id:t,email:i,price_id:n.priceId,presented_offering_identifier:a.offeringIdentifier,trace_id:o};return s&&(l.metadata=s),n.id!=="base_option"&&(l.offer_id=n.id),a.targetingContext&&(l.applied_targeting_rule={rule_id:a.targetingContext.ruleId,revision:a.targetingContext.revision}),a.placementIdentifier&&(l.presented_placement_identifier=a.placementIdentifier),await Sr(new Cg,{apiKey:this.API_KEY,body:l,httpConfig:this.httpConfig})}async postCheckoutCalculateTax(r,t,a,n){const o={country_code:t,postal_code:a};return await Sr(new Og(r),{apiKey:this.API_KEY,body:o,httpConfig:this.httpConfig},n)}async postCheckoutComplete(r,t){const a={email:t};return await Sr(new Lg(r),{apiKey:this.API_KEY,body:a,httpConfig:this.httpConfig})}async getCheckoutStatus(r){return await Sr(new Bg(r),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async setAttributes(r,t){const a=Date.now(),n={};for(const[i,s]of Object.entries(t))n[i]={value:s,updated_at_ms:a};const o={attributes:n};return await Sr(new Rg(r),{apiKey:this.API_KEY,body:o,httpConfig:this.httpConfig})}}function Vg(e){const r=/^rcb_[a-zA-Z0-9_.-]+$/,t=/^pdl_[a-zA-Z0-9_.-]+$/;if(!r.test(e)&&!t.test(e))throw new ve(Se.InvalidCredentialsError,"Invalid API key. Use your Web Billing or Paddle API key.")}function Bi(e){if(!e||new Set(["no_user","null","none","nil","(null)","NaN","\\x00","","unidentified","undefined","unknown"]).has(e)||e.includes("/"))throw new ve(Se.InvalidAppUserIdError,'Provided user id: "'+(e??"[Not provided]")+'" is not valid. See https://www.revenuecat.com/docs/customers/user-ids#tips-for-setting-app-user-ids for more information.')}function Hg(e){if(e!=null&&e.endsWith("/"))throw new ve(Se.ConfigurationError,"Invalid proxy URL. The proxy URL should not end with a trailing slash.")}function Wg(e){if(e){for(const r in e)if(Ag.has(r))throw new ve(Se.ConfigurationError,"Invalid additional headers. Some headers are reserved for internal use.")}}var qn=(e=>(e.Current="current",e))(qn||{});function Yg(e,r){async function t(...a){return await this.preload(),await e.call(this,...a)}return t}const Ri=(e,r)=>{const t={...e.webBillingProduct,presentedOfferingContext:{...e.webBillingProduct.presentedOfferingContext,placementIdentifier:r}};return{...e,webBillingProduct:t,rcBillingProduct:t}},Zr=(e,r)=>e==null?null:Ri(e,r),Gg=(e,r,t)=>{const a=e.offering_ids_by_placement??null;if(a==null)return null;const n=e.fallback_offering_id??null;let o;if(t in a){const s=a[t]??null;if(s==null)return null;o=r[s],o==null&&(o=r[n])}else o=r[n];if(o==null)return null;const i=Object.fromEntries(Object.entries(o.packagesById).map(([s,l])=>[s,Ri(l,t)]));return{...o,packagesById:i,availablePackages:Object.values(i),weekly:Zr(o.weekly,t),monthly:Zr(o.monthly,t),twoMonth:Zr(o.twoMonth,t),threeMonth:Zr(o.threeMonth,t),sixMonth:Zr(o.sixMonth,t),annual:Zr(o.annual,t),lifetime:Zr(o.lifetime,t)}};function Xg(e,r){const t={};r.product_details.forEach(o=>{t[o.identifier]=o});const a={};e.offerings.forEach(o=>{const i=o.identifier===e.current_offering_id,s=xp(i,o,t,e.targeting);s!=null&&(a[o.identifier]=s)});const n=e.current_offering_id?a[e.current_offering_id]??null:null;return Object.keys(a).length==0&&Q.debugLog("Empty offerings. Please make sure you've configured offerings correctly in the RevenueCat dashboard and that the products are properly configured."),{all:a,current:n}}const Zg=1000001;function Kg(e){return e.webBillingProduct.defaultPurchaseOption}function Ui(e,r,t,a=!1){return t.translate(L.PaywallVariablesPricePerPeriod,{formattedPrice:e,period:r.base.period?t.translatePeriod(r.base.period.number,r.base.period.unit,{noWhitespace:!0,short:!a}):""})}function Jg(e,r){return e.unit==="year"?r.translatePeriod(e.number*12,Ye.Month):r.translatePeriod(e.number,e.unit)}function Qg({price:e,period:r,translator:t}){const a=t.formatPrice(e.amountMicros,e.currency);return r?r.unit==="year"?t.formatPrice(e.amountMicros/12/4,e.currency):r.unit==="month"||r.unit==="week"&&r.number>1?t.formatPrice(e.amountMicros/r.number,e.currency):r.unit==="day"?t.formatPrice(e.amountMicros*7/r.number,e.currency):a:a}function $g({price:e,period:r,translator:t}){const a=t.formatPrice(e.amountMicros,e.currency);return!r||!r.number?a:r.unit==="year"?t.formatPrice(e.amountMicros/12,e.currency):r.unit==="month"&&r.number>1?t.formatPrice(e.amountMicros/r.number,e.currency):r.unit==="week"?t.formatPrice(e.amountMicros*4/r.number,e.currency):r.unit==="day"?t.formatPrice(e.amountMicros*30/r.number,e.currency):a}function Vi({price:e,period:r,full:t=!1,translator:a}){if(!r||!r.number||r.unit===Ye.Month&&r.number==1)return a.formatPrice(e.amountMicros,e.currency);let n="";switch(r.unit){case Ye.Year:n=a.formatPrice(e.amountMicros/12,e.currency);break;case Ye.Month:n=a.formatPrice(e.amountMicros/r.number,e.currency);break;case Ye.Week:n=a.formatPrice(e.amountMicros*4/r.number,e.currency);break;case Ye.Day:n=a.formatPrice(e.amountMicros*30/r.number,e.currency);break}return a.translate(L.PaywallVariablesTotalPriceAndPerMonth,{formattedPrice:a.formatPrice(e.amountMicros,e.currency),period:a.translatePeriod(r.number,r.unit,{noWhitespace:!0,short:!t}),formattedPricePerMonth:n,monthPeriod:a.translatePeriodUnit(Ye.Month,{noWhitespace:!0,short:!t})})}function em(e,r){const t=e.availablePackages,a=t.reduce((n,o)=>n.webBillingProduct.currentPrice.amountMicros>o.webBillingProduct.currentPrice.amountMicros?n:o);return t.reduce((n,o)=>(n[o.identifier]=rm(o,a,r),n),{})}function rm(e,r,t){const a=e.webBillingProduct,n=t.formatPrice(a.currentPrice.amountMicros,a.currentPrice.currency),o=Kg(e),i=a.productType,s={product_name:a.title,price:n,price_per_period:"",price_per_period_full:"",total_price_and_per_month:"",total_price_and_per_month_full:"",sub_price_per_month:"",sub_price_per_week:"",sub_duration:"",sub_duration_in_months:"",sub_period:"",sub_period_length:"",sub_period_abbreviated:"",sub_offer_duration:void 0,sub_offer_duration_2:void 0,sub_offer_price:void 0,sub_offer_price_2:void 0,sub_relative_discount:""};if(i===Or.Subscription&&o){s.price_per_period=Ui(n,o,t),s.price_per_period_full=Ui(n,o,t,!0);const l=o.base.period;s.total_price_and_per_month=Vi({price:a.currentPrice,period:l,translator:t}),s.total_price_and_per_month_full=Vi({price:a.currentPrice,period:l,full:!0,translator:t}),s.sub_price_per_month=$g({price:a.currentPrice,period:l,translator:t}),s.sub_price_per_week=Qg({price:a.currentPrice,period:l,translator:t}),s.sub_duration=t.translatePeriod(l==null?void 0:l.number,l==null?void 0:l.unit),s.sub_duration_in_months=Jg(l,t),s.sub_period=t.translatePeriodFrequency(l==null?void 0:l.number,l==null?void 0:l.unit),s.sub_period_length=l?t.translatePeriodUnit(l.unit,{noWhitespace:!0}):void 0,s.sub_period_abbreviated=l?t.translatePeriodUnit(l.unit,{noWhitespace:!0,short:!0}):void 0;const c=a.currentPrice.amountMicros,u=r.webBillingProduct.currentPrice.amountMicros,_=((u-c)*100/u).toFixed(0);s.sub_relative_discount=c===u?"":t.translate(L.PaywallVariablesSubRelativeDiscount,{discount:_})}return(i===Or.NonConsumable||i===Or.Consumable)&&o&&(s.price=n,s.price_per_period=n,s.price_per_period_full=n,s.total_price_and_per_month=n,s.sub_price_per_month=n,s.sub_duration=t.translate(L.PeriodsLifetime),s.sub_duration_in_months=t.translate(L.PeriodsLifetime),s.sub_period=t.translate(L.PeriodsLifetime),s.sub_price_per_week=void 0,s.sub_relative_discount=void 0,s.price_per_period_full=n,s.total_price_and_per_month_full=n,s.sub_period_length=void 0,s.sub_period_abbreviated=void 0),s}const Ee=[];for(let e=0;e<256;++e)Ee.push((e+256).toString(16).slice(1));function tm(e,r=0){return(Ee[e[r+0]]+Ee[e[r+1]]+Ee[e[r+2]]+Ee[e[r+3]]+"-"+Ee[e[r+4]]+Ee[e[r+5]]+"-"+Ee[e[r+6]]+Ee[e[r+7]]+"-"+Ee[e[r+8]]+Ee[e[r+9]]+"-"+Ee[e[r+10]]+Ee[e[r+11]]+Ee[e[r+12]]+Ee[e[r+13]]+Ee[e[r+14]]+Ee[e[r+15]]).toLowerCase()}let zn;const am=new Uint8Array(16);function nm(){if(!zn){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");zn=crypto.getRandomValues.bind(crypto)}return zn(am)}const Hi={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Wi(e,r,t){var n;if(Hi.randomUUID&&!e)return Hi.randomUUID();e=e||{};const a=e.random??((n=e.rng)==null?void 0:n.call(e))??nm();if(a.length<16)throw new Error("Random bytes length must be >= 16");return a[6]=a[6]&15|64,a[8]=a[8]&63|128,tm(a)}var om=/(%?)(%([sdijo]))/g;function im(e,r){switch(r){case"s":return e;case"d":case"i":return Number(e);case"j":return JSON.stringify(e);case"o":{if(typeof e=="string")return e;const t=JSON.stringify(e);return t==="{}"||t==="[]"||/^\[object .+?\]$/.test(t)?e:t}}}function Dn(e,...r){if(r.length===0)return e;let t=0,a=e.replace(om,(n,o,i,s)=>{const l=r[t],c=im(l,s);return o?n:(t++,c)});return t<r.length&&(a+=` ${r.slice(t).join(" ")}`),a=a.replace(/%{2,2}/g,"%"),a}var sm=2;function lm(e){if(!e.stack)return;const r=e.stack.split(`
338
338
  `);r.splice(1,sm),e.stack=r.join(`
339
339
  `)}var cm=class extends Error{constructor(e,...r){super(e),this.message=e,this.name="Invariant Violation",this.message=Dn(e,...r),lm(this)}},Yi=(e,r,...t)=>{if(!e)throw new cm(r,...t)};Yi.as=(e,r,t,...a)=>{if(!r){const n=a.length===0?t:Dn(t,...a);let o;try{o=Reflect.construct(e,[n])}catch{o=e(n)}throw o}};const dm="[MSW]";function An(e,...r){const t=Dn(e,...r);return`${dm} ${t}`}function um(e,...r){console.warn(An(e,...r))}function pm(e,...r){console.error(An(e,...r))}const _m={formatMessage:An,warn:um,error:pm};function gm(){Yi(typeof URL<"u",_m.formatMessage(`Global "URL" class is not defined. This likely means that you're running MSW in an environment that doesn't support all Node.js standard API (e.g. React Native). If that's the case, please use an appropriate polyfill for the "URL" class, like "react-native-url-polyfill".`))}var Gi=(e=>(e.HEAD="HEAD",e.GET="GET",e.POST="POST",e.PUT="PUT",e.PATCH="PATCH",e.OPTIONS="OPTIONS",e.DELETE="DELETE",e))(Gi||{});gm();class mm{constructor(r,t,a,n){j(this,"initialDelay");j(this,"maxDelay");j(this,"jitterPercent");j(this,"callback");j(this,"currentDelay");j(this,"timeoutId");j(this,"executingCallback",!1);this.initialDelay=r,this.currentDelay=r,this.maxDelay=t,this.jitterPercent=a,this.callback=n}tryFlush(){if(this.backingOff()){Q.debugLog("Backing off, not flushing");return}this.clearTimeout(),this.executeCallbackWithRetries()}stop(){this.clearTimeout()}schedule(r){if(this.timeoutId!==void 0)return;const t=this.addJitter(r||this.currentDelay);this.timeoutId=setTimeout(()=>{this.timeoutId=void 0,this.executeCallbackWithRetries()},t)}backoff(){const r=this.currentDelay,t=Math.min(this.currentDelay*2,this.maxDelay);Q.debugLog(`Backing next off to ${r}ms delay`),this.clearTimeout(),this.currentDelay=t,this.schedule(r)}reset(){this.currentDelay!==this.initialDelay&&(this.clearTimeout(),this.currentDelay=this.initialDelay)}async executeCallbackWithRetries(){if(this.executingCallback){Q.debugLog("Callback already running, rescheduling"),this.schedule();return}this.executingCallback=!0;try{await this.callback(),this.reset()}catch{this.backoff()}finally{this.executingCallback=!1}}backingOff(){return this.currentDelay>this.initialDelay}clearTimeout(){clearTimeout(this.timeoutId),this.timeoutId=void 0}addJitter(r){const t=r*this.jitterPercent,a=r-t,n=r+t;return Math.floor(Math.random()*(n-a+1)+a)}}function Xi(e){const r={};for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const a=t.replace(/([A-Z])/g,"_$1").toLowerCase(),n=e[t];n&&typeof n=="object"&&!Array.isArray(n)?r[a]=Xi(n):r[a]=n}return r}class fm{constructor(r){j(this,"EVENT_TYPE","web_billing");j(this,"id");j(this,"timestampMs");j(this,"data");this.id=Wi(),this.timestampMs=Date.now(),this.data=r}toJSON(){return Xi({id:this.id,timestampMs:this.timestampMs,type:this.EVENT_TYPE,eventName:this.data.eventName,appUserId:this.data.appUserId,context:{...this.data.context},properties:{...this.data.properties,traceId:this.data.traceId}})}}function ym(e,r){const t=new URLSearchParams(window.location.search);return{libraryName:"purchases-js",libraryVersion:zi,locale:navigator.language,userAgent:navigator.userAgent,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,screenWidth:screen.width,screenHeight:screen.height,utmSource:t.get("utm_source")??null,utmMedium:t.get("utm_medium")??null,utmCampaign:t.get("utm_campaign")??null,utmContent:t.get("utm_content")??null,utmTerm:t.get("utm_term")??null,pageReferrer:document.referrer,pageUrl:`${window.location.origin}${window.location.pathname}`,pageTitle:document.title,source:e,rcSource:r}}const bm=2e3,hm=5*6e4,vm=.1;class km{constructor(r){j(this,"apiKey");j(this,"eventsQueue",[]);j(this,"eventsUrl");j(this,"flushManager");j(this,"traceId",Wi());j(this,"appUserId");j(this,"isSilent");j(this,"rcSource");this.apiKey=r.apiKey,this.eventsUrl=`${qg}/v1/events`,this.appUserId=r.appUserId,this.isSilent=r.silent||!1,this.rcSource=r.rcSource,this.flushManager=new mm(bm,hm,vm,this.flushEvents.bind(this))}async updateUser(r){this.appUserId=r}getTraceId(){return this.traceId}trackSDKEvent(r){this.trackEvent({...r,source:"sdk"})}trackExternalEvent(r){this.trackEvent({...r})}trackEvent(r){if(this.isSilent){Q.verboseLog("Skipping event tracking, the EventsTracker is silent");return}try{const t=new fm({eventName:r.eventName,traceId:this.traceId,appUserId:this.appUserId,context:ym(r.source,this.rcSource),properties:r.properties||{}});this.eventsQueue.push(t),this.flushManager.tryFlush()}catch{Q.errorLog(`Error while tracking event ${r.eventName}`)}}dispose(){this.flushManager.stop()}flushEvents(){if(this.eventsQueue.length===0)return Promise.resolve();const r=[...this.eventsQueue];return fetch(this.eventsUrl,{method:Gi.POST,headers:Li(this.apiKey),body:JSON.stringify({events:r})}).then(t=>{if(t.status===200||t.status===201){this.eventsQueue.splice(0,r.length);return}else throw Q.debugLog("Events failed to flush due to server error"),new Error("Events failed to flush due to server error")}).catch(t=>{throw Q.debugLog("Error while flushing events"),t})}}const wm=()=>{const e=new URLSearchParams(window.location.search),r=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],t={};return r.forEach(a=>{const n=e.get(a);n!==null&&(t[a]=n)}),t},Fn={autoCollectUTMAsMetadata:!0,collectAnalyticsEvents:!0};function xm(){if(crypto&&crypto.randomUUID)return crypto.randomUUID();const e=new Uint8Array(16);if(crypto&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;const r=Array.from(e).map(t=>t.toString(16).padStart(2,"0"));return[r.slice(0,4).join(""),r.slice(4,6).join(""),r.slice(6,8).join(""),r.slice(8,10).join(""),r.slice(10,16).join("")].join("-")}var Zi=(e=>(e.DisplayName="$displayName",e.Email="$email",e.PhoneNumber="$phoneNumber",e.IDFA="$idfa",e.IDFV="$idfv",e.GPSAdId="$gpsAdId",e.AndroidId="$androidId",e.AmazonAdId="$amazonAdId",e.IP="$ip",e.AdjustId="$adjustId",e.AmplitudeDeviceId="$amplitudeDeviceId",e.AmplitudeUserId="$amplitudeUserId",e.AppsflyerId="$appsflyerId",e.AppsflyerSharingFilter="$appsflyerSharingFilter",e.BranchId="$branchId",e.BrazeAliasName="$brazeAliasName",e.BrazeAliasLabel="$brazeAliasLabel",e.ClevertapId="$clevertapId",e.FbAnonId="$fbAnonId",e.MparticleId="$mparticleId",e.OnesignalId="$onesignalId",e.OnesignalUserId="$onesignalUserId",e.IntercomContactId="$intercomContactId",e.MediaSource="$mediaSource",e.Campaign="$campaign",e.AdGroup="$adGroup",e.AdId="$ad",e.Keyword="$keyword",e.Creative="$creative",e.APNSTokens="$apnsTokens",e.FCMTokens="$fcmTokens",e.AirshipChannelId="$airshipChannelId",e.SegmentId="$segmentId",e.IterableUserId="$iterableUserId",e.IterableCampaignId="$iterableCampaignId",e.IterableTemplateId="$iterableTemplateId",e.FirebaseAppInstanceId="$firebaseAppInstanceId",e.MixpanelDistinctId="$mixpanelDistinctId",e.ATTConsentStatus="$attConsentStatus",e.KochavaDeviceId="$kochavaDeviceId",e.DeviceVersion="$deviceVersion",e.PosthogUserId="$posthogUserId",e.TelemetryDeckUserId="$telemetryDeckUserId",e.TelemetryDeckAppId="$telemetryDeckAppId",e.AppleRefundHandlingPreference="$appleRefundHandlingPreference",e.CustomerioId="$customerioId",e.TenjinId="$tenjinId",e))(Zi||{});const Ki="$RCAnonymousID:";rs=[Yg];const Te=class Te{constructor(r,t,a=In,n=Fn){gs(jn,5,this);j(this,"_API_KEY");j(this,"_appUserId");j(this,"_brandingInfo",null);j(this,"_loadingResourcesPromise",null);j(this,"_flags");j(this,"backend");j(this,"purchaseOperationHelper");j(this,"eventsTracker");this._API_KEY=r,this._appUserId=t,this._flags={...Fn,...n},za(r)&&Q.debugLog("Initializing Purchases SDK with sandbox API Key"),this.eventsTracker=new km({apiKey:this._API_KEY,appUserId:this._appUserId,silent:!this._flags.collectAnalyticsEvents,rcSource:this._flags.rcSource??null}),this.backend=new Ug(this._API_KEY,a),this.purchaseOperationHelper=new Tl(this.backend,this.eventsTracker),this.eventsTracker.trackSDKEvent({eventName:Re.SDKInitialized})}static setLogLevel(r){Q.setLogLevel(r)}static setPlatformInfo(r){Te._platformInfo=r}static getPlatformInfo(){return Te._platformInfo}static getSharedInstance(){if(Te.isConfigured())return Te.instance;throw new Uo}static isConfigured(){return Te.instance!==void 0}static configure(r,t,a=In,n=Fn){return Te.instance!==void 0&&Q.warnLog("Purchases is already initialized. You normally should only configure Purchases once. Creating and returning new instance."),Vg(r),Bi(t),Hg(a.proxyURL),Wg(a.additionalHeaders),Te.instance=new Te(r,t,a,n),Te.getSharedInstance()}async preload(){if(this.hasLoadedResources()){Q.verboseLog("Purchases resources are loaded. Skipping.");return}if(this._loadingResourcesPromise!==null){Q.verboseLog("Purchases resources are loading. Waiting."),await this._loadingResourcesPromise;return}return this._loadingResourcesPromise=this.fetchAndCacheBrandingInfo().catch(r=>{let t=`${r}`;r instanceof ve&&(t=`${r.message}. ${r.underlyingErrorMessage?`Underlying error: ${r.underlyingErrorMessage}`:""}`),Q.errorLog(`Error fetching branding info: ${t}`)}).finally(()=>{this._loadingResourcesPromise=null}),this._loadingResourcesPromise}fetchAndCacheBrandingInfo(){return this.backend.getBrandingInfo().then(r=>{this._brandingInfo=r})}hasLoadedResources(){return this._brandingInfo!==null}async renderPaywall(r){console.warn("This method is @experimental, Paywalls are not generally available but they will come soon!");let a=r.htmlTarget??document.getElementById("rcb-ui-pw-root");if(a===null){const g=document.createElement("div");g.id="rcb-ui-pw-root",g.className="rcb-ui-pw-root",g.style.zIndex=`${Zg}`,document.body.appendChild(g),a=g}if(a===null)throw new Error("Could not generate a mount point for the billing widget");const n=a;n.innerHTML="";const o=r.offering;if(!o.paywall_components)throw new Error("You cannot use paywalls yet, they are coming soon!");const i=r.selectedLocale||navigator.language,s=new ya({},i,o.paywall_components.default_locale),l=g=>{var f;const m=o.availablePackages.find(v=>v.identifier===g);if(m===void 0)throw new Error(`No package found for ${g}`);return this.purchase({rcPackage:m,htmlTarget:r.purchaseHtmlTarget,customerEmail:r.customerEmail,selectedLocale:i,defaultLocale:((f=o.paywall_components)==null?void 0:f.default_locale)||pt})},c=g=>{var m;if(r.onNavigateToUrl){r.onNavigateToUrl(g);return}(m=window.open(g,"_blank"))==null||m.focus()},u=()=>{},_=()=>{if(r.onVisitCustomerCenter){r.onVisitCustomerCenter();return}},p=em(o,s);return new Promise((g,m)=>{Eo(Qc,{target:n,props:{paywallData:o.paywall_components,selectedLocale:i,onNavigateToUrlClicked:c,onVisitCustomerCenterClicked:_,onBackClicked:()=>{if(r.onBack){r.onBack();return}n.innerHTML="",Q.debugLog("Purchase cancelled by user"),m(new ve(Se.UserCancelledError))},onRestorePurchasesClicked:u,onPurchaseClicked:f=>{l(f).then(v=>{g(v)}).catch(v=>m(v))},onError:f=>m(f),variablesPerPackage:p}})})}async getOfferings(r){yg(r==null?void 0:r.currency);const t=this._appUserId,a=await this.backend.getOfferings(t),n=(r==null?void 0:r.offeringIdentifier)===qn.Current?a.current_offering_id:r==null?void 0:r.offeringIdentifier;return n&&(a.offerings=a.offerings.filter(o=>o.identifier===n)),await this.getAllOfferings(a,t,r)}async getCurrentOfferingForPlacement(r,t){const a=this._appUserId,n=await this.backend.getOfferings(a),o=await this.getAllOfferings(n,a,t),i=n.placements??null;return i==null?null:Gg(i,o.all,r)}async getAllOfferings(r,t,a){const n=r.offerings.flatMap(i=>i.packages).map(i=>i.platform_product_identifier),o=await this.backend.getProducts(t,n,a==null?void 0:a.currency);return this.logMissingProductIds(n,o.product_details),Xg(r,o)}async isEntitledTo(r){const t=await this.getCustomerInfo();return r in t.entitlements.active}purchasePackage(r,t,a){return this.purchase({rcPackage:r,customerEmail:t,htmlTarget:a})}purchase(r){var P;const{rcPackage:t,purchaseOption:a,htmlTarget:n,customerEmail:o,selectedLocale:i=pt,defaultLocale:s=pt}=r;let l=n??document.getElementById("rcb-ui-root");if(l===null){const T=document.createElement("div");T.className="rcb-ui-root",document.body.appendChild(T),l=T}if(l===null)throw new Error("Could not generate a mount point for the billing widget");const c=l,u=this._appUserId;Q.debugLog(`Presenting purchase form for package ${t.identifier}`);const _=i||s,p=a??t.webBillingProduct.defaultPurchaseOption,g=mu({appearance:(P=this._brandingInfo)==null?void 0:P.appearance,rcPackage:t,purchaseOptionToUse:p,customerEmail:o});this.eventsTracker.trackSDKEvent(g);const f={...this._flags.autoCollectUTMAsMetadata?wm():{},...r.metadata||{}};let v=null;const h=this._brandingInfo;h&&r.brandingAppearanceOverride&&(h.appearance=r.brandingAppearanceOverride);const y=n!==void 0;return new Promise((T,S)=>{y||window.history.pushState({checkoutOpen:!0},"");const D=this._flags.rcSource==="app"?void 0:()=>{const w=yu();this.eventsTracker.trackSDKEvent(w),window.removeEventListener("popstate",D),v&&on(v),c.innerHTML="",Q.debugLog("Purchase cancelled by user"),S(new ve(Se.UserCancelledError))};!y&&D&&window.addEventListener("popstate",D),v=Eo(bg,{target:c,props:{isInElement:y,appUserId:u,rcPackage:t,purchaseOption:p,customerEmail:o,onFinished:async(w,A)=>{const Z=fu({redemptionInfo:A});this.eventsTracker.trackSDKEvent(Z),Q.debugLog("Purchase finished"),v&&on(v),c.innerHTML="";const G={customerInfo:await this._getCustomerInfoForUserId(u),redemptionInfo:A,operationSessionId:w};T(G)},onClose:D,onError:w=>{var Z;const A=bu({errorCode:(Z=w.errorCode)==null?void 0:Z.toString(),errorMessage:w.message});this.eventsTracker.trackSDKEvent(A),v&&on(v),c.innerHTML="",S(ve.getForPurchasesFlowError(w))},purchases:this,eventsTracker:this.eventsTracker,brandingInfo:this._brandingInfo,purchaseOperationHelper:this.purchaseOperationHelper,selectedLocale:_,metadata:f,defaultLocale:s,customTranslations:r.labelsOverride}})})}async getCustomerInfo(){return await this._getCustomerInfoForUserId(this._appUserId)}getAppUserId(){return this._appUserId}async setAttributes(r){return await this.getCustomerInfo(),await this.backend.setAttributes(this._appUserId,r)}async changeUser(r){return Bi(r),this._appUserId=r,this.eventsTracker.updateUser(r),await this.getCustomerInfo()}logMissingProductIds(r,t){const a={};t.forEach(o=>a[o.identifier]=o);const n=[];r.forEach(o=>{a[o]===void 0&&n.push(o)}),n.length>0&&Q.debugLog(`Could not find product data for product ids:
340
340
  ${n.join()}.
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@revenuecat/purchases-js",
3
3
  "description": "Web subscriptions made easy. Powered by RevenueCat",
4
4
  "private": false,
5
- "version": "1.4.2",
5
+ "version": "1.4.3",
6
6
  "type": "module",
7
7
  "files": [
8
8
  "dist"