@tinkerlandai/longplay-sdk 0.10.75 → 0.10.76
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/{chunk-M3E3ZAHR.js → chunk-2AFZOVAE.js} +1 -1
- package/dist/{chunk-CIVRE5G5.js → chunk-4N7PVGHA.js} +1 -1
- package/dist/{chunk-KRJ7D25I.js → chunk-65QMZQE6.js} +1 -1
- package/dist/{chunk-HQ6MQWFY.js → chunk-ES77Y76B.js} +1 -1
- package/dist/{chunk-KSRJEMYQ.js → chunk-JJIOGZIP.js} +1 -1
- package/dist/chunk-KQE32GKG.js +1 -0
- package/dist/chunk-S5KGFAAW.js +1 -0
- package/dist/{chunk-ZLRQ6X3A.js → chunk-T5QI2ZZR.js} +1 -1
- package/dist/{chunk-WPPT4PS7.js → chunk-TDPFVHJM.js} +1 -1
- package/dist/{chunk-PZPONSBE.js → chunk-W6KE7753.js} +1 -1
- package/dist/{chunk-L33UXXE4.js → chunk-WTZQYCQ2.js} +2 -2
- package/dist/{chunk-FMDLTDLK.js → chunk-YDGJ3KEY.js} +1 -1
- package/dist/{chunk-DIFM44US.js → chunk-ZIYU3HLD.js} +1 -1
- package/dist/{chunk-EU7KLHEE.js → chunk-ZL7YW35H.js} +1 -1
- package/dist/{content-PFD22VB5.js → content-XPEXTRMO.js} +1 -1
- package/dist/{funnel-host-purchase-A7RIV3VL.js → funnel-host-purchase-IKDKPYVN.js} +1 -1
- package/dist/{funnel-host-recovery-paywall-QWUEMOMW.js → funnel-host-recovery-paywall-526KDYRO.js} +1 -1
- package/dist/{funnel-paywall-prerender-LFK2J34G.js → funnel-paywall-prerender-63YAPNPP.js} +1 -1
- package/dist/{funnel-runtime-host-BMOLGYXZ.js → funnel-runtime-host-NUYFCCBB.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/page.js +1 -1
- package/dist/{paywall-ZP5X27ZZ.js → paywall-ZFSJSI6N.js} +1 -1
- package/dist/{paywall-content-5SVZLU5S.js → paywall-content-IERCHHQ5.js} +1 -1
- package/dist/{paywall-session-NKWC4TGU.js → paywall-session-QDO32X66.js} +1 -1
- package/dist/react-native.js +1 -1
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-52GS4CLH.js +0 -1
- package/dist/chunk-WAPQ6BX4.js +0 -1
- /package/dist/{chunk-L33UXXE4.js.LEGAL.txt → chunk-WTZQYCQ2.js.LEGAL.txt} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.76
|
|
4
|
+
|
|
5
|
+
- Replacing an unpaid original Checkout with another plan sends two fewer reads. `terminateCheckout` no longer reads the purchase again first when the state it already holds names that Checkout as open (the server checks the exact original when it terminates it). A recovered Paywall, which rebinds to a new Run for the quote, no longer reads the original a second time when the termination's own reply already read it closed and unpaid. A Paywall that keeps its session still reads, and a paid, settling or still-open original is read and shown as before. The new plan is still quoted only after the original has been read closed and unpaid
|
|
6
|
+
|
|
3
7
|
## 0.10.75
|
|
4
8
|
|
|
5
9
|
- With `whenPurchasePending: "recover"`, a pre-render that finds an unfinished purchase and no kept Paywall now keeps the Paywall it has just read, under the Funnel of its Start or of the purchase left pending in storage, and holds it for that purchase's recovery. Before, only a copy kept from an earlier presentation was held, and an earlier SDK forgot that copy as soon as a purchase became pending, so a Customer who already had an unpaid Checkout never got the Paywall at the click. A refused Start with no pending purchase in storage still gives the copy up
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as T,b as se}from"./chunk-NUIKM2BY.js";import{b as re,h as ae,j as ce}from"./chunk-HQ6MQWFY.js";import{E as M,a as J}from"./chunk-EU7KLHEE.js";import{a as b,b as f,c as m}from"./chunk-YMTCZWZG.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-3ZYWGEBY.js";import{a as oe,b as j}from"./chunk-B7CFFTJI.js";import{b as W,j as X}from"./chunk-Q6SK6G7T.js";import{n as $}from"./chunk-LYTPUZOW.js";import{b as ie}from"./chunk-ZLRQ6X3A.js";import{a as B}from"./chunk-66SRWQES.js";import{a as s}from"./chunk-E4B7243C.js";import{h as Q}from"./chunk-5SNUVXZ7.js";import{b as K}from"./chunk-7RUOZL6C.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-L3CZMIL6.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-L3CZMIL6.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-L3CZMIL6.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-L3CZMIL6.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};
|
|
1
|
+
import{a as T,b as se}from"./chunk-NUIKM2BY.js";import{b as re,h as ae,j as ce}from"./chunk-ES77Y76B.js";import{E as M,a as J}from"./chunk-ZL7YW35H.js";import{a as b,b as f,c as m}from"./chunk-YMTCZWZG.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-3ZYWGEBY.js";import{a as oe,b as j}from"./chunk-B7CFFTJI.js";import{b as W,j as X}from"./chunk-Q6SK6G7T.js";import{n as $}from"./chunk-LYTPUZOW.js";import{b as ie}from"./chunk-T5QI2ZZR.js";import{a as B}from"./chunk-66SRWQES.js";import{a as s}from"./chunk-E4B7243C.js";import{h as Q}from"./chunk-5SNUVXZ7.js";import{b as K}from"./chunk-7RUOZL6C.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-L3CZMIL6.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-L3CZMIL6.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-L3CZMIL6.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-L3CZMIL6.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as ve,b as be}from"./chunk-62MMCXIA.js";import{d as Me,e as ne}from"./chunk-EQJIC52H.js";import{a as Ne}from"./chunk-E4B7243C.js";import{a as R}from"./chunk-DSPLGTQI.js";var Xe=5*6e4,$e=15e3,qe=new WeakMap;function rn(s){return qe.get(s)}var k=s=>Array.isArray(s)?s.map(k):s&&typeof s=="object"?Object.fromEntries(Object.keys(s).sort().map(n=>[n,k(s[n])])):s,L=(s,n)=>JSON.stringify(k(s))===JSON.stringify(k(n)),re=s=>JSON.stringify(k([s.funnelId,s.locale??null,s.parameters??{}])),ze=["onObservationChange","onPurchase","onCheckoutUrl","resumeCheckout","allowNewPurchase","checkoutNavigation","terminateCheckout","beforeCheckoutReplacement","purchaseConfirmation","confirmOnHostedCheckout","resolveOfferId","prepareSubscriptionChange","resolveSubscriptionChange","onOpenUrl","onEvent","onAction","onComplete","onError"];function Qe(s,n,S){let O=e=>structuredClone({funnelId:e.funnelId,locale:e.locale,parameters:e.parameters}),m,_="",E=n.start instanceof Promise?void 0:O(n.start),ae=e=>e?.parameters?.commerce,T=Promise.resolve(n.start).then(e=>e?O(e):void 0),te=n.maxAgeMs??Xe,Ie=new AbortController,g=AbortSignal.any([Ie.signal,n.client.identitySignal,...n.signal?[n.signal]:[]]),oe=()=>u("released","aborted"),a="preparing",Se,j,le=()=>{},J=0,b=null,v=null,C=null,p=null,h,x,V,Ce=new Map,P=null,U=new Set,D=new Map,ie,Ae=new Promise(e=>ie=e),G,se=new Promise(e=>G=e),ce,Le=new Promise(e=>ce=e);function W(e,r){a!==e&&(a=e,Se=r,R(n.onState,e))}function Te(){g.removeEventListener("abort",oe),$(),v?.destroy(),v=null,b?.remove(),b=null,C=null}function u(e,r){["adopted","unavailable","released","closed"].includes(a)||(W(e,r),Te(),ie(!1),G(!1),X(!1),ce(null))}function N(e){a!=="shown"&&u("unavailable",e)}let f,de=!1,F=n.client.paywallCopies,ue,Re=new Promise(e=>ue=e),fe=!1,K=!1,ke,B=n.whenPurchasePending==="recover"&&!S,X,je=new Promise(e=>X=e);function Je(e){if(!B||f||!e||!p||!V||!A(p,V.commerce)||!["preparing","ready","shown"].includes(a))return!1;let r={savedAt:Date.now(),funnelId:e,context:V,resolution:structuredClone(p)};return f=r,we(r),Z(),!0}function pe(e){return!B||!f||!["preparing","ready","shown"].includes(a)?!1:(K=!0,ke=e,!0)}function we(e){Re.then(r=>{r&&F&&F.write(r,e).catch(()=>{})})}function _e(e){Re.then(async r=>{if(!r||!F)return;let l=await F.read(r);de||l&&"presented"in l||await F.write(r,e)}).catch(()=>{})}let ye=e=>`error:${e?.code??e?.name??"unknown"}`,me=s.ownerDocument.defaultView,M=!S,Ee=null,H=!1,Ue=e=>e.storageArea===me?.localStorage&&(e.key===null||e.key.startsWith("indiana.funnel.purchases.")),Ve=e=>{Ue(e)&&z()},Ge=S?()=>{}:n.client.subscribe(()=>z());function $(){M&&(M=!1,me?.removeEventListener("storage",Ve),Ge(),le())}let ge=()=>M&&(a==="ready"||a==="preparing");function he(e){(a==="ready"||a==="preparing")&&u("unavailable",e)}function z(){if(a==="ready"&&Date.now()-J>=te)return $();H=!0,Ee??=(async()=>{for(;H&&m&&!K&&ge();){H=!1;try{await n.client.retained()==="pending"&&!pe("purchase_pending")&&he("purchase_pending")}catch(e){g.aborted?u("released","aborted"):he(ye(e))}}})().finally(()=>{Ee=null,H&&m&&!K&&ge()&&z()})}S||me?.addEventListener("storage",Ve),g.addEventListener("abort",oe,{once:!0});let De=S?Promise.resolve("none"):n.client.findPurchase();De.catch(()=>{});let Q;function Y(e){let r=Q?.paywallVersionId??n.paywallVersionId??f?.resolution.id??p?.id,l=JSON.stringify(k([r??null,e])),i=Ce.get(l);return i||(i=n.client.readPaywall({paywallVersionId:r,...r?{}:{paywallId:Q?.paywallId??n.paywallId},...e}),Ce.set(l,i)),i}function A(e,r){let l=Object.values(e.capabilities.plans),i=Object.values(e.document.buttons).some(t=>t.type==="checkout");return i&&l.length===0?!1:r.intent==="subscription_change"&&i?l.some(t=>t.available):l.every(t=>t.available)}function Pe(e,r){if(p&&!ne(e,p))return u("unavailable","paywall_changed"),!1;p=e,V=r,X(!0);for(let l of D.keys())R(l,structuredClone(e));return!0}function Fe(e,r){if(!(!p||!["preparing","ready","shown"].includes(a))){if(!ne(e,p))return N("paywall_changed");if(!A(e,r.commerce))return N("plan_unavailable");Pe(e,r)}}async function q(){let e=await Le;if(!e)throw new Ne("PURCHASE_PENDING","The purchase did not start; open it again");return e}let We={get view(){return P?P.view:p},get signal(){return P?.signal??n.client.identitySignal},get quote(){return P?.quote??null},get operation(){return P?.operation??null},webViewUrl:"bundled",get canReselect(){return P?.canReselect},get recovery(){return P?.recovery},get pendingCancellation(){return P?.pendingCancellation},subscribe(e){return D.set(e,P?.subscribe?.(e)??(()=>{})),()=>{D.get(e)?.(),D.delete(e)}},refresh:async()=>P?P.refresh():structuredClone(p),preview:async e=>(await q()).preview(e),confirm:async()=>(await q()).confirm(),cancel:async()=>(await q()).cancel(),read:async()=>(await q()).read(),destroy(){P?.destroy()}},w={options:{},handoff:{}},He={loading:"host",focusAtReveal:!0,settleMotionAtReveal:!0,signal:n.client.identitySignal,start:async()=>We,canInteract:()=>w.options.canInteract?w.options.canInteract():!["unavailable","released","closed"].includes(a),async beforeAction(){let e=a!=="adopted",r=p?.capabilities,l=await q();if(e&&!L(l.view?.capabilities,r))throw new Me;await w.options.beforeAction?.()}};for(let e of ze)Object.defineProperty(He,e,{enumerable:!0,get:()=>w.options[e]});function Z(){a!=="preparing"||!C||!v||!f&&(!m||!L(V?.commerce,ae(m))||V?.locale!==m.locale)||(W("ready"),ie(!0))}let Oe={present(e){if(w.handoff.present)return w.handoff.present(e);a==="preparing"&&(C=e,J=Date.now(),Z())},async dismiss(){if(w.handoff.dismiss)return w.handoff.dismiss();u("closed");for(let e of[...U])R(e)},async closeAction(e){if(w.handoff.closeAction)return w.handoff.closeAction(e);w.options.onAction?await w.options.onAction(e):await Oe.dismiss()},quoteError(e){w.handoff.quoteError?w.handoff.quoteError(e):R(w.options.onError,e)}};async function Ke(){if(n.paywallVersionId||n.paywallId)return{paywallVersionId:n.paywallVersionId,paywallId:n.paywallId};let e=n.configuration;if(!e)return u("unavailable","paywall_missing"),null;let r=await Promise.resolve(n.start).catch(()=>null);if(!r||a!=="preparing")return null;let l=()=>ve(e,{funnelId:r.funnelId,customerId:n.client.customerId,parameters:r.parameters??{}});if(j=await l(),a!=="preparing")return null;let i=j;if(i.type!=="paywall")return u("unavailable",be(i)??"route"),null;let t=!1;return le=e.subscribe(()=>{t||!ge()||(t=!0,l().then(c=>{!(c.type==="unavailable"&&!["funnel_stopped","route_unavailable"].includes(c.reason))&&(c.type!=="paywall"||c.paywallVersionId!==i.paywallVersionId)&&he("route_changed")}).finally(()=>t=!1))}),M||le(),{paywallVersionId:i.paywallVersionId}}(async()=>{try{let[{showPaywall:e},r]=await Promise.all([import("./paywall-ZP5X27ZZ.js"),Ke()]),l=n.commerce??ae(E),i=n.locale??E?.locale,t=r&&l&&i?JSON.stringify(k([r.paywallVersionId??null,r.paywallId??null,{commerce:l,locale:i}])):null;if(ue(t),g.throwIfAborted(),a!=="preparing"||!r)return;if(!l)return u("unavailable","commerce_missing");if(!i)return u("unavailable","locale_missing");Q=r;let c={commerce:l,locale:i},y=t?await F?.read(t).catch(()=>null):null;if(fe=!!y&&"presented"in y&&(!E||y.funnelId===E.funnelId),g.throwIfAborted(),a!=="preparing"||fe)return;y&&!("presented"in y)&&(!E||y.funnelId===E.funnelId)&&A(y.resolution,y.context.commerce)&&(f=y),G(!!f);let o;if(f){let ee=f.context;c=ee,o=structuredClone(f.resolution),Y(ee).then(Be=>Fe(Be,ee),()=>{})}else o=await Y(c);if(g.throwIfAborted(),a!=="preparing"||(!A(o,c.commerce)&&n.start instanceof Promise&&!h&&await T,!f&&h&&!L(c,h)&&(c=h,o=await Y(c)),g.throwIfAborted(),a!=="preparing"))return;if(!A(o,c.commerce))return u("unavailable","plan_unavailable");if(!Pe(o,c))return;b=s.ownerDocument.createElement("div"),s.append(b);let d=setTimeout(()=>a==="preparing"&&u("unavailable","timeout"),$e);Ae.then(()=>clearTimeout(d));let I=await e(b,He,Oe);if(!I.host||g.aborted||a!=="preparing"){I.host?.destroy(),u(g.aborted?"released":"unavailable","error");return}v=I.host,Z()}catch(e){u(g.aborted?"released":"unavailable",ye(e))}finally{ue(null),G(!1),X(!1)}})(),T.then(async e=>{let r=o=>{_e(null),N(o)},l=async()=>{let o=await De;return o==="pending"?"purchase_pending":o==="found"?"original_purchase":o==="blocked"?"purchase_blocked":void 0},i=async o=>!o||o==="purchase_blocked"||!B?!1:(await se,pe(o)?!0:await je&&Je(e?.funnelId??await n.client.pendingFunnel().catch(()=>null)??void 0)&&pe(o));if(!e)return B&&await i(await l().catch(()=>{}))?void 0:r("gated");let t=e,c=ae(t),y=n.commerce??c;if(!L(c&&{...c,intent:void 0},y&&{...y,intent:void 0})||n.locale!==void 0&&t.locale!==n.locale)return r("start_mismatch");if(!c)return r("commerce_missing");h={commerce:c,locale:t.locale},x=t,f&&["preparing","ready","shown"].includes(a)&&(m=t,_=re(t));try{let o=await l();if(await i(o)){m=void 0,_="";return}if(o)return r(o);if(!["preparing","ready","shown"].includes(a))return;if(n.configuration&&(n.paywallId||n.paywallVersionId)){let d=await ve(n.configuration,{funnelId:t.funnelId,customerId:n.client.customerId,parameters:t.parameters??{}});g.throwIfAborted();let I=d.type==="unknown"||d.type==="unavailable"&&d.reason!=="funnel_stopped";if(d.type==="paywall"?f?d.paywallId!==f.resolution.paywallId:n.paywallVersionId?d.paywallVersionId!==n.paywallVersionId:d.paywallId!==n.paywallId:!I)return r(be(d)??"route_changed")}if(M&&(H=!1,await n.client.retained()==="pending")){if(await i("purchase_pending")){m=void 0,_="";return}return r("purchase_pending")}if(await se,fe){m=t,_=re(t);return}if(Q||n.paywallId||n.paywallVersionId||p){let d=await Y(h);if(g.throwIfAborted(),_e(A(d,h.commerce)?{savedAt:Date.now(),funnelId:t.funnelId,context:h,resolution:d}:null),f)Fe(d,h);else{if(a!=="preparing")return;if(p){if(!A(d,h.commerce))return u("unavailable","plan_unavailable");if(!Pe(d,h))return}}}}catch(o){return g.aborted?u("released","aborted"):N(ye(o))}["preparing","ready","shown"].includes(a)&&(m=t,_=re(t),Z(),H&&z())},()=>N("gated"));let xe={get state(){return a},get reason(){return Se??ke},ready:Ae,local:se,get start(){return m},get prediction(){return j?structuredClone(j):void 0},matches:e=>m?re(e)===_:!!f&&e.funnelId===f.funnelId&&e.locale===f.context.locale,open(){if(a==="preparing")return"pending";if(a!=="ready"||!C)return!1;if(Date.now()-J>=te)return u("unavailable","expired"),!1;let e=C;return C=null,$(),W("shown"),e(),"shown"},destroy(){Ie.abort()}};return qe.set(xe,{onClose(e){return a==="closed"?(R(e),()=>{}):(U.add(e),()=>{U.delete(e)})},claim(){$()},remember(e){de=!0;let r=structuredClone(e);T.then(()=>{!x||!h||we({savedAt:Date.now(),funnelId:x.funnelId,context:h,resolution:r})},()=>{})},withhold(){de=!0,T.then(()=>{x&&we({savedAt:Date.now(),funnelId:x.funnelId,presented:"nothing"})},()=>{})},async adopt(e,r){let l=e.paywall?.resolution,i=e.paywall&&!e.paywall.quote&&!e.paywall.operation&&!e.paywall.purchaseRequestId&&!(e.paywall.selectionGeneration??0);if(a!=="shown"||!v||!p||!l||!i||e.source.id!==m?.funnelId||e.locale!==m?.locale||!L(e.parameters??{},m?.parameters??{})||!["running","waiting"].includes(e.status)||!ne(l,p))return null;let t;try{t=await r.start()}catch{return null}if(a!=="shown"||!v)return t.destroy(),null;P=t,w.options=r.options,w.handoff=r.handoff;for(let[o]of D)D.set(o,t.subscribe?.(o)??(()=>{})),t.view&&R(o,structuredClone(t.view));g.removeEventListener("abort",oe),W("adopted"),ce(t),U.clear();let c=v,y=b;return v=null,b=null,C=null,new Proxy(c,{get(o,d){return d==="destroy"?()=>{o.destroy(),y?.remove()}:d==="retainPurchaseDialog"?()=>{let I=o.retainPurchaseDialog();if(I)return{dialog:I.dialog,release(){I.release(),y?.remove()}}}:Reflect.get(o,d,o)}})},retainPurchaseDialog(){if(a!=="shown")return;let e=v?.retainPurchaseDialog();if(!e)return;let r=b;return v=null,b=null,u("released"),{dialog:e.dialog,release(){e.release(),r?.remove()}}},get modal(){return p?.document.presentation.type!=="inline"},get revealable(){return a==="ready"&&!!C&&Date.now()-J<te},get recovering(){return K},release(){u("released")}}),xe}function an(s,n){let S=n.run.parameters??{},O=S?.commerce;return Qe(s,{client:n.client,start:{funnelId:n.run.source.id,locale:n.run.locale,parameters:S},paywallVersionId:n.paywallVersionId,...O&&{commerce:O},locale:n.run.locale,signal:n.signal},{run:!0})}export{Xe as a,rn as b,Qe as c,an as d};
|
|
1
|
+
import{a as ve,b as be}from"./chunk-62MMCXIA.js";import{d as Me,e as ne}from"./chunk-EQJIC52H.js";import{a as Ne}from"./chunk-E4B7243C.js";import{a as R}from"./chunk-DSPLGTQI.js";var Xe=5*6e4,$e=15e3,qe=new WeakMap;function rn(s){return qe.get(s)}var k=s=>Array.isArray(s)?s.map(k):s&&typeof s=="object"?Object.fromEntries(Object.keys(s).sort().map(n=>[n,k(s[n])])):s,L=(s,n)=>JSON.stringify(k(s))===JSON.stringify(k(n)),re=s=>JSON.stringify(k([s.funnelId,s.locale??null,s.parameters??{}])),ze=["onObservationChange","onPurchase","onCheckoutUrl","resumeCheckout","allowNewPurchase","checkoutNavigation","terminateCheckout","beforeCheckoutReplacement","purchaseConfirmation","confirmOnHostedCheckout","resolveOfferId","prepareSubscriptionChange","resolveSubscriptionChange","onOpenUrl","onEvent","onAction","onComplete","onError"];function Qe(s,n,S){let O=e=>structuredClone({funnelId:e.funnelId,locale:e.locale,parameters:e.parameters}),m,_="",E=n.start instanceof Promise?void 0:O(n.start),ae=e=>e?.parameters?.commerce,T=Promise.resolve(n.start).then(e=>e?O(e):void 0),te=n.maxAgeMs??Xe,Ie=new AbortController,g=AbortSignal.any([Ie.signal,n.client.identitySignal,...n.signal?[n.signal]:[]]),oe=()=>u("released","aborted"),a="preparing",Se,j,le=()=>{},J=0,b=null,v=null,C=null,p=null,h,x,V,Ce=new Map,P=null,U=new Set,D=new Map,ie,Ae=new Promise(e=>ie=e),G,se=new Promise(e=>G=e),ce,Le=new Promise(e=>ce=e);function W(e,r){a!==e&&(a=e,Se=r,R(n.onState,e))}function Te(){g.removeEventListener("abort",oe),$(),v?.destroy(),v=null,b?.remove(),b=null,C=null}function u(e,r){["adopted","unavailable","released","closed"].includes(a)||(W(e,r),Te(),ie(!1),G(!1),X(!1),ce(null))}function N(e){a!=="shown"&&u("unavailable",e)}let f,de=!1,F=n.client.paywallCopies,ue,Re=new Promise(e=>ue=e),fe=!1,K=!1,ke,B=n.whenPurchasePending==="recover"&&!S,X,je=new Promise(e=>X=e);function Je(e){if(!B||f||!e||!p||!V||!A(p,V.commerce)||!["preparing","ready","shown"].includes(a))return!1;let r={savedAt:Date.now(),funnelId:e,context:V,resolution:structuredClone(p)};return f=r,we(r),Z(),!0}function pe(e){return!B||!f||!["preparing","ready","shown"].includes(a)?!1:(K=!0,ke=e,!0)}function we(e){Re.then(r=>{r&&F&&F.write(r,e).catch(()=>{})})}function _e(e){Re.then(async r=>{if(!r||!F)return;let l=await F.read(r);de||l&&"presented"in l||await F.write(r,e)}).catch(()=>{})}let ye=e=>`error:${e?.code??e?.name??"unknown"}`,me=s.ownerDocument.defaultView,M=!S,Ee=null,H=!1,Ue=e=>e.storageArea===me?.localStorage&&(e.key===null||e.key.startsWith("indiana.funnel.purchases.")),Ve=e=>{Ue(e)&&z()},Ge=S?()=>{}:n.client.subscribe(()=>z());function $(){M&&(M=!1,me?.removeEventListener("storage",Ve),Ge(),le())}let ge=()=>M&&(a==="ready"||a==="preparing");function he(e){(a==="ready"||a==="preparing")&&u("unavailable",e)}function z(){if(a==="ready"&&Date.now()-J>=te)return $();H=!0,Ee??=(async()=>{for(;H&&m&&!K&&ge();){H=!1;try{await n.client.retained()==="pending"&&!pe("purchase_pending")&&he("purchase_pending")}catch(e){g.aborted?u("released","aborted"):he(ye(e))}}})().finally(()=>{Ee=null,H&&m&&!K&&ge()&&z()})}S||me?.addEventListener("storage",Ve),g.addEventListener("abort",oe,{once:!0});let De=S?Promise.resolve("none"):n.client.findPurchase();De.catch(()=>{});let Q;function Y(e){let r=Q?.paywallVersionId??n.paywallVersionId??f?.resolution.id??p?.id,l=JSON.stringify(k([r??null,e])),i=Ce.get(l);return i||(i=n.client.readPaywall({paywallVersionId:r,...r?{}:{paywallId:Q?.paywallId??n.paywallId},...e}),Ce.set(l,i)),i}function A(e,r){let l=Object.values(e.capabilities.plans),i=Object.values(e.document.buttons).some(t=>t.type==="checkout");return i&&l.length===0?!1:r.intent==="subscription_change"&&i?l.some(t=>t.available):l.every(t=>t.available)}function Pe(e,r){if(p&&!ne(e,p))return u("unavailable","paywall_changed"),!1;p=e,V=r,X(!0);for(let l of D.keys())R(l,structuredClone(e));return!0}function Fe(e,r){if(!(!p||!["preparing","ready","shown"].includes(a))){if(!ne(e,p))return N("paywall_changed");if(!A(e,r.commerce))return N("plan_unavailable");Pe(e,r)}}async function q(){let e=await Le;if(!e)throw new Ne("PURCHASE_PENDING","The purchase did not start; open it again");return e}let We={get view(){return P?P.view:p},get signal(){return P?.signal??n.client.identitySignal},get quote(){return P?.quote??null},get operation(){return P?.operation??null},webViewUrl:"bundled",get canReselect(){return P?.canReselect},get recovery(){return P?.recovery},get pendingCancellation(){return P?.pendingCancellation},subscribe(e){return D.set(e,P?.subscribe?.(e)??(()=>{})),()=>{D.get(e)?.(),D.delete(e)}},refresh:async()=>P?P.refresh():structuredClone(p),preview:async e=>(await q()).preview(e),confirm:async()=>(await q()).confirm(),cancel:async()=>(await q()).cancel(),read:async()=>(await q()).read(),destroy(){P?.destroy()}},w={options:{},handoff:{}},He={loading:"host",focusAtReveal:!0,settleMotionAtReveal:!0,signal:n.client.identitySignal,start:async()=>We,canInteract:()=>w.options.canInteract?w.options.canInteract():!["unavailable","released","closed"].includes(a),async beforeAction(){let e=a!=="adopted",r=p?.capabilities,l=await q();if(e&&!L(l.view?.capabilities,r))throw new Me;await w.options.beforeAction?.()}};for(let e of ze)Object.defineProperty(He,e,{enumerable:!0,get:()=>w.options[e]});function Z(){a!=="preparing"||!C||!v||!f&&(!m||!L(V?.commerce,ae(m))||V?.locale!==m.locale)||(W("ready"),ie(!0))}let Oe={present(e){if(w.handoff.present)return w.handoff.present(e);a==="preparing"&&(C=e,J=Date.now(),Z())},async dismiss(){if(w.handoff.dismiss)return w.handoff.dismiss();u("closed");for(let e of[...U])R(e)},async closeAction(e){if(w.handoff.closeAction)return w.handoff.closeAction(e);w.options.onAction?await w.options.onAction(e):await Oe.dismiss()},quoteError(e){w.handoff.quoteError?w.handoff.quoteError(e):R(w.options.onError,e)}};async function Ke(){if(n.paywallVersionId||n.paywallId)return{paywallVersionId:n.paywallVersionId,paywallId:n.paywallId};let e=n.configuration;if(!e)return u("unavailable","paywall_missing"),null;let r=await Promise.resolve(n.start).catch(()=>null);if(!r||a!=="preparing")return null;let l=()=>ve(e,{funnelId:r.funnelId,customerId:n.client.customerId,parameters:r.parameters??{}});if(j=await l(),a!=="preparing")return null;let i=j;if(i.type!=="paywall")return u("unavailable",be(i)??"route"),null;let t=!1;return le=e.subscribe(()=>{t||!ge()||(t=!0,l().then(c=>{!(c.type==="unavailable"&&!["funnel_stopped","route_unavailable"].includes(c.reason))&&(c.type!=="paywall"||c.paywallVersionId!==i.paywallVersionId)&&he("route_changed")}).finally(()=>t=!1))}),M||le(),{paywallVersionId:i.paywallVersionId}}(async()=>{try{let[{showPaywall:e},r]=await Promise.all([import("./paywall-ZFSJSI6N.js"),Ke()]),l=n.commerce??ae(E),i=n.locale??E?.locale,t=r&&l&&i?JSON.stringify(k([r.paywallVersionId??null,r.paywallId??null,{commerce:l,locale:i}])):null;if(ue(t),g.throwIfAborted(),a!=="preparing"||!r)return;if(!l)return u("unavailable","commerce_missing");if(!i)return u("unavailable","locale_missing");Q=r;let c={commerce:l,locale:i},y=t?await F?.read(t).catch(()=>null):null;if(fe=!!y&&"presented"in y&&(!E||y.funnelId===E.funnelId),g.throwIfAborted(),a!=="preparing"||fe)return;y&&!("presented"in y)&&(!E||y.funnelId===E.funnelId)&&A(y.resolution,y.context.commerce)&&(f=y),G(!!f);let o;if(f){let ee=f.context;c=ee,o=structuredClone(f.resolution),Y(ee).then(Be=>Fe(Be,ee),()=>{})}else o=await Y(c);if(g.throwIfAborted(),a!=="preparing"||(!A(o,c.commerce)&&n.start instanceof Promise&&!h&&await T,!f&&h&&!L(c,h)&&(c=h,o=await Y(c)),g.throwIfAborted(),a!=="preparing"))return;if(!A(o,c.commerce))return u("unavailable","plan_unavailable");if(!Pe(o,c))return;b=s.ownerDocument.createElement("div"),s.append(b);let d=setTimeout(()=>a==="preparing"&&u("unavailable","timeout"),$e);Ae.then(()=>clearTimeout(d));let I=await e(b,He,Oe);if(!I.host||g.aborted||a!=="preparing"){I.host?.destroy(),u(g.aborted?"released":"unavailable","error");return}v=I.host,Z()}catch(e){u(g.aborted?"released":"unavailable",ye(e))}finally{ue(null),G(!1),X(!1)}})(),T.then(async e=>{let r=o=>{_e(null),N(o)},l=async()=>{let o=await De;return o==="pending"?"purchase_pending":o==="found"?"original_purchase":o==="blocked"?"purchase_blocked":void 0},i=async o=>!o||o==="purchase_blocked"||!B?!1:(await se,pe(o)?!0:await je&&Je(e?.funnelId??await n.client.pendingFunnel().catch(()=>null)??void 0)&&pe(o));if(!e)return B&&await i(await l().catch(()=>{}))?void 0:r("gated");let t=e,c=ae(t),y=n.commerce??c;if(!L(c&&{...c,intent:void 0},y&&{...y,intent:void 0})||n.locale!==void 0&&t.locale!==n.locale)return r("start_mismatch");if(!c)return r("commerce_missing");h={commerce:c,locale:t.locale},x=t,f&&["preparing","ready","shown"].includes(a)&&(m=t,_=re(t));try{let o=await l();if(await i(o)){m=void 0,_="";return}if(o)return r(o);if(!["preparing","ready","shown"].includes(a))return;if(n.configuration&&(n.paywallId||n.paywallVersionId)){let d=await ve(n.configuration,{funnelId:t.funnelId,customerId:n.client.customerId,parameters:t.parameters??{}});g.throwIfAborted();let I=d.type==="unknown"||d.type==="unavailable"&&d.reason!=="funnel_stopped";if(d.type==="paywall"?f?d.paywallId!==f.resolution.paywallId:n.paywallVersionId?d.paywallVersionId!==n.paywallVersionId:d.paywallId!==n.paywallId:!I)return r(be(d)??"route_changed")}if(M&&(H=!1,await n.client.retained()==="pending")){if(await i("purchase_pending")){m=void 0,_="";return}return r("purchase_pending")}if(await se,fe){m=t,_=re(t);return}if(Q||n.paywallId||n.paywallVersionId||p){let d=await Y(h);if(g.throwIfAborted(),_e(A(d,h.commerce)?{savedAt:Date.now(),funnelId:t.funnelId,context:h,resolution:d}:null),f)Fe(d,h);else{if(a!=="preparing")return;if(p){if(!A(d,h.commerce))return u("unavailable","plan_unavailable");if(!Pe(d,h))return}}}}catch(o){return g.aborted?u("released","aborted"):N(ye(o))}["preparing","ready","shown"].includes(a)&&(m=t,_=re(t),Z(),H&&z())},()=>N("gated"));let xe={get state(){return a},get reason(){return Se??ke},ready:Ae,local:se,get start(){return m},get prediction(){return j?structuredClone(j):void 0},matches:e=>m?re(e)===_:!!f&&e.funnelId===f.funnelId&&e.locale===f.context.locale,open(){if(a==="preparing")return"pending";if(a!=="ready"||!C)return!1;if(Date.now()-J>=te)return u("unavailable","expired"),!1;let e=C;return C=null,$(),W("shown"),e(),"shown"},destroy(){Ie.abort()}};return qe.set(xe,{onClose(e){return a==="closed"?(R(e),()=>{}):(U.add(e),()=>{U.delete(e)})},claim(){$()},remember(e){de=!0;let r=structuredClone(e);T.then(()=>{!x||!h||we({savedAt:Date.now(),funnelId:x.funnelId,context:h,resolution:r})},()=>{})},withhold(){de=!0,T.then(()=>{x&&we({savedAt:Date.now(),funnelId:x.funnelId,presented:"nothing"})},()=>{})},async adopt(e,r){let l=e.paywall?.resolution,i=e.paywall&&!e.paywall.quote&&!e.paywall.operation&&!e.paywall.purchaseRequestId&&!(e.paywall.selectionGeneration??0);if(a!=="shown"||!v||!p||!l||!i||e.source.id!==m?.funnelId||e.locale!==m?.locale||!L(e.parameters??{},m?.parameters??{})||!["running","waiting"].includes(e.status)||!ne(l,p))return null;let t;try{t=await r.start()}catch{return null}if(a!=="shown"||!v)return t.destroy(),null;P=t,w.options=r.options,w.handoff=r.handoff;for(let[o]of D)D.set(o,t.subscribe?.(o)??(()=>{})),t.view&&R(o,structuredClone(t.view));g.removeEventListener("abort",oe),W("adopted"),ce(t),U.clear();let c=v,y=b;return v=null,b=null,C=null,new Proxy(c,{get(o,d){return d==="destroy"?()=>{o.destroy(),y?.remove()}:d==="retainPurchaseDialog"?()=>{let I=o.retainPurchaseDialog();if(I)return{dialog:I.dialog,release(){I.release(),y?.remove()}}}:Reflect.get(o,d,o)}})},retainPurchaseDialog(){if(a!=="shown")return;let e=v?.retainPurchaseDialog();if(!e)return;let r=b;return v=null,b=null,u("released"),{dialog:e.dialog,release(){e.release(),r?.remove()}}},get modal(){return p?.document.presentation.type!=="inline"},get revealable(){return a==="ready"&&!!C&&Date.now()-J<te},get recovering(){return K},release(){u("released")}}),xe}function an(s,n){let S=n.run.parameters??{},O=S?.commerce;return Qe(s,{client:n.client,start:{funnelId:n.run.source.id,locale:n.run.locale,parameters:S},paywallVersionId:n.paywallVersionId,...O&&{commerce:O},locale:n.run.locale,signal:n.signal},{run:!0})}export{Xe as a,rn as b,Qe as c,an as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as C}from"./chunk-
|
|
1
|
+
import{a as C}from"./chunk-S5KGFAAW.js";import{a as v}from"./chunk-MWTSCBSY.js";import{h as I}from"./chunk-XSEYXS4X.js";import{b as g}from"./chunk-TZTWXL53.js";import{t as b}from"./chunk-SUUBL2WC.js";import{a as u}from"./chunk-E4B7243C.js";async function F(s,t){if(!s.closest("dialog")?.open)return null;let r=AbortSignal.any([t.signal,t.client.identitySignal]);r.throwIfAborted();let o=t.operationId?await t.client.recoverPurchasePaywall(void 0,t.operationId):await t.client.recoverPurchasePaywall();if(!o)return null;let c=o.view;if(!c||c.document.presentation.type!=="modal"||r.aborted)return o.destroy(),null;let l=t.upgradeReplacement,{session:m,prepare:f}=A({client:t.client,session:o,start:l?.start,signal:r}),p=I(s);if(!p)return o.destroy(),null;let n,i=new Promise(e=>{n=e}),w=!1,d=()=>n(!1);r.addEventListener("abort",d,{once:!0});try{let{host:e}=await C(s,{signal:r,start:async()=>m,loading:"host",checkoutNavigation:"after_confirmation",allowNewPurchase:!1,...l&&{beforeCheckoutReplacement:l.beforeCheckoutReplacement,resolveOfferId:l.resolveOfferId,resolveSubscriptionChange:l.resolveSubscriptionChange,terminateCheckout:a=>t.client.terminateCheckout(a),prepareUpgradeReplacement:f},resumeCheckout:a=>t.client.continueCheckout(t.onCheckoutUrl,a),onComplete:t.onComplete,onError(a){w?t.onError?.(a):n(!1)}},{retainedDialog:p,present(a){a(!0),w=!0,n(!0)},async dismiss(){t.onDismiss()}});return!e||!await i||r.aborted?(e?.destroy(),null):{document:c.document,destroy:()=>e.destroy()}}finally{r.removeEventListener("abort",d)}}function A(s){let t=s.start;if(!t)return{session:s.session};let{client:h,signal:r}=s,o=s.session,c=o,l;return{session:new Proxy(o,{get(p,n){let i=c[n];return typeof i=="function"?i.bind(c):i}}),prepare:async(p,n)=>{if(r.throwIfAborted(),o.operation?.operationId!==p||!o.canReselect)throw new u("PURCHASE_PENDING","The original purchase has not been closed");if(!l){let e=await t();if(!e)throw new u("PRODUCT_UNAVAILABLE","The selected plan is unavailable");if(e.funnelId!==h.attempt?.funnelId)throw new u("SCOPE_MISMATCH","The new purchase belongs to another Funnel");l={...e,requestId:e.requestId??crypto.randomUUID()}}r.throwIfAborted();let i=await h.start(l),w=h.controller;if(i.mode!=="run"||i.status!=="ready"||!w?.view?.paywall)throw new u("PURCHASE_PENDING","The current Paywall could not be opened for the replacement");let d=await v(w);try{r.throwIfAborted();let e=d.view,a=e?.document.buttons[n.actionId],y=e&&a?.type==="checkout"?g(a.product,n.selection,e.capabilities):null;if(!e||y!==n.productVersionId)throw new u("PRODUCT_UNAVAILABLE","The selected plan is no longer available");let P=b(e.document.screen,y,n.selection,e.capabilities);if(Object.keys(P).length!==Object.keys(n.featureQuantities).length||Object.entries(P).some(([S,k])=>n.featureQuantities[S]!==k))throw new u("PRODUCT_UNAVAILABLE","The selected plan quantities have changed");return c=d,o.destroy(),e}catch(e){throw d.destroy(),e}}}}export{F as a,A as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as me,E as rt,b as qe,c as $e,d as Se,h as He,i as Ke,j as Ye,n as We,q as Xe,z as nt}from"./chunk-EU7KLHEE.js";import{a as tt}from"./chunk-KSRJEMYQ.js";import{c as Ne,d as Te,e as _e,f as Le,g as De,i as Ue,m as ke,n as M,o as Ge,q as be,r as _,s as je,t as ze,u as Be,v as Je}from"./chunk-Q6SK6G7T.js";import{K as U,e as Ve,q as ve,r as Me}from"./chunk-LYTPUZOW.js";import{a as fe,b as Ze}from"./chunk-ZLRQ6X3A.js";import{a as le}from"./chunk-66SRWQES.js";import{e as de}from"./chunk-FINCNJBH.js";import{a as D}from"./chunk-E4B7243C.js";import{h as ie}from"./chunk-5SNUVXZ7.js";import{b as et}from"./chunk-3VUPVXAV.js";import{a as Qe}from"./chunk-5MRSFLQA.js";import{b as e}from"./chunk-7RUOZL6C.js";import{c as Fe,f as Pe}from"./chunk-VPT5MFDG.js";var j=e.literal(Ve),ht=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ot=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:xe}),e.strictObject({type:e.literal("customer"),customer:ve,customerData:Me.optional()})]),Ee=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),yt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:Ee.omit({runId:!0,requestId:!0}).nullable()}),wt=e.union([qe,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),It=$e.omit({authenticated:!0}).extend({identity:yt,instruction:wt.nullable()}),vt=e.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),pe={contract:j,customerToken:e.string().regex(le)},it={contract:j,requestId:e.uuid(),runToken:ht,externalUserId:ve.options[1].shape.value},at=e.discriminatedUnion("operation",[e.strictObject({contract:j,operation:e.literal("describe")}),e.strictObject({contract:j,operation:e.literal("start"),source:ot,funnelId:U.options[0].shape.funnelId,requestId:e.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),He.omit({operation:!0}).extend({contract:j,operation:e.literal("entry_start"),source:ot}),e.strictObject({...it,operation:e.literal("bind_customer"),guestToken:xe,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...it,operation:e.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("review")}),Ye.omit({customerToken:!0}).extend(pe),e.strictObject({...pe,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:vt})]),bt=Se.omit({run:!0}).extend({contract:j,run:It,settlement:Se.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Dt=Ke.extend({contract:j}),Ut=e.discriminatedUnion("operation",[at.options[1].omit({contract:!0,source:!0,requestId:!0}),at.options[2].omit({contract:!0,source:!0,requestId:!0})]),Vt=bt.extend({binding:Ee,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Mt=e.discriminatedUnion("state",[e.strictObject({contract:j,scope:ie,state:e.literal("not_accepted")}),e.strictObject({contract:j,scope:ie,state:e.literal("conflict")}),e.strictObject({contract:j,scope:ie,state:e.literal("bound"),binding:Ee})]),kt=e.strictObject({contract:j,scope:ie,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var st=e.string().regex(/^[a-f0-9]{64}$/),St=Ne.omit({variations:!0,active:!0}).extend({changeId:st,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),ut=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:st,experiments:e.array(St).max(100),savedGroups:Te}),xt=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),Bt=e.strictObject({events:e.array(xt).min(1).max(20)}),Jt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Wt(r){let a=null,g=null,O=0,v=0,C=new Set,l=null,w=null,m=new Set,b=()=>{for(let s of m)try{s()}catch{}},d={attributes:de.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,I)=>{!C.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(I),structuredClone(d.attributes),a.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,I)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(I),structuredClone(d.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,I=new Set){return C.has(s)?!l||!l.features[s]||["unknownFeature","cyclicPrerequisite"].includes(l.features[s].source):I.has(s)?!1:(I.add(s),(a?.features[s]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(P=>P.experiment.parentConditions??[])].some(P=>h(P.id,I))))}let x=s=>{if(r.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return l?.expiresAt&&Date.parse(l.expiresAt)<=Date.now()&&(l=null,d.features=a.features),C.has(s)?!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now()?S():structuredClone(l.features[s]??S()):r.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!l||h(s)?S():structuredClone(Pe(s,d))};async function V(){if(!a||!C.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=v;if(w?.revision===s)return w.loading;let I=O,F=a,P=[...C],E=(async()=>{let y=Ue.parse(await r.evaluateRemote({attributes:structuredClone(d.attributes),features:P}));if(!(I!==O||s!==v||F!==a)){if(r.assertUsable?.(F.generation),y.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(P.some(T=>!Object.hasOwn(y.features,T))||Object.keys(y.features).some(T=>!C.has(T)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!y.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=de.parse({...d.attributes,...y.merchandiseContext})}l=structuredClone(y),d.features={...F.features,...Object.fromEntries(Object.entries(l.features).map(([T,J])=>[T,{defaultValue:J.value}]))},b()}})();w={revision:s,loading:E};try{await E}finally{w?.loading===E&&(w=null)}}function L(){V().catch(s=>{try{r.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=O,I=(async()=>{let F=await r.load(),P="remoteFeatures"in F?Le.parse(F):null,E=P??_e.parse(F);if(E.scope.projectId!==r.scope.projectId||E.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==O)throw new Error("Feature client was reset");if(r.assertUsable&&a?.generation===E.generation){let{evaluatedAt:T,expiresAt:J,...ae}=a,{evaluatedAt:Z,expiresAt:ge,...z}=E;if(_(ae)!==_(z))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=E.evaluatedAt,a.expiresAt=E.expiresAt,b(),(!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now())&&L(),structuredClone(a)}let y=new Set(P?.remoteFeatures??[]);if([...y].some(T=>Object.hasOwn(E.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in E&&!a.analyticsConfig.experimentViewsEnabled&&P?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),a=structuredClone(E),C=y,l=null,w=null,v++,d.features=a.features,d.savedGroups=Fe(a.savedGroups),d.trackedFeatureUsage={},b(),L(),structuredClone(a)})();g=I;try{return await I}finally{g===I&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let I=de.parse(s);(d.attributes?.merchandise||d.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=I,v++,l=null,w=null,d.features=a?.features??{},d.trackedFeatureUsage={},b(),L()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,I){let F=x(s).value;return structuredClone(F===null?I:F)},reset(){O++,v++,g=null,w=null,a=null,l=null,C.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),b()}}}var Et=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),Q=2*1048576,Ct=100;function Rt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ct(r,a){let g=a===void 0?Rt():a,O=new Map,v=0,C=!1,l=!1,w,m;async function b(S){if(!g)return null;let h;try{let x=await Promise.race([Promise.resolve().then(()=>g.getItem(S)),new Promise(V=>{h=setTimeout(()=>V(null),Ct)})]);return typeof x=="string"&&x.length<=Q&&new TextEncoder().encode(x).byteLength<=Q?x:null}catch{return null}finally{clearTimeout(h)}}function d(){if(m)return m;let S=(async()=>{try{let h=await b(`${r}:artifacts`);if(h)return Et.parse(JSON.parse(h))}catch{}return{}})();return m=S,S.finally(()=>{m===S&&(m=void 0)}),S}return{async readManifest(){return b(r)},writeManifest(S){!g||S.length>Q||new TextEncoder().encode(S).byteLength>Q||(w=S,!l&&(l=!0,Promise.resolve().then(async()=>{try{for(;w!==void 0;){let h=w;try{await g.setItem(r,h)}catch{}w===h&&(w=void 0)}}finally{l=!1}})))},async readArtifact(S){let h=(await d())[S],x=Date.now();return h&&x>=h.at&&x-h.at<=M.retentionMs?h.text:void 0},writeArtifact(S,h){if(!g||h.length>Q)return;let x=O.get(S);if(x?.text===h||!x&&O.size>=128)return;let V=new TextEncoder().encode(h).byteLength;v-(x?.byteLength??0)+V>Q||(O.set(S,{text:h,byteLength:V}),v+=V-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;O.size;){let L=new Map(O);try{let k={...await d()},s=Date.now();for(let[E,y]of L)k[E]={at:s,text:y.text};let I={},F=2,P=0;for(let[E,y]of Object.entries(k).sort(([,T],[,J])=>J.at-T.at)){if(y.at>s||s-y.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[E]:y})).byteLength;F+T>Q||P>=128||(I[E]=y,F+=T,P++)}await g.setItem(`${r}:artifacts`,JSON.stringify(I))}catch{}finally{for(let[k,s]of L)O.get(k)===s&&(O.delete(k),v-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,a)=>new D(r,a),B=()=>performance.now(),lt=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function pn(r){let a=Ge.parse(r.scope),g=new fe(r.origin??Qe);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let O=new Set([g.origin,...(r.assetOrigins??[]).map(t=>{let n=new fe(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return n.origin})]),v=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${a.environmentId}`,l=`indiana:configuration:1:${g.origin}:${_(a)}`,w=ct(l,r.storage),m,b=0,d=0,S=!1,h=!1,x=0,V=0,L,k,s,I,F=0,P=new Set,E=new Set,y=new Map,T=new Map,J=0,ae=!1;function Z(){for(let t of P)try{t()}catch{}}function ge(t){try{r.onError?.(t)}catch{}}let z=()=>!h&&!S&&!!m&&B()<b&&Date.now()<d;function re(){if(!z())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(t,n,i){if(!y.has(t)){for(;y.size&&(y.size>=128||J+i>M.maxCacheBytes);){let o=y.entries().next().value;J-=o[1].byteLength,y.delete(o[0])}y.set(t,{text:n,byteLength:i}),J+=i}}function he(t,n,i){return et(t,n,{signal:i,error:o=>u("INVALID_RESPONSE",o==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function ye(t){let n=new fe(t,g);if(!O.has(n.origin)||n.username||n.password||n.hash||n.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return n.href}async function we(t,n,i=!1){let o=await v(ye(t),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:n,headers:{}});if(o.status===429){let f=o.headers.get("retry-after")??"";F=/^\d+$/.test(f)?Number(f)*1e3:Math.max(0,Date.parse(f)-Date.now())||15e3}if(!o.ok&&o.status!==304)throw u(`CONFIGURATION_HTTP_${o.status}`,"Configuration synchronization failed");return o}function ft(t,n,i){let o=Date.parse(t.headers.get("x-indiana-config-validated-at")??""),f=Date.parse(t.headers.get("x-indiana-config-valid-until")??""),p=Date.parse(t.headers.get("date")??""),c=t.headers.get("age"),R=c!==null&&/^\d+(\.\d+)?$/.test(c)?Number(c)*1e3:NaN;if(![o,f,p,R].every(Number.isFinite)||f<=o||f-o>M.maxControlAgeMs||o>p+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let A=Math.min(f-o,i.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(R,p-o,0)-(B()-n);if(A<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return B()+A}function se(){if(clearTimeout(s),clearTimeout(I),h||!P.size||(z()&&(I=setTimeout(()=>{z()?se():Z()},Math.max(1,b-B())),lt(I)),typeof document<"u"&&document.visibilityState==="hidden"))return;let t=V?Math.min(15e3,1e3*2**Math.min(V-1,4)):Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{X().catch(ge)},Math.max(F,t*(.8+Math.random()*.2))),lt(s)}async function X(){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let t=x,n=new AbortController;k=n;let i=(async()=>{if(!ae){ae=!0;try{let ce=await w.readManifest();if(ce&&!m){let $=be.parse(JSON.parse(ce));_($.scope)===_(a)&&(m=$)}}catch{}}n.signal.throwIfAborted();let c=m,R=B(),N=await we(C,n.signal);N.status===304&&(!c||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await we(C,n.signal));let A=N.status===304?c:be.parse(JSON.parse(await he(N,M.maxManifestBytes,n.signal))),{generation:G,...ne}=A,q=N.headers.get("etag");if(_(A.scope)!==_(a)||ze(ne)!==G||q!==`"${G}"`&&q!==`W/"${G}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(c&&(A.revision<c.revision||A.revision===c.revision&&A.generation!==c.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ce,$]of Object.entries(c?.funnels??{})){let W=A.funnels[ce];if(W&&(W.controlRevision<$.controlRevision||W.evaluationRevision<$.evaluationRevision||W.controlRevision===$.controlRevision&&W.state!==$.state||W.evaluationRevision===$.evaluationRevision&&W.evaluationMode!==$.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=ft(N,R,A.policy);if(n.signal.throwIfAborted(),t!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return m=A,b=Y,d=Date.now()+Math.max(0,Y-B()),S=!1,V=0,F=0,w.writeManifest(_(A)),Z(),structuredClone(A)})(),o=setTimeout(()=>n.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),f=new Promise((c,R)=>n.signal.addEventListener("abort",()=>R(n.signal.reason),{once:!0})),p=Promise.race([i,f]).catch(c=>{throw V++,(c instanceof e.ZodError||c instanceof SyntaxError||c instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(c.code))&&(b=0,S=!0,Z()),c}).finally(()=>{clearTimeout(o),L===p&&(L=void 0),se()});return L=p,p}async function ue(t){let n=t.sha256,i=ne=>tt(ne,t);ye(t.url);let o=y.get(n);if(o){if(o.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return y.delete(n),y.set(n,o),o.text}let f=T.get(n);if(f){if(f.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return f.promise}let p=new AbortController;E.add(p);let c=x,R=(async()=>{try{let Y=await w.readArtifact(n);if(Y&&i(Y)){if(p.signal.throwIfAborted(),h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,Y,t.byteLength),Y}}catch{}p.signal.throwIfAborted();let ne=await we(t.url,p.signal,!0),q=await he(ne,t.byteLength,p.signal);if(!i(q))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,q,t.byteLength),w.writeArtifact(n,q),q})(),N=setTimeout(()=>p.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),A=new Promise((ne,q)=>p.signal.addEventListener("abort",()=>q(p.signal.reason),{once:!0})),G=Promise.race([R,A]).finally(()=>{clearTimeout(N),E.delete(p),T.delete(n)});return T.set(n,{promise:G,byteLength:t.byteLength}),G}async function ee(){return z()||await X(),re(),m}async function K(t){let n,i=new Promise((o,f)=>{n=setTimeout(()=>f(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([t(),i])}finally{clearTimeout(n)}}function H(t,n){if(re(),m?.generation!==t.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(n&&m.funnels[n]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Re(t){let n=t.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let o=De.parse(JSON.parse(await ue(i)));if(_(o.scope)!==_({projectId:a.projectId,environment:a.environment})||o.generation!==i.generation||o.remoteFeatures.some(f=>Object.hasOwn(o.features,f)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return H(t),{...o,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,b-B())).toISOString()}}async function Oe(t,n){let i=await ee(),o=i.funnels[t];n&&(!o||o.evaluationMode==="local"&&!o.versions[n])&&(L&&await L,i=await X()),H(i,t);let f=i.funnels[t];if(f.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let p=n??f.currentVersionId,c=f.versions[p];if(!c)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[c.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[R,N]=await Promise.all([ue(i.artifacts[c.artifact]).then(A=>Je(JSON.parse(A))),f.evaluationMode==="local"?Re(i):void 0]);if(N&&_(Be(R,N))!==_(c.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return H(i,t),{document:R,growth:N,versionId:p,control:structuredClone(f),manifest:structuredClone(i)}}async function Ie(t,n){try{return await Oe(t,n)}catch(i){if(!(i instanceof D)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&z()))throw i;let o=m?.generation;if(L&&await L,await X(),i.code!=="CONFIGURATION_CHANGED"&&m?.generation===o)throw i;return Oe(t,n)}}let oe=new Map;async function mt(t,n){let{FUNNEL_ROUTE_LIMITS:i,funnelRouteSchema:o}=await import("./funnel-route-source-2OGRCZKX.js"),f=new AbortController;E.add(f);let p=setTimeout(()=>f.abort(u("CONFIGURATION_UNAVAILABLE","Funnel route read timed out")),M.initializationMs);try{let c=await v(ye(`${C}/funnels/${t}/versions/${n}/route`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:f.signal,headers:{}});if(c.status===404)throw u("ROUTE_UNAVAILABLE","This Funnel Version publishes no route");if(!c.ok)throw u(`CONFIGURATION_HTTP_${c.status}`,"Funnel route read failed");let R=await he(c,i.maxBytes,f.signal),N=je(R),A=c.headers.get("etag");if(A!==`"${N}"`&&A!==`W/"${N}"`)throw u("INVALID_RESPONSE","Funnel route identity changed");let G=o.safeParse(JSON.parse(R));if(!G.success||G.data.funnelId!==t||G.data.versionId!==n)throw u("INVALID_RESPONSE","Funnel route does not describe this Version");return G.data}finally{clearTimeout(p),E.delete(f)}}async function pt(t){let n=await ee();H(n,t);let i=n.funnels[t],o=i.currentVersionId,f;if(i.evaluationMode==="local"){let{projectFunnelRoute:p}=await import("./funnel-route-source-2OGRCZKX.js"),c=await Ie(t,o),R=Object.entries(c.manifest.paywalls??{});f=p({funnelId:t,versionId:o,document:c.document,experiments:c.growth?.experiments??{},paywallOf:N=>R.find(([,A])=>Object.hasOwn(A.versions,N))?.[0]})}else{let p=`${t}:${o}`,c=oe.get(p);if(!c||B()-c.readAt>=M.maxControlAgeMs){let R={promise:mt(t,o),readAt:B()};oe.set(p,R),R.promise.catch(()=>{oe.get(p)===R&&oe.delete(p)}),c=R}f=await c.promise}return H(n,t),{route:structuredClone(f),control:structuredClone(i),generation:n.generation}}function te(){if(z()||Z(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}X().catch(ge)}function gt(t){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return P.add(t),P.size===1&&(typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("focus",te),document.addEventListener("visibilitychange",te)),se()),()=>{P.delete(t),P.size||(clearTimeout(s),clearTimeout(I),Ae())}}function Ae(){typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("focus",te),document.removeEventListener("visibilitychange",te))}return{scope:Object.freeze({...a}),refresh:X,subscribe:gt,assertFresh:re,assertFeatures(t){re();let n=m.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(t!==void 0&&m.artifacts[n].generation!==t)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return z()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return z()?Math.max(0,b-B()):0},async features(){return K(async()=>Re(await ee()))},pageExperiments:()=>K(async()=>{let t=await ee(),n=t.gb.pageExperiments;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let o=ut.parse(JSON.parse(await ue(i)));if(o.environmentId!==a.environmentId||o.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return H(t),o}),funnel:(t,n)=>K(()=>Ie(t,n)),funnelControl:t=>K(async()=>{let n=await ee();return H(n,t),structuredClone(n.funnels[t])}),funnelRoute:t=>K(()=>pt(t)),paywall:(t,n)=>K(async()=>{let i=await ee(),o=i.paywalls?.[t];if(!o||!n&&o.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let f=n??o.currentVersionId,p=o.versions[f],c=p&&i.artifacts[p.artifact];if(!c||c.kind!=="paywall"||c.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let R=ke.parse(JSON.parse(await ue(c)));return H(i),{document:R,versionId:f,version:p.version,control:structuredClone(o),manifest:structuredClone(i)}}),async localFunnel(t,n){let i=await K(()=>Ie(t,n));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:o,remoteFeatures:f,...p}=i.growth;return We({scope:{projectId:a.projectId,environment:a.environment},funnelId:t,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:p})},assertFunnel(t,n,i){re();let o=m.funnels[t];if(!o||o.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(o.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(n!==void 0&&o.controlRevision!==n)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!o.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,x++,b=0,k?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(I),Ae(),Z(),P.clear();for(let t of E)t.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));y.clear(),oe.clear(),J=0}}}}function dt(r){let a=le.test(r.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!me.test(r.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let O=U.safeParse({...g,operation:"start"});if(!O.success||O.data.operation!=="start"||(a?O.data.customer!==void 0:O.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let v=O.data,C=Ze({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let l=Xe(r,await C.request("funnels",v));if(!l.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(l.run.source.id!==v.funnelId||l.run.locale!==(v.locale??"en")||!nt(l.run.parameters,v.parameters??{})||(v.customer?!l.customerId||v.customer.type==="id"&&l.customerId!==v.customer.value:l.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...l,runToken:l.runToken}}finally{C.dispose()}}}}async function An(r){r={...r};let a=r.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(r.scope&&_(g)!==_(r.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(r.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let v=me.test(r.credential);if(v?!r.customerId:r.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=dt({...r,scope:g,apiKey:r.credential}),l=(w,m)=>{let b=rt({...r,scope:g,runToken:w,initialResponse:m,...v?{serverKey:r.credential}:{}});return v||b.identify(r.credential),b};return{async start(w){let m=await C.start({...w,funnelId:r.funnelId,...v?{customer:{type:"id",value:r.customerId}}:{}}),b=l(m.runToken,m),d=await b.get();return{...m,...d,controller:b}},async restore(w){let m=l(w),b=await m.get();if(b.run.source.id!==r.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...b,runToken:w,controller:m}}}}export{at as a,bt as b,Dt as c,Ut as d,Vt as e,Mt as f,kt as g,Wt as h,pn as i,dt as j,An as k};
|
|
1
|
+
import{A as me,E as rt,b as qe,c as $e,d as Se,h as He,i as Ke,j as Ye,n as We,q as Xe,z as nt}from"./chunk-ZL7YW35H.js";import{a as tt}from"./chunk-JJIOGZIP.js";import{c as Ne,d as Te,e as _e,f as Le,g as De,i as Ue,m as ke,n as M,o as Ge,q as be,r as _,s as je,t as ze,u as Be,v as Je}from"./chunk-Q6SK6G7T.js";import{K as U,e as Ve,q as ve,r as Me}from"./chunk-LYTPUZOW.js";import{a as fe,b as Ze}from"./chunk-T5QI2ZZR.js";import{a as le}from"./chunk-66SRWQES.js";import{e as de}from"./chunk-FINCNJBH.js";import{a as D}from"./chunk-E4B7243C.js";import{h as ie}from"./chunk-5SNUVXZ7.js";import{b as et}from"./chunk-3VUPVXAV.js";import{a as Qe}from"./chunk-5MRSFLQA.js";import{b as e}from"./chunk-7RUOZL6C.js";import{c as Fe,f as Pe}from"./chunk-VPT5MFDG.js";var j=e.literal(Ve),ht=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ot=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:xe}),e.strictObject({type:e.literal("customer"),customer:ve,customerData:Me.optional()})]),Ee=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),yt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:Ee.omit({runId:!0,requestId:!0}).nullable()}),wt=e.union([qe,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),It=$e.omit({authenticated:!0}).extend({identity:yt,instruction:wt.nullable()}),vt=e.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),pe={contract:j,customerToken:e.string().regex(le)},it={contract:j,requestId:e.uuid(),runToken:ht,externalUserId:ve.options[1].shape.value},at=e.discriminatedUnion("operation",[e.strictObject({contract:j,operation:e.literal("describe")}),e.strictObject({contract:j,operation:e.literal("start"),source:ot,funnelId:U.options[0].shape.funnelId,requestId:e.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),He.omit({operation:!0}).extend({contract:j,operation:e.literal("entry_start"),source:ot}),e.strictObject({...it,operation:e.literal("bind_customer"),guestToken:xe,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...it,operation:e.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("review")}),Ye.omit({customerToken:!0}).extend(pe),e.strictObject({...pe,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:vt})]),bt=Se.omit({run:!0}).extend({contract:j,run:It,settlement:Se.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Dt=Ke.extend({contract:j}),Ut=e.discriminatedUnion("operation",[at.options[1].omit({contract:!0,source:!0,requestId:!0}),at.options[2].omit({contract:!0,source:!0,requestId:!0})]),Vt=bt.extend({binding:Ee,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Mt=e.discriminatedUnion("state",[e.strictObject({contract:j,scope:ie,state:e.literal("not_accepted")}),e.strictObject({contract:j,scope:ie,state:e.literal("conflict")}),e.strictObject({contract:j,scope:ie,state:e.literal("bound"),binding:Ee})]),kt=e.strictObject({contract:j,scope:ie,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var st=e.string().regex(/^[a-f0-9]{64}$/),St=Ne.omit({variations:!0,active:!0}).extend({changeId:st,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),ut=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:st,experiments:e.array(St).max(100),savedGroups:Te}),xt=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),Bt=e.strictObject({events:e.array(xt).min(1).max(20)}),Jt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Wt(r){let a=null,g=null,O=0,v=0,C=new Set,l=null,w=null,m=new Set,b=()=>{for(let s of m)try{s()}catch{}},d={attributes:de.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,I)=>{!C.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(I),structuredClone(d.attributes),a.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,I)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(I),structuredClone(d.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,I=new Set){return C.has(s)?!l||!l.features[s]||["unknownFeature","cyclicPrerequisite"].includes(l.features[s].source):I.has(s)?!1:(I.add(s),(a?.features[s]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(P=>P.experiment.parentConditions??[])].some(P=>h(P.id,I))))}let x=s=>{if(r.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return l?.expiresAt&&Date.parse(l.expiresAt)<=Date.now()&&(l=null,d.features=a.features),C.has(s)?!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now()?S():structuredClone(l.features[s]??S()):r.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!l||h(s)?S():structuredClone(Pe(s,d))};async function V(){if(!a||!C.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=v;if(w?.revision===s)return w.loading;let I=O,F=a,P=[...C],E=(async()=>{let y=Ue.parse(await r.evaluateRemote({attributes:structuredClone(d.attributes),features:P}));if(!(I!==O||s!==v||F!==a)){if(r.assertUsable?.(F.generation),y.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(P.some(T=>!Object.hasOwn(y.features,T))||Object.keys(y.features).some(T=>!C.has(T)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!y.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=de.parse({...d.attributes,...y.merchandiseContext})}l=structuredClone(y),d.features={...F.features,...Object.fromEntries(Object.entries(l.features).map(([T,J])=>[T,{defaultValue:J.value}]))},b()}})();w={revision:s,loading:E};try{await E}finally{w?.loading===E&&(w=null)}}function L(){V().catch(s=>{try{r.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=O,I=(async()=>{let F=await r.load(),P="remoteFeatures"in F?Le.parse(F):null,E=P??_e.parse(F);if(E.scope.projectId!==r.scope.projectId||E.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==O)throw new Error("Feature client was reset");if(r.assertUsable&&a?.generation===E.generation){let{evaluatedAt:T,expiresAt:J,...ae}=a,{evaluatedAt:Z,expiresAt:ge,...z}=E;if(_(ae)!==_(z))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=E.evaluatedAt,a.expiresAt=E.expiresAt,b(),(!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now())&&L(),structuredClone(a)}let y=new Set(P?.remoteFeatures??[]);if([...y].some(T=>Object.hasOwn(E.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in E&&!a.analyticsConfig.experimentViewsEnabled&&P?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),a=structuredClone(E),C=y,l=null,w=null,v++,d.features=a.features,d.savedGroups=Fe(a.savedGroups),d.trackedFeatureUsage={},b(),L(),structuredClone(a)})();g=I;try{return await I}finally{g===I&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let I=de.parse(s);(d.attributes?.merchandise||d.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=I,v++,l=null,w=null,d.features=a?.features??{},d.trackedFeatureUsage={},b(),L()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,I){let F=x(s).value;return structuredClone(F===null?I:F)},reset(){O++,v++,g=null,w=null,a=null,l=null,C.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),b()}}}var Et=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),Q=2*1048576,Ct=100;function Rt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ct(r,a){let g=a===void 0?Rt():a,O=new Map,v=0,C=!1,l=!1,w,m;async function b(S){if(!g)return null;let h;try{let x=await Promise.race([Promise.resolve().then(()=>g.getItem(S)),new Promise(V=>{h=setTimeout(()=>V(null),Ct)})]);return typeof x=="string"&&x.length<=Q&&new TextEncoder().encode(x).byteLength<=Q?x:null}catch{return null}finally{clearTimeout(h)}}function d(){if(m)return m;let S=(async()=>{try{let h=await b(`${r}:artifacts`);if(h)return Et.parse(JSON.parse(h))}catch{}return{}})();return m=S,S.finally(()=>{m===S&&(m=void 0)}),S}return{async readManifest(){return b(r)},writeManifest(S){!g||S.length>Q||new TextEncoder().encode(S).byteLength>Q||(w=S,!l&&(l=!0,Promise.resolve().then(async()=>{try{for(;w!==void 0;){let h=w;try{await g.setItem(r,h)}catch{}w===h&&(w=void 0)}}finally{l=!1}})))},async readArtifact(S){let h=(await d())[S],x=Date.now();return h&&x>=h.at&&x-h.at<=M.retentionMs?h.text:void 0},writeArtifact(S,h){if(!g||h.length>Q)return;let x=O.get(S);if(x?.text===h||!x&&O.size>=128)return;let V=new TextEncoder().encode(h).byteLength;v-(x?.byteLength??0)+V>Q||(O.set(S,{text:h,byteLength:V}),v+=V-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;O.size;){let L=new Map(O);try{let k={...await d()},s=Date.now();for(let[E,y]of L)k[E]={at:s,text:y.text};let I={},F=2,P=0;for(let[E,y]of Object.entries(k).sort(([,T],[,J])=>J.at-T.at)){if(y.at>s||s-y.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[E]:y})).byteLength;F+T>Q||P>=128||(I[E]=y,F+=T,P++)}await g.setItem(`${r}:artifacts`,JSON.stringify(I))}catch{}finally{for(let[k,s]of L)O.get(k)===s&&(O.delete(k),v-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,a)=>new D(r,a),B=()=>performance.now(),lt=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function pn(r){let a=Ge.parse(r.scope),g=new fe(r.origin??Qe);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let O=new Set([g.origin,...(r.assetOrigins??[]).map(t=>{let n=new fe(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return n.origin})]),v=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${a.environmentId}`,l=`indiana:configuration:1:${g.origin}:${_(a)}`,w=ct(l,r.storage),m,b=0,d=0,S=!1,h=!1,x=0,V=0,L,k,s,I,F=0,P=new Set,E=new Set,y=new Map,T=new Map,J=0,ae=!1;function Z(){for(let t of P)try{t()}catch{}}function ge(t){try{r.onError?.(t)}catch{}}let z=()=>!h&&!S&&!!m&&B()<b&&Date.now()<d;function re(){if(!z())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(t,n,i){if(!y.has(t)){for(;y.size&&(y.size>=128||J+i>M.maxCacheBytes);){let o=y.entries().next().value;J-=o[1].byteLength,y.delete(o[0])}y.set(t,{text:n,byteLength:i}),J+=i}}function he(t,n,i){return et(t,n,{signal:i,error:o=>u("INVALID_RESPONSE",o==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function ye(t){let n=new fe(t,g);if(!O.has(n.origin)||n.username||n.password||n.hash||n.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return n.href}async function we(t,n,i=!1){let o=await v(ye(t),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:n,headers:{}});if(o.status===429){let f=o.headers.get("retry-after")??"";F=/^\d+$/.test(f)?Number(f)*1e3:Math.max(0,Date.parse(f)-Date.now())||15e3}if(!o.ok&&o.status!==304)throw u(`CONFIGURATION_HTTP_${o.status}`,"Configuration synchronization failed");return o}function ft(t,n,i){let o=Date.parse(t.headers.get("x-indiana-config-validated-at")??""),f=Date.parse(t.headers.get("x-indiana-config-valid-until")??""),p=Date.parse(t.headers.get("date")??""),c=t.headers.get("age"),R=c!==null&&/^\d+(\.\d+)?$/.test(c)?Number(c)*1e3:NaN;if(![o,f,p,R].every(Number.isFinite)||f<=o||f-o>M.maxControlAgeMs||o>p+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let A=Math.min(f-o,i.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(R,p-o,0)-(B()-n);if(A<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return B()+A}function se(){if(clearTimeout(s),clearTimeout(I),h||!P.size||(z()&&(I=setTimeout(()=>{z()?se():Z()},Math.max(1,b-B())),lt(I)),typeof document<"u"&&document.visibilityState==="hidden"))return;let t=V?Math.min(15e3,1e3*2**Math.min(V-1,4)):Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{X().catch(ge)},Math.max(F,t*(.8+Math.random()*.2))),lt(s)}async function X(){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let t=x,n=new AbortController;k=n;let i=(async()=>{if(!ae){ae=!0;try{let ce=await w.readManifest();if(ce&&!m){let $=be.parse(JSON.parse(ce));_($.scope)===_(a)&&(m=$)}}catch{}}n.signal.throwIfAborted();let c=m,R=B(),N=await we(C,n.signal);N.status===304&&(!c||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await we(C,n.signal));let A=N.status===304?c:be.parse(JSON.parse(await he(N,M.maxManifestBytes,n.signal))),{generation:G,...ne}=A,q=N.headers.get("etag");if(_(A.scope)!==_(a)||ze(ne)!==G||q!==`"${G}"`&&q!==`W/"${G}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(c&&(A.revision<c.revision||A.revision===c.revision&&A.generation!==c.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ce,$]of Object.entries(c?.funnels??{})){let W=A.funnels[ce];if(W&&(W.controlRevision<$.controlRevision||W.evaluationRevision<$.evaluationRevision||W.controlRevision===$.controlRevision&&W.state!==$.state||W.evaluationRevision===$.evaluationRevision&&W.evaluationMode!==$.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=ft(N,R,A.policy);if(n.signal.throwIfAborted(),t!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return m=A,b=Y,d=Date.now()+Math.max(0,Y-B()),S=!1,V=0,F=0,w.writeManifest(_(A)),Z(),structuredClone(A)})(),o=setTimeout(()=>n.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),f=new Promise((c,R)=>n.signal.addEventListener("abort",()=>R(n.signal.reason),{once:!0})),p=Promise.race([i,f]).catch(c=>{throw V++,(c instanceof e.ZodError||c instanceof SyntaxError||c instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(c.code))&&(b=0,S=!0,Z()),c}).finally(()=>{clearTimeout(o),L===p&&(L=void 0),se()});return L=p,p}async function ue(t){let n=t.sha256,i=ne=>tt(ne,t);ye(t.url);let o=y.get(n);if(o){if(o.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return y.delete(n),y.set(n,o),o.text}let f=T.get(n);if(f){if(f.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return f.promise}let p=new AbortController;E.add(p);let c=x,R=(async()=>{try{let Y=await w.readArtifact(n);if(Y&&i(Y)){if(p.signal.throwIfAborted(),h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,Y,t.byteLength),Y}}catch{}p.signal.throwIfAborted();let ne=await we(t.url,p.signal,!0),q=await he(ne,t.byteLength,p.signal);if(!i(q))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,q,t.byteLength),w.writeArtifact(n,q),q})(),N=setTimeout(()=>p.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),A=new Promise((ne,q)=>p.signal.addEventListener("abort",()=>q(p.signal.reason),{once:!0})),G=Promise.race([R,A]).finally(()=>{clearTimeout(N),E.delete(p),T.delete(n)});return T.set(n,{promise:G,byteLength:t.byteLength}),G}async function ee(){return z()||await X(),re(),m}async function K(t){let n,i=new Promise((o,f)=>{n=setTimeout(()=>f(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([t(),i])}finally{clearTimeout(n)}}function H(t,n){if(re(),m?.generation!==t.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(n&&m.funnels[n]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Re(t){let n=t.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let o=De.parse(JSON.parse(await ue(i)));if(_(o.scope)!==_({projectId:a.projectId,environment:a.environment})||o.generation!==i.generation||o.remoteFeatures.some(f=>Object.hasOwn(o.features,f)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return H(t),{...o,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,b-B())).toISOString()}}async function Oe(t,n){let i=await ee(),o=i.funnels[t];n&&(!o||o.evaluationMode==="local"&&!o.versions[n])&&(L&&await L,i=await X()),H(i,t);let f=i.funnels[t];if(f.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let p=n??f.currentVersionId,c=f.versions[p];if(!c)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[c.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[R,N]=await Promise.all([ue(i.artifacts[c.artifact]).then(A=>Je(JSON.parse(A))),f.evaluationMode==="local"?Re(i):void 0]);if(N&&_(Be(R,N))!==_(c.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return H(i,t),{document:R,growth:N,versionId:p,control:structuredClone(f),manifest:structuredClone(i)}}async function Ie(t,n){try{return await Oe(t,n)}catch(i){if(!(i instanceof D)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&z()))throw i;let o=m?.generation;if(L&&await L,await X(),i.code!=="CONFIGURATION_CHANGED"&&m?.generation===o)throw i;return Oe(t,n)}}let oe=new Map;async function mt(t,n){let{FUNNEL_ROUTE_LIMITS:i,funnelRouteSchema:o}=await import("./funnel-route-source-2OGRCZKX.js"),f=new AbortController;E.add(f);let p=setTimeout(()=>f.abort(u("CONFIGURATION_UNAVAILABLE","Funnel route read timed out")),M.initializationMs);try{let c=await v(ye(`${C}/funnels/${t}/versions/${n}/route`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:f.signal,headers:{}});if(c.status===404)throw u("ROUTE_UNAVAILABLE","This Funnel Version publishes no route");if(!c.ok)throw u(`CONFIGURATION_HTTP_${c.status}`,"Funnel route read failed");let R=await he(c,i.maxBytes,f.signal),N=je(R),A=c.headers.get("etag");if(A!==`"${N}"`&&A!==`W/"${N}"`)throw u("INVALID_RESPONSE","Funnel route identity changed");let G=o.safeParse(JSON.parse(R));if(!G.success||G.data.funnelId!==t||G.data.versionId!==n)throw u("INVALID_RESPONSE","Funnel route does not describe this Version");return G.data}finally{clearTimeout(p),E.delete(f)}}async function pt(t){let n=await ee();H(n,t);let i=n.funnels[t],o=i.currentVersionId,f;if(i.evaluationMode==="local"){let{projectFunnelRoute:p}=await import("./funnel-route-source-2OGRCZKX.js"),c=await Ie(t,o),R=Object.entries(c.manifest.paywalls??{});f=p({funnelId:t,versionId:o,document:c.document,experiments:c.growth?.experiments??{},paywallOf:N=>R.find(([,A])=>Object.hasOwn(A.versions,N))?.[0]})}else{let p=`${t}:${o}`,c=oe.get(p);if(!c||B()-c.readAt>=M.maxControlAgeMs){let R={promise:mt(t,o),readAt:B()};oe.set(p,R),R.promise.catch(()=>{oe.get(p)===R&&oe.delete(p)}),c=R}f=await c.promise}return H(n,t),{route:structuredClone(f),control:structuredClone(i),generation:n.generation}}function te(){if(z()||Z(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}X().catch(ge)}function gt(t){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return P.add(t),P.size===1&&(typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("focus",te),document.addEventListener("visibilitychange",te)),se()),()=>{P.delete(t),P.size||(clearTimeout(s),clearTimeout(I),Ae())}}function Ae(){typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("focus",te),document.removeEventListener("visibilitychange",te))}return{scope:Object.freeze({...a}),refresh:X,subscribe:gt,assertFresh:re,assertFeatures(t){re();let n=m.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(t!==void 0&&m.artifacts[n].generation!==t)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return z()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return z()?Math.max(0,b-B()):0},async features(){return K(async()=>Re(await ee()))},pageExperiments:()=>K(async()=>{let t=await ee(),n=t.gb.pageExperiments;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let o=ut.parse(JSON.parse(await ue(i)));if(o.environmentId!==a.environmentId||o.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return H(t),o}),funnel:(t,n)=>K(()=>Ie(t,n)),funnelControl:t=>K(async()=>{let n=await ee();return H(n,t),structuredClone(n.funnels[t])}),funnelRoute:t=>K(()=>pt(t)),paywall:(t,n)=>K(async()=>{let i=await ee(),o=i.paywalls?.[t];if(!o||!n&&o.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let f=n??o.currentVersionId,p=o.versions[f],c=p&&i.artifacts[p.artifact];if(!c||c.kind!=="paywall"||c.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let R=ke.parse(JSON.parse(await ue(c)));return H(i),{document:R,versionId:f,version:p.version,control:structuredClone(o),manifest:structuredClone(i)}}),async localFunnel(t,n){let i=await K(()=>Ie(t,n));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:o,remoteFeatures:f,...p}=i.growth;return We({scope:{projectId:a.projectId,environment:a.environment},funnelId:t,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:p})},assertFunnel(t,n,i){re();let o=m.funnels[t];if(!o||o.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(o.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(n!==void 0&&o.controlRevision!==n)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!o.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,x++,b=0,k?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(I),Ae(),Z(),P.clear();for(let t of E)t.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));y.clear(),oe.clear(),J=0}}}}function dt(r){let a=le.test(r.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!me.test(r.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let O=U.safeParse({...g,operation:"start"});if(!O.success||O.data.operation!=="start"||(a?O.data.customer!==void 0:O.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let v=O.data,C=Ze({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let l=Xe(r,await C.request("funnels",v));if(!l.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(l.run.source.id!==v.funnelId||l.run.locale!==(v.locale??"en")||!nt(l.run.parameters,v.parameters??{})||(v.customer?!l.customerId||v.customer.type==="id"&&l.customerId!==v.customer.value:l.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...l,runToken:l.runToken}}finally{C.dispose()}}}}async function An(r){r={...r};let a=r.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(r.scope&&_(g)!==_(r.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(r.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let v=me.test(r.credential);if(v?!r.customerId:r.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=dt({...r,scope:g,apiKey:r.credential}),l=(w,m)=>{let b=rt({...r,scope:g,runToken:w,initialResponse:m,...v?{serverKey:r.credential}:{}});return v||b.identify(r.credential),b};return{async start(w){let m=await C.start({...w,funnelId:r.funnelId,...v?{customer:{type:"id",value:r.customerId}}:{}}),b=l(m.runToken,m),d=await b.get();return{...m,...d,controller:b}},async restore(w){let m=l(w),b=await m.get();if(b.run.source.id!==r.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...b,runToken:w,controller:m}}}}export{at as a,bt as b,Dt as c,Ut as d,Vt as e,Mt as f,kt as g,Wt as h,pn as i,dt as j,An as k};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as w,f as b}from"./chunk-DMMD4TMS.js";import{n as h,s as u}from"./chunk-Q6SK6G7T.js";import{a as y}from"./chunk-
|
|
1
|
+
import{e as w,f as b}from"./chunk-DMMD4TMS.js";import{n as h,s as u}from"./chunk-Q6SK6G7T.js";import{a as y}from"./chunk-T5QI2ZZR.js";import{a as n}from"./chunk-E4B7243C.js";import{a as g}from"./chunk-3VUPVXAV.js";import{a as f}from"./chunk-5MRSFLQA.js";function p(r,s){let a=typeof r=="string"?new TextEncoder().encode(r):r;return a.byteLength===s.byteLength&&u(a)===s.sha256}async function _(r,s){let a=w.parse(s),{artifact:i,environmentId:P}=a.content,m=new y(r.baseUrl??f).origin,e=new y(i.url,m);if(e.origin!==m||e.username||e.password||e.search||e.hash||e.pathname!==`/api/v1/configuration/${P}/artifacts/${i.sha256}`)throw new n("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,d,I=new Promise((t,l)=>{d=setTimeout(()=>{let c=new n("TIMEOUT","Public Paywall read timed out");o.abort(c),l(c)},h.initializationMs)}),E=(async()=>{let t=await(r.fetch??globalThis.fetch)(e,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(t.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!t.ok||!t.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(t.headers.get("content-length"))>i.byteLength)throw t.body?.cancel().catch(()=>{}),new n("INVALID_RESPONSE","Public Paywall is unavailable");let l=await g(t,i.byteLength,{signal:o.signal,error:c=>new n("INVALID_RESPONSE",c==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!p(l,i))throw new n("INVALID_RESPONSE","Public Paywall digest or size changed");return b(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))})();try{return await Promise.race([E,I])}finally{clearTimeout(d)}}export{p as a,_ as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as n,r as t}from"./chunk-ZL7YW35H.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as kn,c as Rn,d as _t,f as Lt,g as An,k as Sn}from"./chunk-IEYSWIRA.js";import{a as wn,b as Ye}from"./chunk-W32FI2A2.js";import{e as bn,f as Cn,g as Pn,h as vn,j as Ut,k as ot,l as In,m as En,n as xn}from"./chunk-XSEYXS4X.js";import{a as hn,c as Ot,d as mn,e as yn}from"./chunk-464CINQK.js";import{a as at,b as oe,d as Nt,f as Dt,j as gn}from"./chunk-EQJIC52H.js";import{b as Ee}from"./chunk-TZTWXL53.js";import{B as U,C as it,D as Ge,E as Ue,y as fn}from"./chunk-H3LBNH34.js";import{r as _e,t as Le}from"./chunk-SUUBL2WC.js";import{i as pn}from"./chunk-4G52SO64.js";import{c as Ce,j as We}from"./chunk-CWBL2S3A.js";import{c as Tt}from"./chunk-X6ZYJHX4.js";import{a as I}from"./chunk-E4B7243C.js";import{a as z}from"./chunk-DSPLGTQI.js";async function Tn(H,a,x){if(!Ge(a))throw new I("INVALID_RESPONSE","A verified completed purchase is required");let T=H?We.parse(H):null;if(await x.onComplete?.(a),!T||!x.check)return;let F=We.parse(await x.check());if(F.internal_feature_id!==T.internal_feature_id||F.quantity!==T.quantity||T.observation!==void 0&&(F.observation===void 0||F.observation.requirementDigest!==T.observation.requirementDigest||F.observation.authority!==T.observation.authority||Tt(F.observation.subject)!==Tt(T.observation.subject)))throw new I("INVALID_RESPONSE","The access requirement changed");F.allowed&&await x.onAccessGranted?.(F)}function On(H){return Object.entries(H.document.buttons).filter(([,a])=>a.type==="checkout"&&a.product.type==="fixed"&&!Ee(a.product,{},H.capabilities)).map(([a])=>a)}function Nn(H,a){let x=U(a)?void 0:a.lines[0];if(!U(a)&&(a.lines.length!==1||!x))return;let T=U(a)?a.productVersionId:x.productVersionId,{screen:F,buttons:se}=H.document,M=new Map(U(a)?Object.entries(a.featureQuantities??{}):(x?.prepaid??[]).map(b=>[b.internal_feature_id,b.quantity]));function le(b,d){if(b.hidden)return!1;if(b.type==="plan_picker"&&H.capabilities.pickers[b.id]?.options.includes(T))return d[b.id]=T,!0;if(b.type==="quantity_picker"){let ne=M.get(b.internalFeatureId);return ne!==void 0&&(!b.bind?.plan||b.bind.plan===T)&&(d[b.id]=ne),!1}if(b.type==="button"&&b.action){let ne=se[b.action];return ne?.type==="checkout"&&ne.product.type==="fixed"&&ne.product.productVersionId===T}if(b.type!=="stack")return!1;let te=b.interaction,i=b.bind?.plan===T;for(let[ne,f]of b.children.entries()){let Z={},_=le(f,Z);if(te?.type==="toggle"||te?.type==="tabs"){if(!_)continue;return d[b.id]=te.type==="toggle"?ne===0:f.id,Object.assign(d,Z),!0}Object.assign(d,Z),_&&(i=!0,te?.type==="select"&&te.purpose==="product"&&te.pickerId&&f.type==="stack"&&f.bind?.plan===T&&(d[b.id]=f.id,d[te.pickerId]=T))}return i}for(let b of F.pages){let d={__page:b.id};if(le(b.root,d))return d}}var Bn="position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0";async function Pr(H,a,x){let T=a.focusAtReveal?()=>{}:Ut(H.ownerDocument),F=()=>{M.finish("dismissed"),T()},se=()=>F(),M=In(H,a,"paywall",()=>{F(),z(a.onDismiss)},kn);a.signal?.throwIfAborted(),a.signal?.addEventListener("abort",se,{once:!0});let le=null,b,d,te;try{if(M.start(!0,a.loadingDocument?.screen.strings.defaultLocale,a.loadingDocument??null),M.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(le=a.check?We.parse(await M.wait(a.check(),ot)):null,le?.allowed)return M.finish("skipped"),a.signal?.removeEventListener("abort",se),T(),await a.onAccessGranted?.(le),{check:le,host:null};let[e,t]=await Promise.allSettled([M.wait(import("./screen-renderer-IKROGLA7.js")),M.wait(a.start().then(r=>(M.cancelled&&r.destroy(),r)),ot)]);if(e.status==="rejected")throw t.status==="fulfilled"&&t.value.destroy(),e.reason;if(t.status==="rejected")throw t.reason;te=e.value,b=t.value,a.signal?.throwIfAborted(),b.signal?.throwIfAborted(),b.signal?.addEventListener("abort",se,{once:!0});let n=b.view??await M.wait(b.refresh(),ot);if(!n)throw new I("INVALID_RESPONSE","Paywall presentation is missing");b.signal?.throwIfAborted(),d=n}catch(e){throw M.finish("error",e),x?.retainedDialog?.release(),a.signal?.removeEventListener("abort",se),b?.signal?.removeEventListener("abort",se),b?.destroy(),T(),e}let i=b,{mountScreenPreview:ne}=te,f=H.ownerDocument,Z=new AbortController,_=f.createElement("section"),pe=f.createElement("div"),W=f.createElement("div"),st=a.mountControls,ee=st?f.createElement("div"):void 0,p=f.createElement("p"),y=f.createElement("button"),ce=f.createElement("button"),N=f.createElement("button");(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&x?.hostPaywallTarget&&!x.retainedDialog&&d.document.presentation.type==="modal"&&(x.retainedDialog=vn(x.hostPaywallTarget));let ue=x?.retainedDialog,A=ue?.dialog??f.createElement("dialog"),Me=ue&&d.document.presentation.type==="inline"?{type:"modal",size:"md"}:d.document.presentation,re=Me.type==="inline"?W:f.createElement("div"),lt=i.locale||d.document.screen.strings.defaultLocale,o=lt.toLowerCase().startsWith("zh"),Dn=o?"正在处理…":"Processing…",Un=o?"正在准备报价…":"Preparing your price…",D=Rn(d.document.screen.theme);_.dataset.indianaPaywall="",_.setAttribute("aria-label",d.document.name),_.style.cssText=D.root,W.style.cssText=D.controls,p.style.cssText=D.message,p.setAttribute("role","status"),N.style.cssText=D.link,N.textContent=o?"关闭":"Close",y.style.cssText=D.secondary,y.textContent=o?"重试":"Retry",y.hidden=!0,ce.type="button",ce.style.cssText=D.primary,ce.textContent=o?"继续付款":"Continue payment",ce.hidden=!0,re.append(p,ce,y),W.append(N),ee&&(ee.style.cssText="flex:1 0 100%;min-width:0",ee.hidden=!0,W.prepend(ee)),re!==W&&(re.dataset.indianaPaywallStatus="",re.style.cssText="display:none;padding:0",_.append(re)),_.append(pe,W);let ct=()=>{let e=Mn();p.style.cssText=e?`${D.message};${Bn}`:D.message,zt();let t=l=>!l.hidden&&(l!==p||!!p.textContent&&!e);if(re!==W&&(re.style.cssText=!ie&&[...re.children].some(t)?`${D.controls};padding:12px 64px 12px 20px;flex-shrink:0`:e?"padding:0":"display:none;padding:0"),ee){let l=!ee.childElementCount&&!ee.textContent?.trim();ee.hidden!==l&&(ee.hidden=l)}let n=me??W,r=![...n.children].some(t),c=[...n.children].some(l=>l!==N&&t(l));n.style.cssText=r?D.controls.replace(/padding:[^;]+/,"padding:0"):c?`${D.controls};${D.pinned}`:D.controls,dt()},Mt=typeof MutationObserver>"u"?void 0:new MutationObserver(ct);Mt?.observe(_,{attributes:!0,attributeFilter:["hidden"],characterData:!0,childList:!0,subtree:!0});let _n=Object.entries(d.document.buttons).filter(([,e])=>e.type==="close").map(([e])=>e),O,Vt,Ve=!1,$t=JSON.stringify(d.capabilities),Q;function Pe(e){let t=On(e);if(Q||fe&&!ae||B&&(C||!we()||ge))return Ae(e).map(({actionId:r})=>r);if(bt()||!C&&we())return t;let n=C?wt(e):Ct(e);return[...new Set([...t,...Ae(e).map(({actionId:r})=>r).filter(r=>!n.includes(r))])]}function $e(e){if(w)return;let t=d.id!==e.id;d=e;let n=JSON.stringify(e.capabilities);if(t||n!==$t){let r=!v&&!i.quote&&!i.operation?at(e,K,Bt):K;t||JSON.stringify(r)!==JSON.stringify(K)?(K=r,O?.update(e.document.screen,lt,{capabilities:oe(e),unavailableActions:Pe(e),serverInput:{bindings:[],answers:{}},selection:K})):O?.updateCapabilities(oe(e),Pe(e)),$t=n}Vn(e),ve(),Xe()}let L,ut=0;function Ht(){return(me??W).getBoundingClientRect().height+(re===W?0:re.getBoundingClientRect().height)}function dt(){let e=f.defaultView;if(!L?.responsive||!e)return;let t=me??W,n=e.innerHeight-(L.type==="modal"?32:0);t.style.maxHeight=`${Math.max(1,n)}px`,t.style.overflowY="auto",t.style.flexShrink="0",ut=Math.max(1,n-Ht()),O?.resizeViewport?.(ut,e.innerWidth)}let w=!1,fe=!1,v=null,pt,ze=!1,Qt=!1,he=!1,ft,ht=!1,ie,me;function Ln(){return fe||w||ie||ht?{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null}:Ot(i)}let E=()=>!w&&!ze&&!ie&&a.canInteract?.()!==!1,J,xe=!1,Re=!1,mt,h=null,de=null,Ke="",ye=()=>a.checkoutNavigation==="after_confirmation"&&!!(a.terminateCheckout||a.resumeCheckout),K={},Bt=new Set,ae,C;function yt(e){return!!e&&U(e)&&e.timing==="immediate"&&e.execution.provider==="merchant"}let gt=o?"正在确认付款…":"Confirming payment…",B=null,ge,Je,jt=!1,we=()=>a.allowNewPurchase!==!1||jt;function qt(){return JSON.stringify([d.id,d.capabilities])}function Ft(){let e=mt;return e&&e.read===a.prepareSubscriptionChange&&e.basis===qt()?e:void 0}function Xe(){let e=a.prepareSubscriptionChange;if(!e||!he||!E()||!we()||a.onPurchaseIntent||f.visibilityState==="hidden"||v||i.quote||i.operation||!Ae(d).length||Ft())return;let t=Z.signal,n=new Promise(r=>{let c=()=>r(void 0);t.addEventListener("abort",c,{once:!0}),Promise.resolve().then(()=>(t.throwIfAborted(),e(t))).then(l=>r(t.aborted?void 0:l),c).finally(()=>t.removeEventListener("abort",c))});mt={read:e,basis:qt(),result:n}}let Wt=()=>{f.visibilityState==="hidden"?mt=void 0:Xe()};f.addEventListener("visibilitychange",Wt);function Ae(e){return Object.entries(e.document.buttons).flatMap(([t,n])=>n.type==="checkout"?[{actionId:t,policy:n}]:[])}function Gt(e){let t=C?.quote;return t?Ae(e).filter(({actionId:n,policy:r})=>Se(t,e,n,r.product,K)).map(({actionId:n})=>n):[]}function wt(e){return C?.phase==="payment"?Gt(e):[]}function bt(){return(C?C.phase==="payment":!we())&&(we()||!!a.prepareUpgradeReplacement)&&ye()&&!!a.terminateCheckout&&!!i.quote&&i.canReselect===!1&&!!i.operation&&R(i.operation).type==="checkout"}function Ct(e){let t=i.quote;return!ye()||B||!t||!i.operation||R(i.operation).type!=="checkout"?[]:Ae(e).filter(({actionId:n,policy:r})=>Se(t,e,n,r.product,K)).map(({actionId:n})=>n)}function ve(){let e=Q?[]:C?wt(d):Ct(d),t=a.allowNewPurchase===!1&&!!i.operation&&R(i.operation).type==="checkout";ce.hidden=!!Q||(C?C.phase!=="payment":!t)||e.length>0,zt(e)}function Yt(){if(!(ae===void 0||Q))return p.textContent?p.textContent:C?.phase==="checking"?gt:void 0}function Mn(){return!!O?.updateCheckoutControls&&!!p.textContent&&Yt()!==void 0}let Ze;function zt(e=Q?[]:C?wt(d):Ct(d)){if(!O?.updateCheckoutControls)return;let t=Yt(),n=ye()||!!C;if(!t&&!n&&Ze?.on!==O)return;let r={actions:Ae(d).map(({actionId:l})=>l),resume:t?[ae]:n?e:[],resumeLabel:t??(o?"继续付款":C?"Continue payment":"Continue checkout"),busy:ae},c=JSON.stringify(r);Ze?.on===O&&Ze.key===c||(Ze={on:O,key:c},O.updateCheckoutControls(r))}function Kt(){de?.remove(),de=null}async function et(){if(B)return;if(a.resumeCheckout&&i.operation){let t=i.operation.operationId;try{await a.resumeCheckout(t)}catch(n){if(!(n instanceof I&&n.code==="PURCHASE_PENDING"))throw n;let r=await i.read();if(!E())return;if(r.operationId!==t||R(r).type==="checkout")throw n;await V(r,!1)}return}let e=await i.read();if(R(e).type!=="checkout")return V(e,!1);E()&&(He.delete(e.operationId),await Qe(e))}function Pt(){ge?.destroy(),ge=void 0,Je=void 0}function Jt(){let e=B;if(!e||ge)return;let t=o?"仍在核对原订单,暂时无法更换套餐。":"We’re still checking the original purchase before changing plans.",n=Date.now()+6e5,r=wn({document:f,delay:()=>Date.now()<n?5e3:void 0,async run(){if(!E())return;let c=await i.read();if(ge!==r||!E())return;if(c.operationId!==e.operationId)throw new I("PURCHASE_PENDING","The original Checkout changed");let l=R(c);l.type==="native"?(Pt(),p.textContent=o?"原订单已关闭。你可以继续更换套餐。":"The original checkout is closed. You can continue changing plans.",y.textContent=o?"继续更换套餐":"Continue changing plans",h=()=>tt(),y.hidden=!1):(l.type==="complete"||l.type==="fulfillment"||l.type==="recording")&&(Pt(),B=null,y.hidden=!0,await V(c,!1))}});ge=r,Je=async()=>{try{await r.refresh()}finally{ge===r&&(p.textContent=t,y.hidden=!1)}},h=Je,y.textContent=o?"查询结果":"Check result",y.hidden=!1,p.textContent=t,r.schedule()}async function tt(e=!1,t=!1){let n=B;if(!n)return;h=()=>tt(),C&&(y.textContent=o?"查询状态":"Check status"),y.hidden=!0;let r=async()=>{if(!we()&&a.prepareUpgradeReplacement){let l=await a.prepareUpgradeReplacement(n.operationId,n.intent);if(!E())return;jt=!0,$e(l)}B=null,C&&Te(C.quote),Kt(),v=n.selection,J=n.coupon,xe=!1,Re=!1,await qe()};if(t&&!we()&&a.prepareUpgradeReplacement)return r();let c=Date.now()+2e4;for(;E();){let l=await i.read();if(l.operationId!==n.operationId)throw new I("PURCHASE_PENDING","The original Checkout changed");if(!E())break;let s=R(l);if(s.type==="native"){await r();return}if(s.type==="complete"||s.type==="fulfillment"||s.type==="recording"){B=null,C?await ke(C.quote,l):await V(l,!1);return}if(e&&s.type==="checkout"){e=!1;try{await a.terminateCheckout(n.operationId)}catch(u){z(a.onError,u)}}if(Date.now()>=c){C&&s.type==="checkout"&&(B=null,await ke(C.quote,l));break}await Ye(1e3,f,Z.signal)}!B||w||(C?(p.textContent=o?"仍在核对原升级单,暂时无法更换套餐。":"We’re still checking the original upgrade before changing plans.",y.hidden=!1):Jt())}async function Xt(e,t,n,r){if(h=()=>Xt(e,t,n,r),await a.beforeCheckoutReplacement?.(structuredClone(r)),!E())return;let c=i.operation;if(c?.operationId!==e||R(c).type!=="checkout"){h=null,c&&await V(c,!1);return}B={operationId:e,selection:t,coupon:n,intent:r},C&&(p.textContent=o?"正在切换套餐…":"Changing plan…",y.hidden=!0);let l=!1,s=!1;try{let u=await a.terminateCheckout(e);s=(Array.isArray(u?.purchases)?u.purchases:[]).some(k=>k.operationId===e&&k.type==="native")}catch(u){if(u instanceof I&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(u.code)){B=null,C&&(h=It,y.textContent=o?"查询状态":"Check status",y.hidden=!1),p.textContent=o?"请继续原订单,或等待它过期后再更换方案。":"Continue your original checkout, or wait for it to expire before changing plans.",z(a.onError,u);return}l=u instanceof I&&(u.status??0)>=500,z(a.onError,u)}E()&&await tt(l,s)}function vt(e,t,n,r,c){let l=oe(e).checkoutCoupons?.[t],s=l?l.products[n]:a.claimCoupon&&c?pn(e.capabilities,c,r):void 0;return s?.couponId&&s.planVersionId===n?{id:s.couponId,offerId:s.offerId}:void 0}function Vn(e){fe||v||i.quote||i.operation||Ke&&p.textContent===Ke||(p.textContent=Object.values(e.capabilities.plans).some(t=>t.available)?"":o?"当前账号暂无可购买的方案。":"No plans are currently available for this account.")}let He=new Map,nt=!1;function Se(e,t,n,r,c,l){let s=U(e),u=!s&&e.lines.length===1?e.lines[0]:void 0,m=Ee(r,c,t.capabilities);if(!m||m!==(s?e.productVersionId:u?.productVersionId))return!1;let k=vt(t,n,m,c,l),q;try{q=Le(t.document.screen,m,c,t.capabilities)}catch{return!1}if(s){let X=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return Object.keys(q).length===Object.keys(e.featureQuantities??{}).length&&Object.entries(q).every(([De,St])=>e.featureQuantities?.[De]===St)&&(!k||X?.couponId===k.id&&(!k.offerId||X.grantId===k.offerId))}if((k||oe(t).checkoutCoupons?.[n])&&(k?.id??null)!==(e.discount?.couponId??null))return!1;let G=Object.fromEntries((u?.prepaid??[]).map(X=>[X.internal_feature_id,X.quantity]));return[...new Set([...Object.keys(q),...Object.keys(G)])].every(X=>(q[X]??0)===(G[X]??0))}let R=e=>hn({quote:i.quote,operation:e,requestId:null,pending:!1,destroyed:w,canReselect:i.canReselect});async function Qe(e){let t=e.merchantExecution,n=R(e),r=n.type==="checkout"?n.checkoutUrl:e.checkoutUrl;if(!(!E()||!r||it(e)&&n.type!=="checkout"||a.checkoutNavigation==="after_confirmation"&&n.type!=="checkout"||t?.type==="purchase"&&!["not_started","pending"].includes(t.paymentStatus)||He.get(e.operationId)===r)){He.set(e.operationId,r);try{a.onCheckoutUrl?await a.onCheckoutUrl(r):f.defaultView?.location.assign(r)}catch(c){throw He.delete(e.operationId),c}}}let be=(e,t=!1)=>{if(e instanceof Nt)h=null,p.textContent=e.customerMessage(o);else if(An(e))h=null,p.textContent=t?o?"当前无法在此购买,付款尚未开始。请联系商户。":"Purchases aren’t available here right now. Payment hasn’t started. Contact the merchant for help.":Lt(e,o);else if(t){let n=e instanceof I?e.code:void 0;n==="CAPABILITY_UNAVAILABLE"||n==="NOT_CONFIGURED"?(h=null,p.textContent=o?"暂时无法为此套餐报价,付款尚未开始。":"Pricing for this plan is unavailable. Payment hasn’t started."):i.canReselect===!0&&!v?p.textContent=o?"未能取得报价,付款尚未开始。请重新选择套餐。":"We couldn’t prepare your price. Payment hasn’t started. Choose a plan again.":n==="COMMAND_PENDING"?p.textContent=o?"仍在准备报价,请重试以查看结果。":"Your price is still being prepared. Retry to check the result.":p.textContent=o?"未能取得报价,付款尚未开始。请重试。":"We couldn’t prepare your price. Payment hasn’t started. Try again."}else p.textContent=e instanceof I&&(e.code==="NETWORK_ERROR"||e.code==="TIMEOUT")?Lt(e,o):e instanceof I?e.message:o?"操作未完成,请重试。":"This action couldn’t be completed. Try again.";y.hidden=h===null,Ke=p.textContent,t&&ae===void 0&&!L?.responsive&&p.scrollIntoView?.({block:"nearest"}),z(t&&x?.quoteError?x.quoteError:a.onError,e)},Be=new WeakMap;function je(e){fe=e,y.disabled=e,ce.disabled=e,O?.updateCapabilities?.(oe(d),Pe(d));for(let t of de?.querySelectorAll("button")??[])e?(Be.has(t)||Be.set(t,t.disabled),t.disabled=!0):Be.has(t)&&(t.disabled=Be.get(t),Be.delete(t)),_t(t)}function Zt(){Q&&(p.textContent=Q.message,y.textContent=o?"重试":"Retry",y.disabled=!1,y.hidden=!Q.retry,ce.disabled=!0)}function kt(){p.textContent=o?"暂时无法操作,请稍后重试。":"This action is unavailable right now. Try again in a moment."}async function $n(e){if(a.beforeAction)try{await a.beforeAction()}catch(t){throw t instanceof Nt?(v=null,xe=!1,Re=!1,h=null):h=e,t}}async function j(e,t){if(fe||w||Q)return;if(!E()){kt();return}let n=e===qe,r=n?Un:Dn;ae=t!==void 0&&O?.updateCheckoutControls?t:void 0,p.textContent=r,je(!0),ve(),y.hidden=!0;try{if(e!==on&&e!==It&&e!==Et&&e!==Je&&(e!==et||!a.resumeCheckout)&&await $n(e),w||Q)return;if(!E()){h=e,y.hidden=!1,kt();return}await e()}catch(c){w||be(c,n)}finally{ae=void 0,je(!1),ve(),Q?Zt():p.textContent===r&&(p.textContent="")}}async function en(e){await Tn(le,e,a)}function Te(e,t){C=t?{quote:e,phase:t}:void 0,t==="checking"?(ae??=v?.actionId??Gt(d)[0],p.textContent=gt,h=It,y.textContent=o?"查询状态":"Check status",y.hidden=!0):ae=void 0,O?.updateCapabilities(oe(d),Pe(d)),ve()}function tn(e){return e instanceof I&&(e.code==="COMMAND_PENDING"||e.reason==="RESULT_UNKNOWN"||e.code==="NETWORK_ERROR"||e.code==="TIMEOUT"||e.status===429||(e.status??0)>=500)}function nn(e,t){Dt(e,{...t,featureQuantities:t.featureQuantities??{}},"Purchase operation changed")}async function It(){C&&await ke(C.quote)}async function ke(e,t){Te(e,"checking"),Ke="";let n=1e3;Ve=!0,z(a.onObservationChange,!0);try{for(let r=t;E();r=void 0){if(!r){try{r=await i.read()}catch(c){if(!tn(c))throw c}if(!E())return}if(r){nn(r,e);let c=R(r);if(c.type==="checkout"){Te(e,"payment"),p.textContent=o?"请先完成原订单的付款。":"Finish paying for this upgrade.",y.hidden=!1;return}if(c.type==="complete"){Te(e,"complete"),h=null;let l=d.capabilities.plans[e.productVersionId]?.name,s=e.merchantTerms?.subscriptionTerms?.items,u=s?.length===1?s[0].interval:void 0,m=u==="year"?o?"年付":"annual billing":u==="month"?o?"月付":"monthly billing":null;p.textContent=l?o?`已升级到 ${l}${m?" "+m:""}。`:`Upgraded to ${l}${m?" ("+m+")":""}.`:o?"已成功升级。":"Plan upgraded.",await en(r);return}if(c.type==="native"&&!Ue(r)){Te(e),v=null,h=null,p.textContent=o?"付款没有成功,套餐未变更。请检查付款方式后重新选择套餐。":"Your payment didn’t go through, so your plan is unchanged. Check your payment method, then choose a plan again.",y.textContent=o?"重试":"Retry";return}if(r.problem&&!["RESULT_UNKNOWN","STATE_CHANGED"].includes(r.problem.reason??""))throw new I(r.problem.code,o?"暂时无法完成升级。":"The upgrade needs attention.",void 0,void 0,r.problem)}await Ye(n,f,Z.signal),n=Math.min(n*1.5,15e3)}}finally{Ve=!1,z(a.onObservationChange,!1)}}async function Et(){let e=C?.quote;if(!e)return;let t=await i.read();if(nn(t,e),R(t).type!=="checkout")return ke(e,t);if(a.resumeCheckout){await a.resumeCheckout(t.operationId);return}He.delete(t.operationId),await Qe(t)}function rn(e){return Ot(i).type==="recording"||R(e).type==="recording"}function an(e){let t=e.merchantTerms,n=t?.subscriptionTerms?.items??[],r=t?t.totalMinor:U(e)?e.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),c=t?n.length===1&&n[0]?.amountMinor===r&&n[0]:!U(e)&&e.lines.length===1&&e.lines[0]?.catalogAmountMinor===r&&e.lines[0],l=r===null?Ce(t.subtotalMinor-t.discountMinor,e.currency)+(o?" + 待确认税费":" + tax confirmed at checkout"):Ce(r,e.currency)+(c?_e(c.interval,o?"zh-CN":"en",c.intervalCount??1):""),s=U(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(u=>u.productName).join(", ");return{label:s?`${s} · ${l}`:l,recurring:c}}async function V(e,t=a.checkoutNavigation!=="after_confirmation"){if(w)return;if(!E()){h=async()=>V(await i.read()),y.hidden=!1;return}let n=e.quote??i.quote;if(yt(n)&&(e.confirmedAt||e.merchantExecution))return ke(n,e);if(p.textContent=Sn(e.status,o),rn(e)){let m=e.merchantExecution?.recordingStatus==="failed";p.textContent=m?o?"付款和商户处理已完成,但交易记录失败。请联系商户修复,勿重复购买。":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":o?"付款和商户处理已完成,正在确认交易记录。请勿重复购买。":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",y.textContent=o?"查询记录":"Check recording",h=async()=>V(await i.read()),y.hidden=!1;return}if(e.problem&&R(e).type!=="native"){let m=e.problem;h=Oe,y.textContent=o?"检查并恢复原操作":"Check and recover original purchase",be(new I(m.code,m.reason==="RESULT_UNKNOWN"?o?"付款结果尚未确定,请恢复原操作,暂勿重复购买。":"The payment result is unknown. Recover the original purchase before buying again.":m.phase==="fulfillment"?o?"付款已记录,商户权益处理需要核对。":"Payment was recorded. Access fulfillment needs attention.":m.code==="CAPABILITY_UNAVAILABLE"?o?"商户尚不支持本次购买所需的完整能力,请处理后恢复原操作。":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":m.code==="NOT_CONFIGURED"?o?"付款服务连接需要处理,请联系商户后恢复原操作。":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":o?"原购买操作需要处理,请查询或恢复此操作。":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,m));return}if((e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"||e.merchantExecution?.type==="subscription_change"&&e.merchantExecution.status==="applied")&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(p.textContent=o?"付款已记录,正在等待商户完成处理。":"Payment was recorded. Waiting for merchant fulfillment."),Ge(e)&&R(e).type==="complete"){h=null,await en(e);return}if(!Ue(e)&&R(e).type!=="fulfillment"){if(i.canReselect===!1){p.textContent=o?"正在核对原购买结果":"Checking the original purchase result",y.textContent=o?"查询结果":"Check result",h=async()=>V(await i.read()),y.hidden=!1;return}e.status==="cancelled"?p.textContent=o?"这笔购买已取消,可以重新选择方案。":"This purchase was cancelled. Choose a plan to start again.":e.status==="failed"&&(p.textContent=o?"这笔购买未能完成,可以重新选择方案。":"This purchase didn’t go through. Choose a plan to try again."),y.textContent=o?"重试":"Retry",h=null,v=null;return}if(!t&&R(e).type==="checkout"){if(B){Jt();return}if(ye()){p.textContent="",nt=!1,h=null,y.hidden=!0,O?.updateCapabilities?.(oe(d),Pe(d)),ve();return}let m=i.quote,k=m?.operationId===e.operationId?an(m).label:"";p.textContent=nt?k?o?`${k} 尚未付款。再次选择该方案即可继续付款。`:`${k} is still unpaid. Choose it again to continue paying.`:o?"之前的购买尚未付款。再次选择该方案即可继续付款。":"Your earlier purchase is still unpaid. Choose that plan again to continue paying.":"",nt=!1,h=null;return}await Qe(e);let r=Date.now(),c=r+6e5,l=2e3,s=R(e).type!=="checkout",u=()=>s&&Date.now()-r<15e3;Ve=!0,z(a.onObservationChange,!0);try{for(;!w&&Date.now()<c;){if(await Ye(u()?700:l,f,Z.signal),w)return;if(!E()){h=async()=>V(await i.read()),y.hidden=!1;return}let m=await i.read();if(R(m).type==="checkout"&&(s=!1),!t&&R(m).type==="checkout"){await V(m,!1);return}if(!m.problem&&Ue(m)&&await Qe(m),!Ue(m)||m.problem||rn(m)){await V(m);return}u()||(l=Math.min(l*1.5,3e4))}}finally{Ve=!1,z(a.onObservationChange,!1)}h=async()=>V(await i.read()),y.hidden=!1}async function xt(e=!1){let t=await i.read();if(w)return;if(!E()){h=()=>xt(e),y.hidden=!1;return}let n=i.quote;if(n&&Dt(t,{operationId:n.operationId,currency:n.currency},"The original purchase operation changed"),n&&(it(t)?["prepared","quoted"].includes(t.status):t.status==="pending")&&(it(t)||t.quoteFinalized===!1)&&!t.confirmedAt&&!t.checkoutUrl&&!("nativePurchase"in t&&t.nativePurchase)&&!t.merchantExecution&&!t.problem&&!i.pendingCancellation){if(a.purchaseConfirmation!=="paywall"){e?await Oe():h=null;return}setTimeout(sn,0,n);return}await V(t,e||void 0)}async function on(){await xt()}async function Hn(e){p.textContent=gt;let t=Date.now()+12e3;for(;!w&&Date.now()<t&&(await Ye(1500,f,Z.signal),!(w||!E()));){let n;try{n=await i.read()}catch{break}if(n.problem?.reason!=="RESULT_UNKNOWN")return n}return e}async function Oe(){if(i.quote&&!(Date.parse(i.quote.expiresAt)>Date.now()))throw new I("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");Kt();let e=i.quote;if(yt(e)){Te(e,"checking");let n;try{n=await i.confirm()}catch(r){if(!tn(r))throw r;return ke(e)}return ke(e,n)}h=Oe;let t=await i.confirm();if(!E()){h=Oe,y.hidden=!1;return}if(t.problem?.reason==="RESULT_UNKNOWN"&&(t=await Hn(t)),t.problem){await V(t);return}if(Ue(t)){if(R(t).type==="checkout")await Qe(t);else if(t.execution&&t.execution.provider!=="merchant"||"nativePurchase"in t&&t.nativePurchase){if(!a.onPurchase)throw new I("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await a.onPurchase({operation:t,signal:Z.signal})}}h=async()=>V(await i.read()),await V(t,!0)}function sn(e){if(w)return;de?.remove();let t=!(Date.parse(e.expiresAt)>Date.now());p.textContent=t?o?"此报价已过期。请先取消,再重新选择。":"This quote has expired. Cancel it, then choose again.":"";let n=f.createElement("div"),r=f.createElement("button"),c=f.createElement("button"),l=f.createElement("div"),s=f.createElement("p"),u=e.merchantTerms,m=o?"zh-CN":"en",k=u?.subscriptionTerms?.items??[],q=u?u.subscriptionTerms?.trial?.days:U(e)?void 0:e.lines.find(g=>g.trial)?.trial?.days,G=U(e)?u?u.totalMinor:e.totalMinor:q===void 0?null:u?u.totalMinor:e.charge?e.charge.totalMinor:e.lines.every(g=>g.trial)?0:null,Ne=(g,P)=>o?`${P} 天试用结束后 ${g}`:`Then ${g} after the ${P}-day trial`,{label:X,recurring:De}=an(e),St=U(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(g=>g.productName).join(", "),un=G===null?"":`${o?"今天应付":"Due today"} ${Ce(G,e.currency)}`;s.textContent=un?[St,un].filter(Boolean).join(" · "):X,r.textContent=U(e)?o?"确认变更":"Confirm change":o?"确认购买":"Confirm purchase",r.disabled=t,c.textContent=o?"取消":"Cancel",n.style.cssText=D.panel,s.style.cssText=D.summary,l.style.cssText=D.actions,r.style.cssText=D.primary,c.style.cssText=D.secondary,_t(r),r.onclick=()=>{j(Oe)};let dn=async()=>{let g=await i.cancel();w||(n.remove(),de=null,await V(g))};c.onclick=()=>{h=dn,j(dn)};let Y=f.createElement("div");if(Y.style.cssText=D.terms,U(e)){for(let[P,S]of Object.entries(e.featureQuantities??{})){let $=i.view?.capabilities.plans[e.productVersionId]?.prepaid?.find(Qn=>Qn.internalFeatureId===P),rt=f.createElement("p");rt.textContent=`${$?.name??P} · ${S} ${o?"份":"packs"}${$?` × ${$.terms.units}`:""}`,Y.append(rt)}for(let[P,S]of[[o?"原订阅抵扣":"Unused subscription credit",e.creditMinor],[o?"新套餐费用":"New plan charge",e.debitMinor],[o?"优惠减免":"Offer savings",u?.discountMinor??e.discountMinor],[o?"税费":"Tax",u?u.taxMinor:e.taxMinor]]){let $=f.createElement("p");$.textContent=`${P}: ${S===null?o?"结账时确认":"Confirmed at checkout":Ce(S,e.currency)}`,Y.append($)}let g=f.createElement("p");g.textContent=`${o?"生效时间":"Effective"}: ${e.effectiveAt}`,Y.append(g)}if(u){for(let P of k){if(G===null&&P===De)continue;let S=f.createElement("p"),$=Ce(P.amountMinor,e.currency)+_e(P.interval,m,P.intervalCount);S.textContent=G!==null&&q!==void 0?Ne($,q):$,P.amountAfterOfferMinor!==void 0&&(S.textContent+=` · ${o?"优惠结束后":"After the offer"} ${Ce(P.amountAfterOfferMinor,e.currency)}${_e(P.interval,m,P.intervalCount)}`),Y.append(S)}let g=u.subscriptionTerms?.trial;if(g){let P=f.createElement("p");P.textContent=o?`试用 ${g.days} 天;${g.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${g.days}; ${g.cardRequired?"a payment method is required":"no payment method is required"}`,Y.append(P)}for(let P of[...u.expectedEffects.map(S=>S.description),...u.requiredConsents.map(S=>S.summary)]){let S=f.createElement("p");S.textContent=P,Y.append(S)}}else if(!U(e)){for(let g of e.lines){if(G!==null||g!==De){let P=f.createElement("p"),S=`${Ce(g.catalogAmountMinor,e.currency)}${_e(g.interval,m,g.intervalCount??1)}`;P.textContent=G!==null&&g.trial?(e.lines.length>1?`${g.productName} · `:"")+Ne(S,g.trial.days):`${g.productName} · ${S}`,Y.append(P)}for(let P of g.prepaid??[]){let S=f.createElement("p"),$=i.view?.capabilities.plans[g.productVersionId]?.prepaid?.find(rt=>rt.internalFeatureId===P.internal_feature_id);S.textContent=`${$?.name??P.internal_feature_id} · ${P.quantity} ${o?"份":"packs"} × ${P.terms.units}`,$&&(S.textContent+=_e($.reset==="week"||$.reset==="month"||$.reset==="year"?$.reset:"one_time",m,$.resetCount)),Y.append(S)}if(g.trial){let P=f.createElement("p");P.textContent=o?`试用 ${g.trial.days} 天;${g.trial.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${g.trial.days}; ${g.trial.cardRequired?"a payment method is required":"no payment method is required"}`,Y.append(P)}}if(!e.charge){let g=f.createElement("p");g.textContent=o?"目录价格;最终金额以结账时税费和试用规则为准。":"Catalog price; the final charge depends on checkout taxes and trial terms.",Y.append(g)}}for(let g of Y.children)g.style.margin="0";l.append(r,c),n.append(s,...Y.childElementCount?[Y]:[],l),W.prepend(n),L?.responsive||n.scrollIntoView?.({block:"nearest"}),r.focus({preventScroll:!0}),de=n,fe&&je(!0),h=null}async function qe(){if(!v)return;if(h=qe,!xe){let n=i.view,r=n?.document.buttons[v.actionId],c=n&&r?.type==="checkout"?Ee(r.product,v.selection,n.capabilities):null;if(!n||!c)throw new I("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");if(!Re){let s=Ft(),u=s?await s.result:void 0;if(w)return;let m=a.resolveSubscriptionChange;if(m||u){let k={actionId:v.actionId,productVersionId:c,featureQuantities:Le(n.document.screen,c,v.selection,n.capabilities)},q=u?[async()=>u(k)]:[],G=m?await m(k,...q):await q[0]?.();if(w)return;G!==void 0&&(v.subscriptionChange=fn.parse(G))}Re=!0}let l=J?.offerId;if(J&&!l){if(!a.claimCoupon)throw new I("CAPABILITY_UNAVAILABLE","Coupon claiming is unavailable");let{offer:s}=await a.claimCoupon(J.id,v.requestId);if(w)return;if(!s||s.couponId!==J.id||s.status!=="issued"||!(Date.parse(s.expiresAt)>Date.now()))throw v=null,J=void 0,h=async()=>{$e(await i.refresh()),h=null},new I("COUPON_UNAVAILABLE","This Coupon is no longer available for this purchase");l=s.id}if(!J&&!n.document.screen.actions.some(s=>s.id===v?.actionId&&typeof s.properties.couponBinding=="string")&&(l=await a.resolveOfferId?.({actionId:v.actionId,productVersionId:c,featureQuantities:Le(n.document.screen,c,v.selection,n.capabilities)})),w)return;l!==void 0&&(v.offerId=l),xe=!0}if(!E()){y.hidden=!1;return}let e;try{e=await i.preview(v)}catch(n){throw i.canReselect===!0&&(v=null,xe=!1,Re=!1,J=void 0,h=null),n}if(J&&(U(e)?(()=>{let n=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return n?.couponId!==J.id||n.grantId!==v.offerId})():e.discount?.couponId!==J.id||e.discount.offerId!==v.offerId))throw new I("INVALID_RESPONSE","The quote did not apply the Coupon selected on this Paywall");if(w)return;let t=e.merchantTerms;if(a.purchaseConfirmation!=="paywall"||a.confirmOnHostedCheckout&&E()&&!U(e)&&e.provider==="merchant"&&e.billingSubscriptionId===null&&t?.request.action==="purchase"&&t.request.mode==="subscription"&&t.subscriptionTerms?.trial===null&&t.requiredConsents.length===0&&Date.parse(e.expiresAt)>Date.now()){if(!E()){y.hidden=!1;return}if(!(Date.parse(e.expiresAt)>Date.now()))throw new I("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");let n=ae?"":o?"正在打开收银台…":"Opening checkout…";p.textContent=n;try{await Oe()}catch(r){w||be(r)}finally{p.textContent===n&&(p.textContent="")}return}sn(e)}function Ie(e="destroy",t=!1){if(w)return;w=!0;let n=pt;pt=void 0,z(n),a.signal?.removeEventListener("abort",se),i.signal?.removeEventListener("abort",se),M.finish("dismissed"),Vt?.(),Pt(),f.removeEventListener("visibilitychange",Wt),Z.abort(),Mt?.disconnect(),O?.destroy(),i.destroy(),A.removeEventListener("cancel",cn),N.remove(),_.remove(),t||ln(),e==="dismiss"&&z(a.onDismiss)}function ln(){if(L?.destroy(),ue){ue.release();return}A.open&&A.close(),A.remove(),T()}F=Ie;async function Fe(){if(!he||w||ze||ie==="closing"||!ie&&!E())return;if(!x){Ie("dismiss");return}let e=f.createElement("p");e.setAttribute("role","status"),e.textContent=o?"正在关闭…":"Closing…",me||(me=f.createElement("div"),me.style.cssText=W.style.cssText,W.replaceWith(me),pe.inert=!0),N.hidden=!1,me.replaceChildren(e,N),ie="closing",N.setAttribute("aria-disabled","true"),N.focus({preventScroll:!0});try{await x.dismiss()}catch(t){w||z(a.onError,t)}w||(ie="retry",e.textContent=o?"未能确认关闭,请重试。":"Could not confirm closure. Try again.",N.textContent=o?"重试关闭":"Retry closing",N.removeAttribute("aria-label"),N.removeAttribute("aria-disabled"))}N.onclick=()=>{Fe()};function cn(e){e.preventDefault(),Fe()}A.addEventListener("cancel",cn),ce.onclick=()=>{j(C?Et:et)},y.onclick=()=>{if(Q){Q.retry?.();return}h&&j(h)};function Rt(e){M.finish("error",e),Ie()}function At(){if(!(!Qt||he||w||ze||L&&!E()))try{let e=t=>{a.focusAtReveal&&(T=Ut(f)),a.settleMotionAtReveal?O?.setHidden?.(!1,!0):O?.setHidden?.(!1),ft?.(),L&&(A.open||A.showModal(),L.responsive&&A.focus({preventScroll:!0}),!t&&a.loading!=="host"&&Cn(A,L.type,L.responsive)),t&&a.loading!=="host"&&typeof pe.animate=="function"&&!f.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&pe.animate([{opacity:.55},{opacity:1}],{duration:160,easing:"ease-out"}),he=!0,Xe()};x?x.present(t=>M.present(n=>e(t??n))):M.present(e)}catch(e){Rt(e),be(e)}}try{if(Me.type==="inline"?(ct(),ft=xn(_,H),H.append(_)):(A.setAttribute("aria-label",d.document.name),N.textContent="×",N.setAttribute("aria-label",o?"关闭":"Close"),Pn(N,d.document.screen.theme),N.hidden=gn(d.document),(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&ue?.content?ue.content.append(N,_):A.replaceChildren(N,_),ue||H.append(A),L=bn(A,{...d.document.screen,presentation:Me},dt),L.latch(),L.responsive&&(_.style.display="flex",_.style.flexDirection="column",_.style.maxHeight="100%",pe.style.overflow="clip",pe.style.minHeight="0"),ue||(ft=En(A))),st&&ee){let n=st(ee);if(typeof n=="function"&&(w?z(n):pt=n),w)throw new DOMException("Presentation cancelled","AbortError");ct()}O=ne(pe,{mode:"live",rendererUrl:"bundled",title:d.document.name,closeActions:_n,onAuthoredClose(n){ie||w||(N.hidden=n)},hostPresentation:()=>L?.type??Me.type,reportContentHeight:L?.responsive,onResize:n=>{if(!L?.responsive)return;let r=Math.min(n,ut);pe.style.height=`${r}px`,L.setContentHeight(r+Ht())},onSelection(n){for(let[r,c]of Object.entries(n))typeof c=="number"&&typeof K[r]=="number"&&K[r]!==c&&Bt.add(r);K=n,ve(),Xe()},onAction(n,r={},c,l){if(!he||w||ie)return;let s=i.view,u=s?.document.buttons[n];if(!u)return;if(Q){u.type==="close"&&Fe();return}if(u.type==="close"&&x&&a.resumeCheckout&&i.operation&&mn(R(i.operation))){Fe();return}if(fe)return;if(!E()){kt();return}if(u.type==="close"){j(async()=>{x?.closeAction?await x.closeAction(n):await a.onAction?.(n),Ie(a.onAction?"action":"dismiss")});return}if(u.type==="action"){h=async()=>{if(u.action.type==="event"){if(!a.onEvent)throw new I("EVENT_HANDLER_REQUIRED","Provide the event handler");await a.onEvent(u.action.event)}else a.onOpenUrl?await a.onOpenUrl(u.action.url):f.defaultView?.location.assign(u.action.url);await a.onAction?.(n),h=null},j(h);return}if(ye()&&B){!ge&&B.selection.actionId===n&&j(()=>tt(!0),n);return}if(C){if(C.phase==="payment"&&s&&Se(C.quote,s,n,u.product,r,l)){j(Et,n);return}if(!bt())return}if(!we()&&!bt()){ye()&&s&&i.quote&&i.operation&&R(i.operation).type==="checkout"&&Se(i.quote,s,n,u.product,r,l)?j(et,n):p.textContent=o?"当前只能继续原订单。":"Only your original checkout is available.";return}if(de&&i.canReselect===!1){p.textContent=o?"请先确认或取消当前购买。":"Confirm or cancel the current purchase first.",L?.responsive||de.scrollIntoView?.({block:"nearest"}),de.querySelector("button")?.focus({preventScroll:!0});return}if(ye()&&a.terminateCheckout&&s&&i.quote&&i.operation&&i.canReselect===!1&&R(i.operation).type==="checkout"){if(Se(i.quote,s,n,u.product,r,l)){j(et,n);return}let k=Ee(u.product,r,s.capabilities),q;try{if(!k)throw new I("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");q=Le(s.document.screen,k,r,s.capabilities)}catch(De){be(De);return}let G=i.operation.operationId,Ne={actionId:n,requestId:crypto.randomUUID(),selection:structuredClone(r)},X=vt(s,n,k,r,l);j(()=>Xt(G,Ne,X,{actionId:n,productVersionId:k,selection:Ne.selection,featureQuantities:q}),n);return}if((i.quote||v)&&i.canReselect===!1){let k=!!s&&!!i.quote&&Se(i.quote,s,n,u.product,r,l);nt=!!i.quote&&!k,h=i.quote?()=>xt(k):qe,j(h,n);return}let m=s&&Ee(u.product,r,s.capabilities);if(!s||!m){be(new I("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(a.onPurchaseIntent){h=null,j(async()=>{let k={actionId:n,productVersionId:m,selection:structuredClone(r),featureQuantities:Le(s.document.screen,m,r,s.capabilities)};ht=!0,await a.onPurchaseIntent(k)},n);return}if(v&&v.actionId!==n){be(new I("COMMAND_PENDING","Finish the current purchase"));return}v||(J=vt(s,n,m,r,l),v={requestId:crypto.randomUUID(),actionId:n,selection:structuredClone(r)},xe=!1,Re=!1),j(qe,n)},onEscape:()=>{Fe()},onError:n=>{let r=new Error(n);!he&&!w&&Rt(r),be(r)},onRendered:n=>{n&&A.setAttribute("aria-label",n),Qt=!0,At()}}),O.setHidden?.(!0),dt();let e=ye()&&!!i.quote&&!!i.operation&&R(i.operation).type==="checkout";K=i.quote?Nn(d,i.quote)??at(d,{}):at(d,{}),O.update(d.document.screen,lt,{capabilities:oe(d),unavailableActions:Pe(d),serverInput:{bindings:[],answers:{}},...Object.keys(K).length?{selection:K}:{}}),Vt=i.subscribe?.($e),$e(i.view??d),await M.wait(O.ready);let t=i.operation;(!e||yt(i.quote))&&(i.quote||t&&(t.confirmedAt||t.checkoutUrl||Ge(t)))&&(h=on,j(h))}catch(e){throw Rt(e),e}return{check:le,host:{get currentResolution(){return d},setPurchaseRecovery(e,t){Q={message:e,retry:t},O?.updateCapabilities?.(oe(d),Pe(d)),ve(),Zt()},get subscriptionUpgradeActive(){return C!==void 0},get observing(){return Ve},get recovery(){return Ln()},async prepareFallback(){if(fe||w||ie||ht)return{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null};je(!0);try{let e=await yn(i);return e.type==="native"&&Ie(),e}finally{je(!1)}},setSuspended(e){ze=e,_.hidden=e,e&&A.open?A.close():!e&&!he?At():!e&&!w&&he&&Me.type!=="inline"&&!A.open&&A.showModal()},destroy:Ie,retainPurchaseDialog(){if(!(w||!A.open||!A.isConnected))return Ie("destroy",!0),{dialog:A,content:ue?.content,release:ln}},refresh:async()=>{if(!E()){if(i.view)return i.view;throw new I("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await i.refresh();return $e(e),At(),e}}}}export{Pr as a};
|