@tinkerlandai/longplay-sdk 0.10.22 → 0.10.23
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 +5 -0
- package/dist/{chunk-NO5GW7GX.js → chunk-3J24TUO7.js} +1 -1
- package/dist/{chunk-77ZUEWYE.js → chunk-7MF2YMN4.js} +1 -1
- package/dist/{chunk-HK3UIQ4O.js → chunk-DUZ2E7BK.js} +1 -1
- package/dist/{chunk-CM75TDWK.js → chunk-EZLLTGV3.js} +1 -1
- package/dist/chunk-IIYIIXNB.js +1 -0
- package/dist/{chunk-KSCITFNQ.js → chunk-KRQESEG2.js} +1 -1
- package/dist/{chunk-HCI6E3R7.js → chunk-KZ63ANBP.js} +1 -1
- package/dist/{chunk-GQ7B25L5.js → chunk-PKLLZXNM.js} +1 -1
- package/dist/{chunk-O5XTOWFZ.js → chunk-WMIDEJTZ.js} +1 -1
- package/dist/{chunk-KLP5TN5O.js → chunk-XFO4FBFG.js} +1 -1
- package/dist/{content-RWD3AGMM.js → content-FM52HLRX.js} +1 -1
- package/dist/funnel-runtime-host-MZKLVLC4.js +1 -0
- 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-JL4SXFXT.js +1 -0
- 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-RNOB7OYB.js +0 -1
- package/dist/funnel-runtime-host-MRP53J2I.js +0 -1
- package/dist/paywall-5Q4VATYY.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.23
|
|
4
|
+
|
|
5
|
+
- JavaScript, React Native, iOS and Android no longer reopen a merchant Checkout after payment has succeeded or when payment is not required while fulfillment is still pending. They continue observing the original purchase until its result is accepted.
|
|
6
|
+
- Show quote preparation and recoverable quote failures inside the Paywall, keep the original error callback and retry, and avoid turning a quote failure into a Funnel presentation failure. An unavailable or unconfigured capability does not offer a futile retry. Wire protocol remains `0.10`.
|
|
7
|
+
|
|
3
8
|
## 0.10.22
|
|
4
9
|
|
|
5
10
|
- Read merchant subscription changes with the original `sourceLineItems` in the quote and execution authority. Historical operations can omit the field.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as p,b as ne,c as j,d as re,n as B,q as ie}from"./chunk-O5XTOWFZ.js";import{b as te}from"./chunk-KLP5TN5O.js";import{a as o}from"./chunk-QVGTHPWT.js";import{Da as u,Fa as G,Qa as ee,_ as $,a as K,b as Q,c as W,d as M,e as H,f as X,ia as Z,q as L}from"./chunk-KSCITFNQ.js";import{a as J}from"./chunk-DSPLGTQI.js";import{a as Y}from"./chunk-HDVLCRC6.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new o("INVALID_STATE","Installation sequence exhausted");return t+1},ve=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 F(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 o("INVALID_STATE","Installation journal is invalid");return e({...n})})}function se(t,e,n){let r=null,s=0,a=0,l=0,y=Promise.resolve(),w=!1;if(t&&(!n||Y.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new o("SCOPE_MISMATCH","Push installation belongs to another scope");let f=()=>{if(w)throw new o("CLOSED","SDK client was destroyed");if(!t)throw new o("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==s)throw new o("IDENTITY_CHANGED","Identity changed during Push operation")};async function D(i){let c=f();if(!c.sha256&&!globalThis.crypto?.subtle)throw new o("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let d=c.sha256?await c.sha256(Uint8Array.from(i,E=>E.charCodeAt(0))):await ve(i);if(!/^[a-f0-9]{64}$/.test(d))throw new o("INVALID_STATE","Push credential digest is invalid");return d}function m(i){let c=H.parse(i);if(c.installationId.toLowerCase()!==f().installationId.toLowerCase())throw new o("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let d=f(),E={installationId:d.installationId,publicKey:d.publicKey,issuedAt:new Date().toISOString(),...c},C=await d.sign(X(i,d.scope,E));return{...E,signature:C}}let I=(i,c,d)=>e.requestWithCredential?e.requestWithCredential(i,c,d):e.request(i,c);async function q(){let i=f(),c=s,d=r?await(e.session?.access()??r):null,E=F(i,g=>g),C;if(E.detachSeq!==null){let g=E.detachSeq,x=K.parse(await S("detach",{sequence:g,platform:i.platform}));try{let N=await e.request("push/installations/detach",{...i.scope,...x},"POST",{installationDetach:!0});if(!N||typeof N!="object"||!("installation"in N))throw new o("INVALID_RESPONSE","Push detach acknowledgement is invalid");let _=m(N.installation);if(_.bound||_.identitySeq!==g)throw new o("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(N){if(N instanceof o&&N.status===404)C=N;else if(!(N instanceof o)||N.status!==412)throw N}C||F(i,N=>({...N,detachSeq:N.detachSeq===g?null:N.detachSeq}))}if(O(c),!d){if(C)throw C;return null}let A=u.bindPushInstallation,k=A.request.parse(await S("bind",{sequence:l,platform:i.platform,credentialDigest:await D(d)}));O(c);let T=A.response.parse(await I(A.path,k,d));O(c);let R=m(T.installation);if(!R.bound||R.identitySeq!==l)throw new o("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return C&&E.detachSeq!==null&&l>E.detachSeq&&F(i,g=>({...g,detachSeq:g.detachSeq===E.detachSeq?null:g.detachSeq})),R}async function h(){f();let i=s,c=r?await(e.session?.access()??r):null;if(!c)throw new o("NOT_IDENTIFIED","Identify before reading this installation");let d=u.readPushInstallation,E=d.request.parse(await S("read",{credentialDigest:await D(c)}));O(i);let C=d.response.parse(await I(d.path,E,c));return O(i),m(C.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(d=>{try{t?.onError?.(d instanceof Error?d:new Error("Push synchronization failed"))}catch{}}),c}async function v(i,c,d){let E=f(),C=c.identity,A=c.observation,k=r?await(e.session?.access()??r):null;if(O(C),A!==a)throw new o("INVALID_STATE","Push observation changed during recovery");if(!k)throw new o("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new o("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(C),await q(),O(C),A!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let T=F(E,_=>d?_:{..._,addressSeq:U(_.addressSeq)}),g=await S(d?"recovery_confirm":"recovery_request",{...i,sequence:T.addressSeq,credentialDigest:await D(k),...d?{challenge:d}:{}}),x=d?W.parse(g):Q.parse(g);if(O(C),A!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let N=await I(`push/installations/recovery/${d?"confirm":"request"}`,x,k);if(O(C),A!==a||F(E,_=>_).addressSeq!==T.addressSeq)throw new o("INVALID_STATE","Push observation changed during recovery");if(d){let _=u.updatePushAddress.response.parse(N),V=m(_.installation);if(!V.bound||V.identitySeq!==l||V.addressSeq!==T.addressSeq||V.connectionId!==i.connectionId||V.addressStatus!=="active")throw new o("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return V}if(!N||typeof N!="object"||!("recovery"in N))throw new o("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return M.parse(N.recovery)})}return{recoveryObserver(){f();let i={identity:s,observation:++a};return{async request(c){return M.parse(await v(c,i))},async confirm(c,d){return H.parse(await v(d,i,c))}}},identify(i){if(!t)return;l=F(t,d=>({...d,identitySeq:U(d.identitySeq)})).identitySeq,r=i,s++,a++},reset(){if(t)try{F(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,s++,a++}},start(){t&&!w&&P()},destroy(){w=!0,r=null,s++,a++},async sync(){return await P()},read:h,async recover(){let i=f(),c=s,d=l;return a++,await P(async()=>{O(c);let E=await h();return O(c),l=F(i,A=>{if(A.identitySeq!==d)throw new o("IDENTITY_CHANGED","A newer installation intent exists");return{...A,identitySeq:U(Math.max(A.identitySeq,E.identitySeq)),addressSeq:Math.max(A.addressSeq,E.addressSeq)}}).identitySeq,await q()})},tokenObserver(){f();let i=++a,c=s;return async d=>{if(i!==a||c!==s)return null;let E=f(),C=r?await(e.session?.access()??r):null;if(!C)throw new o("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let A=F(E,g=>({...g,addressSeq:U(g.addressSeq)})),k=u.updatePushAddress,T=k.request.parse(await S("address",{...d,sequence:A.addressSeq,credentialDigest:await D(C)}));if(O(c),i!==a)return null;let R=await I(k.path,T,C);return O(c),i!==a||F(E,g=>g).addressSeq!==A.addressSeq?null:m(k.response.parse(R).installation)}}}}function oe(t,e){let n={async preference(r){let s=u.readMessagingPreference;return(await p(t,s,{channel:r})).preference},async setPreference(r){let s=u.setMessagingPreference;return(await p(t,s,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 n.setPreference({...r,channel:"push"})}}}}function ae(t,e,n={}){let r=!1;function s(){if(r)throw new o("CLOSED","SDK client was destroyed")}let a=new Set,l=w=>{for(let f of a)try{f(w)}catch{}},y=t.session.subscribeIdentity(()=>{l(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:s,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(w){return s(),a.add(w),()=>{a.delete(w)}},identify(w){s();let f=typeof w=="string"?w:w.accessToken;if(!L.test(f))throw new o("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(f),t.identify(w)},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 b(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new o("INVALID_REQUEST","Customer requests use the verified session identity")}var Ae={...u.readHoldings,request:u.readHoldings.request.omit({customerId:!0})};function ce(t){return{async checkEntitlement(e){b(e);let n=u.checkEntitlement,r=n.request.parse(e),s=await p(t,n,r);return ne(r.requirement,s.check,void 0,s.scope),s},async readHoldings(e={}){return p(t,Ae,e)}}}function ue(t){return{async readLedger(e){let n=u.readLedger;return p(t,n,{query:e})},async readCreditStatement(e){b(e);let n=u.readCreditStatement;return p(t,n,e)},async quoteBalance(e){b(e);let n=u.quoteBalance;return p(t,n,{command:e})}}}function de(t){return{async setupPayment(e){b(e);let n=u.setupPayment;return p(t,n,e)},async readPaymentSetup(e){b(e);let n=u.readPaymentSetup;return p(t,n,e)},async readBillingInvoice(e){b(e);let n=u.readBillingInvoice;return p(t,n,e)},async readBillingControls(e={}){b(e);let n=u.readBillingControls;return p(t,n,e)},async prepareBillingAuthorization(e){b(e);let n=u.prepareBillingAuthorization;return p(t,n,e)},async confirmBillingAuthorization(e){b(e);let n=u.confirmBillingAuthorization;return p(t,n,e)},async setBillingCoupons(e){b(e);let n=u.setBillingCoupons;return p(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){b(e);let n=u.revokeBillingAuthorization;return p(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){b(e);let n=u.listBillingInvoices;return p(t,n,e)},async confirmBillingAdjustment(e){b(e);let n=u.confirmBillingAdjustment;return p(t,n,e)}}}function pe(t){return{async previewUpdate(e){b(e);let n=u.previewUpdate;return p(t,n,e)},async update(e){b(e);let n=u.update;return p(t,n,e)},async readSubscriptionUpdate(e){b(e);let n=u.readSubscriptionUpdate;return p(t,n,e)},async restoreNativePurchase(e){b(e);let n=u.restoreNativePurchase;return p(t,n,e)},async previewAttach(e){b(e);let n=u.previewAttach;return p(t,n,e)},async attach(e){b(e);let n=u.attach;return p(t,n,e)},async readSubscriptionOperation(e){b(e);let n=u.readSubscriptionOperation;return p(t,n,e)}}}function le(t){return{async redeemReward(e){return b(e),(await p(t,u.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return b(e),(await p(t,u.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return b(e),(await p(t,u.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let r=await p(t,u.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 p(t,u.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await p(t,u.listOffers,{},{response:"Invalid offers response"})).offers}}}function fe(t){return{...ce(t),...ue(t),...de(t),...pe(t),...le(t)}}function me(t){return{async resolveContent(e){b(e);let n=u.resolveContent;return p(t,n,e)},async resolvePaywall(e){b(e);let n=u.resolvePaywall,r=n.request.parse(e),s=await p(t,n,r);return j(r,s.paywall.check,s.scope),s},async resolveOffering(e){b(e);let n=u.resolveOffering,r=n.request.parse(e),s=await p(t,n,r);return j(r,s.check,s.scope),s}}}var z=t=>new TextEncoder().encode(JSON.stringify(t)).length,ye=16384,be=5e3,Ee=6e4,Oe=5;function Se(t){return t instanceof o&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function Ie(t,e){let n=0,r,s=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],l=null,y,w=0;function f(){if(!e())throw new o("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(be*2**w,Ee)),typeof y=="object"&&"unref"in y&&y.unref())}function D(h){if(f(),r&&Date.now()<r.until&&!$(r.config,h.kind))return;q();let P=u.trackEvents.request.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(z({events:[P]})>ye)throw new o("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new o("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function m(h,P={},v={}){D({kind:"custom",name:h,properties:P,...v})}async function S(h=!1){if(f(),l)return l;let P=n,v=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let d=[],E=z({events:[]});for(let k of a.slice(0,Math.min(c,100))){let T=z(k)+(d.length?1:0);if(d.length&&E+T>ye)break;d.push(k),E+=T}let C=u.trackEvents,A;try{if(A=await p(t,C,{events:d},void 0,{keepalive:h}),P!==n)throw new o("IDENTITY_CHANGED","Event identity changed during delivery");if(A.inserted+A.duplicates+A.rejected+A.skipped!==d.length||A.rejections.length!==A.rejected)throw new o("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(k){throw P===n&&(w++,(Se(k)||w>=Oe)&&(a.splice(0,d.length),w=0)),k}w=0,s(A.analyticsConfig),a.splice(0,d.length),c-=d.length,i.inserted+=A.inserted,i.duplicates+=A.duplicates,i.rejected+=A.rejected,i.skipped+=A.skipped,i.rejections.push(...A.rejections)}return i})();l=v;try{return await v}finally{l===v&&(l=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:s,track:m,observe:D,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],w=0,l=null},detachVisibility(){I?.(),I=void 0}}}function he(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 Pe=new Set([...Z,"merchandiseId","merchandise"]);function Ce(t){let e=he(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!Pe.has(r))),...e?{merchandise:e}:{}}}function we(t,e,n,r,s){if(s&&r&&(s.scope.projectId!==r.projectId||s.scope.environment!==r.environment))throw new o("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,l=new Set;function y(){if(!e())throw new o("NOT_IDENTIFIED","Call identify before using Features or events")}async function w(f={}){s||y();let O=a,D=!1,m=async()=>{if(D||O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let T=u.getFeatures,R=s?{scope:{projectId:s.scope.projectId,environment:s.scope.environment},payload:await s.features()}:await p(t,T,{});if(O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new o("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await m(),I=!0,q,h=T=>{try{f.onError?.(T)}catch{}},P=(T,R)=>{try{let g=he(R);n.observe({...T,...g?{merchandise:g}:{}})}catch(g){h(g)}},v=re({assertUsable:s?.assertFeatures,scope:S.scope,attributes:f.attributes,onError:f.onError,load:async()=>I?(I=!1,S.payload):(await m()).payload,evaluateRemote:async T=>{if(O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let R=u.evaluateFeatures,g=await p(t,R,{...T,attributes:Ce(T.attributes)});if(g.scope.projectId!==S.scope.projectId||g.scope.environment!==S.scope.environment)throw new o("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:g.generation,evaluatedAt:g.evaluatedAt,expiresAt:g.expiresAt,features:g.features,...g.merchandiseContext?{merchandiseContext:g.merchandiseContext}:{}}},onExperimentViewed:(T,R,g,x)=>P({kind:"experiment_exposure",generation:x,experimentId:T.key,variationId:R.key},g),onFeatureUsage:(T,R,g,x)=>P({kind:"feature_usage",generation:x,feature:T,value:R.value??null,source:R.source,ruleId:R.ruleId,...R.experimentResult?{variationId:R.experimentResult.key}:{}},g)}),i=v.refresh;function c(){clearTimeout(q),!s&&(D||O!==a||!v.expiresAt||(q=setTimeout(()=>{d().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(v.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function d(){try{return await i()}finally{c()}}let E=()=>{D||d().catch(h)},C=v.subscribe(c),A=s?.subscribe(()=>{!D&&s.fresh&&d().catch(h)});function k(){D||(D=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",E),C(),A?.(),v.reset(),l.delete(k))}l.add(k);try{await v.init(),(f.attributes?.merchandise||f.attributes?.merchandiseId)&&await v.refreshRemote()}catch(T){throw k(),T}return c(),!s&&typeof window<"u"&&window.addEventListener("focus",E),Object.assign(v,{refresh:d,destroy:k})}return{features:w,reset(f){a++,f();for(let O of l)O()}}}import{z as Te}from"zod";function ge(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=Te.object({funnelId:G.shape.id,funnelVersionId:G.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new o("INVALID_REQUEST","A valid Funnel source is required");let s=Object.freeze(r.data);function a(l){if("customerId"in l)throw new o("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in l&&l.funnelId!==void 0&&l.funnelId!==s.funnelId||"funnelVersionId"in l&&l.funnelVersionId!==void 0&&l.funnelVersionId!==s.funnelVersionId)throw new o("SCOPE_MISMATCH","The original Funnel source cannot change");return{...l,...s}}return{async claimCoupon(l,y=crypto.randomUUID()){let w=u.grantOffer,f=await p(t,w,a({couponId:l,requestId:y}));return{offer:f.offer,reason:f.reason}},async resolveOffering(l){let y=u.resolveOffering,w=y.request.parse(a(l)),f=await p(t,y,w);return j(w,f.check,f.scope),f},async resolvePaywall(l){let y=u.resolvePaywall,w=y.request.parse(a(l)),f=await p(t,y,w);return j(w,f.paywall.check,f.scope),f},async previewAttach(l){let y=u.previewAttach;return p(t,y,a(l))}}}function Ht(t){return Re(t)}function Re(t){let e=te(t),n=e.request,r;try{r=se(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let s=ae(e,()=>{l.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Ie(n,s.isIdentified),l=we(n,s.isIdentified,a,t.scope,t.configuration);return{session:e.session,...oe(n,r),...fe(n),...me(n),forFunnel(y){return s.assertActive(),ge(n,y)},async features(y={}){return s.assertActive(),l.features(y)},track(y,w,f={}){return a.track(y,w,f)},flush(){return a.flush()},...s.methods}}function Qt(t){if(!L.test(t.customerToken))throw new o("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new o("INVALID_REQUEST","An explicit App and environment scope is required");let e=ie({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),s=B({...t,runToken:r.runToken,initialResponse:r});s.identify(t.customerToken);let a=await s.get();return{...r,...a,controller:s}}}}function tn(t){if(!t.scope)throw new o("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new o("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,s=new Set,a=new Map,l=new Map;async function y(m){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new o("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(m),I])}finally{clearTimeout(S)}}function w(m){throw m instanceof o&&(m.status===401||m.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear()),m}function f(m,S){if(S!==r)throw new o("IDENTITY_CHANGED","Process was detached during a request");let I=ee.parse(m);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new o("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 o("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 o("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let E of s)J(E,I.run);I.run.instruction?.type==="authentication_required"&&J(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&l.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:v,settlement:i,...c}=I,d=i&&(({accepted:E,...C})=>C)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...d?{settlement:d}:{}}}let O=m=>(a.has(m)||a.set(m,e?.run.identity.binding?.id??null),a.get(m));async function D(m){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return w(P)};if(m.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new o("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(m.release,m.usedReceiptIds)).catch(q)}let h;if(m.operation==="get"){let{operation:P,customerToken:v,...i}=m;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(m.operation==="review")h=await y(()=>t.adapter.review(m.receiptId)).catch(q);else{if(m.operation==="start")throw new o("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...v}=m;h=await y(()=>t.adapter.command(v,O(v.requestId))).catch(q)}}return f(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(m){let S=r,I=await y(()=>t.adapter.open(m)).catch(w),q=f(I,S);if(!n){n=B({...t,runToken:I.runToken,initialResponse:q,process:{request:D,binding:O,restore(v){for(let[i,c]of Object.entries(v))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async v=>{try{return await P(v)}catch(i){if(!(i instanceof o)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||v.operation!=="submit"||v.input.type!=="screen"||a.get(v.requestId)!==null)throw i;await h.settle?.(v.requestId),await h.get();let c=h.view;if(l.get(v.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==v.nodeId||c.visit!==v.visit||!e?.run.identity.binding)throw i;return P({...v,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 m=r;f(await y(()=>t.adapter.syncIdentity()).catch(w),m),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(),l.clear(),await y(()=>t.adapter.detach())},forProcess(m){if(!e?.run.identity.binding)throw new o("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:m}},subscribe(m){return s.add(m),()=>{s.delete(m)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear(),s.clear()}}}export{Ht as a,Re as b,Qt as c,tn as d};
|
|
1
|
+
import{a as p,b as ne,c as j,d as re,n as B,q as ie}from"./chunk-WMIDEJTZ.js";import{b as te}from"./chunk-XFO4FBFG.js";import{a as o}from"./chunk-QVGTHPWT.js";import{Da as u,Fa as G,Qa as ee,_ as $,a as K,b as Q,c as W,d as M,e as H,f as X,ia as Z,q as L}from"./chunk-KRQESEG2.js";import{a as J}from"./chunk-DSPLGTQI.js";import{a as Y}from"./chunk-HDVLCRC6.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new o("INVALID_STATE","Installation sequence exhausted");return t+1},ve=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 F(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 o("INVALID_STATE","Installation journal is invalid");return e({...n})})}function se(t,e,n){let r=null,s=0,a=0,l=0,y=Promise.resolve(),w=!1;if(t&&(!n||Y.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new o("SCOPE_MISMATCH","Push installation belongs to another scope");let f=()=>{if(w)throw new o("CLOSED","SDK client was destroyed");if(!t)throw new o("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==s)throw new o("IDENTITY_CHANGED","Identity changed during Push operation")};async function D(i){let c=f();if(!c.sha256&&!globalThis.crypto?.subtle)throw new o("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let d=c.sha256?await c.sha256(Uint8Array.from(i,E=>E.charCodeAt(0))):await ve(i);if(!/^[a-f0-9]{64}$/.test(d))throw new o("INVALID_STATE","Push credential digest is invalid");return d}function m(i){let c=H.parse(i);if(c.installationId.toLowerCase()!==f().installationId.toLowerCase())throw new o("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let d=f(),E={installationId:d.installationId,publicKey:d.publicKey,issuedAt:new Date().toISOString(),...c},C=await d.sign(X(i,d.scope,E));return{...E,signature:C}}let I=(i,c,d)=>e.requestWithCredential?e.requestWithCredential(i,c,d):e.request(i,c);async function q(){let i=f(),c=s,d=r?await(e.session?.access()??r):null,E=F(i,g=>g),C;if(E.detachSeq!==null){let g=E.detachSeq,x=K.parse(await S("detach",{sequence:g,platform:i.platform}));try{let N=await e.request("push/installations/detach",{...i.scope,...x},"POST",{installationDetach:!0});if(!N||typeof N!="object"||!("installation"in N))throw new o("INVALID_RESPONSE","Push detach acknowledgement is invalid");let _=m(N.installation);if(_.bound||_.identitySeq!==g)throw new o("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(N){if(N instanceof o&&N.status===404)C=N;else if(!(N instanceof o)||N.status!==412)throw N}C||F(i,N=>({...N,detachSeq:N.detachSeq===g?null:N.detachSeq}))}if(O(c),!d){if(C)throw C;return null}let A=u.bindPushInstallation,k=A.request.parse(await S("bind",{sequence:l,platform:i.platform,credentialDigest:await D(d)}));O(c);let T=A.response.parse(await I(A.path,k,d));O(c);let R=m(T.installation);if(!R.bound||R.identitySeq!==l)throw new o("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return C&&E.detachSeq!==null&&l>E.detachSeq&&F(i,g=>({...g,detachSeq:g.detachSeq===E.detachSeq?null:g.detachSeq})),R}async function h(){f();let i=s,c=r?await(e.session?.access()??r):null;if(!c)throw new o("NOT_IDENTIFIED","Identify before reading this installation");let d=u.readPushInstallation,E=d.request.parse(await S("read",{credentialDigest:await D(c)}));O(i);let C=d.response.parse(await I(d.path,E,c));return O(i),m(C.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(d=>{try{t?.onError?.(d instanceof Error?d:new Error("Push synchronization failed"))}catch{}}),c}async function v(i,c,d){let E=f(),C=c.identity,A=c.observation,k=r?await(e.session?.access()??r):null;if(O(C),A!==a)throw new o("INVALID_STATE","Push observation changed during recovery");if(!k)throw new o("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new o("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(C),await q(),O(C),A!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let T=F(E,_=>d?_:{..._,addressSeq:U(_.addressSeq)}),g=await S(d?"recovery_confirm":"recovery_request",{...i,sequence:T.addressSeq,credentialDigest:await D(k),...d?{challenge:d}:{}}),x=d?W.parse(g):Q.parse(g);if(O(C),A!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let N=await I(`push/installations/recovery/${d?"confirm":"request"}`,x,k);if(O(C),A!==a||F(E,_=>_).addressSeq!==T.addressSeq)throw new o("INVALID_STATE","Push observation changed during recovery");if(d){let _=u.updatePushAddress.response.parse(N),V=m(_.installation);if(!V.bound||V.identitySeq!==l||V.addressSeq!==T.addressSeq||V.connectionId!==i.connectionId||V.addressStatus!=="active")throw new o("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return V}if(!N||typeof N!="object"||!("recovery"in N))throw new o("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return M.parse(N.recovery)})}return{recoveryObserver(){f();let i={identity:s,observation:++a};return{async request(c){return M.parse(await v(c,i))},async confirm(c,d){return H.parse(await v(d,i,c))}}},identify(i){if(!t)return;l=F(t,d=>({...d,identitySeq:U(d.identitySeq)})).identitySeq,r=i,s++,a++},reset(){if(t)try{F(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,s++,a++}},start(){t&&!w&&P()},destroy(){w=!0,r=null,s++,a++},async sync(){return await P()},read:h,async recover(){let i=f(),c=s,d=l;return a++,await P(async()=>{O(c);let E=await h();return O(c),l=F(i,A=>{if(A.identitySeq!==d)throw new o("IDENTITY_CHANGED","A newer installation intent exists");return{...A,identitySeq:U(Math.max(A.identitySeq,E.identitySeq)),addressSeq:Math.max(A.addressSeq,E.addressSeq)}}).identitySeq,await q()})},tokenObserver(){f();let i=++a,c=s;return async d=>{if(i!==a||c!==s)return null;let E=f(),C=r?await(e.session?.access()??r):null;if(!C)throw new o("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let A=F(E,g=>({...g,addressSeq:U(g.addressSeq)})),k=u.updatePushAddress,T=k.request.parse(await S("address",{...d,sequence:A.addressSeq,credentialDigest:await D(C)}));if(O(c),i!==a)return null;let R=await I(k.path,T,C);return O(c),i!==a||F(E,g=>g).addressSeq!==A.addressSeq?null:m(k.response.parse(R).installation)}}}}function oe(t,e){let n={async preference(r){let s=u.readMessagingPreference;return(await p(t,s,{channel:r})).preference},async setPreference(r){let s=u.setMessagingPreference;return(await p(t,s,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 n.setPreference({...r,channel:"push"})}}}}function ae(t,e,n={}){let r=!1;function s(){if(r)throw new o("CLOSED","SDK client was destroyed")}let a=new Set,l=w=>{for(let f of a)try{f(w)}catch{}},y=t.session.subscribeIdentity(()=>{l(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:s,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(w){return s(),a.add(w),()=>{a.delete(w)}},identify(w){s();let f=typeof w=="string"?w:w.accessToken;if(!L.test(f))throw new o("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(f),t.identify(w)},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 b(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new o("INVALID_REQUEST","Customer requests use the verified session identity")}var Ae={...u.readHoldings,request:u.readHoldings.request.omit({customerId:!0})};function ce(t){return{async checkEntitlement(e){b(e);let n=u.checkEntitlement,r=n.request.parse(e),s=await p(t,n,r);return ne(r.requirement,s.check,void 0,s.scope),s},async readHoldings(e={}){return p(t,Ae,e)}}}function ue(t){return{async readLedger(e){let n=u.readLedger;return p(t,n,{query:e})},async readCreditStatement(e){b(e);let n=u.readCreditStatement;return p(t,n,e)},async quoteBalance(e){b(e);let n=u.quoteBalance;return p(t,n,{command:e})}}}function de(t){return{async setupPayment(e){b(e);let n=u.setupPayment;return p(t,n,e)},async readPaymentSetup(e){b(e);let n=u.readPaymentSetup;return p(t,n,e)},async readBillingInvoice(e){b(e);let n=u.readBillingInvoice;return p(t,n,e)},async readBillingControls(e={}){b(e);let n=u.readBillingControls;return p(t,n,e)},async prepareBillingAuthorization(e){b(e);let n=u.prepareBillingAuthorization;return p(t,n,e)},async confirmBillingAuthorization(e){b(e);let n=u.confirmBillingAuthorization;return p(t,n,e)},async setBillingCoupons(e){b(e);let n=u.setBillingCoupons;return p(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){b(e);let n=u.revokeBillingAuthorization;return p(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){b(e);let n=u.listBillingInvoices;return p(t,n,e)},async confirmBillingAdjustment(e){b(e);let n=u.confirmBillingAdjustment;return p(t,n,e)}}}function pe(t){return{async previewUpdate(e){b(e);let n=u.previewUpdate;return p(t,n,e)},async update(e){b(e);let n=u.update;return p(t,n,e)},async readSubscriptionUpdate(e){b(e);let n=u.readSubscriptionUpdate;return p(t,n,e)},async restoreNativePurchase(e){b(e);let n=u.restoreNativePurchase;return p(t,n,e)},async previewAttach(e){b(e);let n=u.previewAttach;return p(t,n,e)},async attach(e){b(e);let n=u.attach;return p(t,n,e)},async readSubscriptionOperation(e){b(e);let n=u.readSubscriptionOperation;return p(t,n,e)}}}function le(t){return{async redeemReward(e){return b(e),(await p(t,u.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return b(e),(await p(t,u.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return b(e),(await p(t,u.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let r=await p(t,u.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 p(t,u.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await p(t,u.listOffers,{},{response:"Invalid offers response"})).offers}}}function fe(t){return{...ce(t),...ue(t),...de(t),...pe(t),...le(t)}}function me(t){return{async resolveContent(e){b(e);let n=u.resolveContent;return p(t,n,e)},async resolvePaywall(e){b(e);let n=u.resolvePaywall,r=n.request.parse(e),s=await p(t,n,r);return j(r,s.paywall.check,s.scope),s},async resolveOffering(e){b(e);let n=u.resolveOffering,r=n.request.parse(e),s=await p(t,n,r);return j(r,s.check,s.scope),s}}}var z=t=>new TextEncoder().encode(JSON.stringify(t)).length,ye=16384,be=5e3,Ee=6e4,Oe=5;function Se(t){return t instanceof o&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function Ie(t,e){let n=0,r,s=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],l=null,y,w=0;function f(){if(!e())throw new o("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(be*2**w,Ee)),typeof y=="object"&&"unref"in y&&y.unref())}function D(h){if(f(),r&&Date.now()<r.until&&!$(r.config,h.kind))return;q();let P=u.trackEvents.request.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(z({events:[P]})>ye)throw new o("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new o("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function m(h,P={},v={}){D({kind:"custom",name:h,properties:P,...v})}async function S(h=!1){if(f(),l)return l;let P=n,v=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let d=[],E=z({events:[]});for(let k of a.slice(0,Math.min(c,100))){let T=z(k)+(d.length?1:0);if(d.length&&E+T>ye)break;d.push(k),E+=T}let C=u.trackEvents,A;try{if(A=await p(t,C,{events:d},void 0,{keepalive:h}),P!==n)throw new o("IDENTITY_CHANGED","Event identity changed during delivery");if(A.inserted+A.duplicates+A.rejected+A.skipped!==d.length||A.rejections.length!==A.rejected)throw new o("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(k){throw P===n&&(w++,(Se(k)||w>=Oe)&&(a.splice(0,d.length),w=0)),k}w=0,s(A.analyticsConfig),a.splice(0,d.length),c-=d.length,i.inserted+=A.inserted,i.duplicates+=A.duplicates,i.rejected+=A.rejected,i.skipped+=A.skipped,i.rejections.push(...A.rejections)}return i})();l=v;try{return await v}finally{l===v&&(l=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:s,track:m,observe:D,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],w=0,l=null},detachVisibility(){I?.(),I=void 0}}}function he(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 Pe=new Set([...Z,"merchandiseId","merchandise"]);function Ce(t){let e=he(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!Pe.has(r))),...e?{merchandise:e}:{}}}function we(t,e,n,r,s){if(s&&r&&(s.scope.projectId!==r.projectId||s.scope.environment!==r.environment))throw new o("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,l=new Set;function y(){if(!e())throw new o("NOT_IDENTIFIED","Call identify before using Features or events")}async function w(f={}){s||y();let O=a,D=!1,m=async()=>{if(D||O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let T=u.getFeatures,R=s?{scope:{projectId:s.scope.projectId,environment:s.scope.environment},payload:await s.features()}:await p(t,T,{});if(O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new o("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await m(),I=!0,q,h=T=>{try{f.onError?.(T)}catch{}},P=(T,R)=>{try{let g=he(R);n.observe({...T,...g?{merchandise:g}:{}})}catch(g){h(g)}},v=re({assertUsable:s?.assertFeatures,scope:S.scope,attributes:f.attributes,onError:f.onError,load:async()=>I?(I=!1,S.payload):(await m()).payload,evaluateRemote:async T=>{if(O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let R=u.evaluateFeatures,g=await p(t,R,{...T,attributes:Ce(T.attributes)});if(g.scope.projectId!==S.scope.projectId||g.scope.environment!==S.scope.environment)throw new o("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:g.generation,evaluatedAt:g.evaluatedAt,expiresAt:g.expiresAt,features:g.features,...g.merchandiseContext?{merchandiseContext:g.merchandiseContext}:{}}},onExperimentViewed:(T,R,g,x)=>P({kind:"experiment_exposure",generation:x,experimentId:T.key,variationId:R.key},g),onFeatureUsage:(T,R,g,x)=>P({kind:"feature_usage",generation:x,feature:T,value:R.value??null,source:R.source,ruleId:R.ruleId,...R.experimentResult?{variationId:R.experimentResult.key}:{}},g)}),i=v.refresh;function c(){clearTimeout(q),!s&&(D||O!==a||!v.expiresAt||(q=setTimeout(()=>{d().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(v.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function d(){try{return await i()}finally{c()}}let E=()=>{D||d().catch(h)},C=v.subscribe(c),A=s?.subscribe(()=>{!D&&s.fresh&&d().catch(h)});function k(){D||(D=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",E),C(),A?.(),v.reset(),l.delete(k))}l.add(k);try{await v.init(),(f.attributes?.merchandise||f.attributes?.merchandiseId)&&await v.refreshRemote()}catch(T){throw k(),T}return c(),!s&&typeof window<"u"&&window.addEventListener("focus",E),Object.assign(v,{refresh:d,destroy:k})}return{features:w,reset(f){a++,f();for(let O of l)O()}}}import{z as Te}from"zod";function ge(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=Te.object({funnelId:G.shape.id,funnelVersionId:G.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new o("INVALID_REQUEST","A valid Funnel source is required");let s=Object.freeze(r.data);function a(l){if("customerId"in l)throw new o("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in l&&l.funnelId!==void 0&&l.funnelId!==s.funnelId||"funnelVersionId"in l&&l.funnelVersionId!==void 0&&l.funnelVersionId!==s.funnelVersionId)throw new o("SCOPE_MISMATCH","The original Funnel source cannot change");return{...l,...s}}return{async claimCoupon(l,y=crypto.randomUUID()){let w=u.grantOffer,f=await p(t,w,a({couponId:l,requestId:y}));return{offer:f.offer,reason:f.reason}},async resolveOffering(l){let y=u.resolveOffering,w=y.request.parse(a(l)),f=await p(t,y,w);return j(w,f.check,f.scope),f},async resolvePaywall(l){let y=u.resolvePaywall,w=y.request.parse(a(l)),f=await p(t,y,w);return j(w,f.paywall.check,f.scope),f},async previewAttach(l){let y=u.previewAttach;return p(t,y,a(l))}}}function Ht(t){return Re(t)}function Re(t){let e=te(t),n=e.request,r;try{r=se(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let s=ae(e,()=>{l.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Ie(n,s.isIdentified),l=we(n,s.isIdentified,a,t.scope,t.configuration);return{session:e.session,...oe(n,r),...fe(n),...me(n),forFunnel(y){return s.assertActive(),ge(n,y)},async features(y={}){return s.assertActive(),l.features(y)},track(y,w,f={}){return a.track(y,w,f)},flush(){return a.flush()},...s.methods}}function Qt(t){if(!L.test(t.customerToken))throw new o("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new o("INVALID_REQUEST","An explicit App and environment scope is required");let e=ie({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),s=B({...t,runToken:r.runToken,initialResponse:r});s.identify(t.customerToken);let a=await s.get();return{...r,...a,controller:s}}}}function tn(t){if(!t.scope)throw new o("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new o("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,s=new Set,a=new Map,l=new Map;async function y(m){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new o("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(m),I])}finally{clearTimeout(S)}}function w(m){throw m instanceof o&&(m.status===401||m.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear()),m}function f(m,S){if(S!==r)throw new o("IDENTITY_CHANGED","Process was detached during a request");let I=ee.parse(m);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new o("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 o("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 o("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let E of s)J(E,I.run);I.run.instruction?.type==="authentication_required"&&J(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&l.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:v,settlement:i,...c}=I,d=i&&(({accepted:E,...C})=>C)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...d?{settlement:d}:{}}}let O=m=>(a.has(m)||a.set(m,e?.run.identity.binding?.id??null),a.get(m));async function D(m){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return w(P)};if(m.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new o("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(m.release,m.usedReceiptIds)).catch(q)}let h;if(m.operation==="get"){let{operation:P,customerToken:v,...i}=m;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(m.operation==="review")h=await y(()=>t.adapter.review(m.receiptId)).catch(q);else{if(m.operation==="start")throw new o("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...v}=m;h=await y(()=>t.adapter.command(v,O(v.requestId))).catch(q)}}return f(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(m){let S=r,I=await y(()=>t.adapter.open(m)).catch(w),q=f(I,S);if(!n){n=B({...t,runToken:I.runToken,initialResponse:q,process:{request:D,binding:O,restore(v){for(let[i,c]of Object.entries(v))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async v=>{try{return await P(v)}catch(i){if(!(i instanceof o)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||v.operation!=="submit"||v.input.type!=="screen"||a.get(v.requestId)!==null)throw i;await h.settle?.(v.requestId),await h.get();let c=h.view;if(l.get(v.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==v.nodeId||c.visit!==v.visit||!e?.run.identity.binding)throw i;return P({...v,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 m=r;f(await y(()=>t.adapter.syncIdentity()).catch(w),m),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(),l.clear(),await y(()=>t.adapter.detach())},forProcess(m){if(!e?.run.identity.binding)throw new o("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:m}},subscribe(m){return s.add(m),()=>{s.delete(m)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear(),s.clear()}}}export{Ht as a,Re as b,Qt as c,tn as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sa as g}from"./chunk-
|
|
1
|
+
import{sa as g}from"./chunk-KRQESEG2.js";async function u(t,r,e){if(Number(t.headers.get("content-length"))>r)throw t.body?.cancel().catch(()=>{}),e.error("limit");let o=t.body?.getReader();if(!o)throw e.error("missing");let i=[],s=0,c=!1,a=()=>{},b=new Promise((n,f)=>{a=()=>f(e.signal?.reason),e.signal?.addEventListener("abort",a,{once:!0}),e.signal?.aborted&&a()});try{for(;;){let n=await Promise.race([o.read(),b]);if(n.done){c=!0;break}if(s+=n.value.length,s>r)throw e.error("limit");i.push(n.value)}}finally{e.signal?.removeEventListener("abort",a),c||o.cancel().catch(()=>{}),o.releaseLock()}e.signal?.throwIfAborted();let l=new Uint8Array(s),d=0;for(let n of i)l.set(n,d),d+=n.length;return l}async function m(t,r,e){return new TextDecoder("utf-8",{fatal:!0}).decode(await u(t,r,e))}function y(t,r){let e=typeof t=="string"?new TextEncoder().encode(t):t;return e.byteLength===r.byteLength&&g(e)===r.sha256}export{u as a,m as b,y as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as Ve,c as sn}from"./chunk-JGG4R75K.js";import{d as tn,f as qe,g as _e,h as rn,i as Le,k as on}from"./chunk-6DTGBDYG.js";import{a as Ke,b as Xe,c as Ze,d as en,e as nn,f as Te}from"./chunk-YAVWELIV.js";import{a as b}from"./chunk-QVGTHPWT.js";import{b as an,e as un}from"./chunk-SLUA7ABW.js";import{d as ln}from"./chunk-GQ7B25L5.js";import{Z as xe,ma as Ae}from"./chunk-KSCITFNQ.js";import{a as le}from"./chunk-DSPLGTQI.js";import{Da as We,I as Be,Na as Ye}from"./chunk-HDVLCRC6.js";async function dn(n){let{session:E,load:e}=bn(n);try{return await e(),E}catch(I){throw E.destroy(),I}}function bn(n){let E=n.view;if(!E?.paywall)throw new b("INVALID_REQUEST","The current node is not a Paywall");let e=E.paywall.receiptId,I=E.nodeId,w=E.visit,P=E.paywall.resolution,o=E.paywall,m="document"in P?{document:P.document,offering:P.offering,capabilities:P.capabilities}:null;function p(){let i=o.resolution;return"document"in i?i:m&&{...i,document:m.document,offering:m.offering,capabilities:Ke(i.capabilities,m.capabilities)}}function r(i){if(!Xe(i,P))throw new b("INVALID_RESPONSE","The pinned Paywall binding changed")}let v=!1,S=new Set,A=null;function F(){let i=p();if(i&&!v)for(let c of S)le(c,structuredClone(i))}async function q(){L();let i=p();if(i)return structuredClone(i);if(!A){let c=(async()=>{if("document"in o.resolution||!n.resolvePaywall)throw new b("INVALID_RESPONSE","Public Paywall reader is unavailable");let d=await n.resolvePaywall(o.resolution);return L(),r(d),m={document:d.document,offering:d.offering,capabilities:d.capabilities},F(),p()})();A=c;let a=()=>{A===c&&(A=null)};c.then(a,a)}return A.then(c=>structuredClone(c))}let u=new AbortController,O=(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===I&&i.visit===w&&i.input.type==="paywall_quote")?.requestId??E.paywall.purchaseRequestId,T=0,D=null,z=new Set,N=null,f=new Map;function M(i){if(i.purchase&&i.purchase.receiptId!==e)throw new b("INVALID_RESPONSE","Purchase receipt changed");let c=i.run.paywall;return i.purchase??(c?.receiptId===e?c:null)}function L(){if(v)throw new b("IDENTITY_CHANGED","Paywall presentation has closed")}function x(i,c,a){if(L(),c!==T||a!==void 0&&o.quote?.operationId!==a)return!1;let d=o.selectionGeneration??0,y=i.run.paywall;if(y?.receiptId===e){if((y.selectionGeneration??0)<(o.selectionGeneration??0))return!1;r(y.resolution)}let h=M(i),B=y?.receiptId===e&&(y.selectionGeneration??0)>d,Q=B?h?.quote??null:h?.quote??o.quote,$=h?.operation??(Q?.operationId===o.quote?.operationId?o.operation:null);return Q&&$&&Ze($,{operationId:Q.operationId},"Purchase operation changed"),(B||Q?.operationId!==o.quote?.operationId)&&(T++,y?.receiptId===e&&(O=y.purchaseRequestId)),o={...o,...y?.receiptId===e?y:{},quote:Q,operation:nn(o.operation,$,!0)},F(),!0}function U(i,c,a){return new Promise((d,y)=>{let h=!1,B=()=>{clearTimeout(ce),u.signal.removeEventListener("abort",Z)},Q=ye=>{h||(h=!0,B(),d(ye))},$=ye=>{h||(h=!0,B(),y(ye))},Z=()=>$(new b("IDENTITY_CHANGED","Paywall presentation has closed")),ce=setTimeout(()=>$(new b("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a)),Math.max(0,c-Date.now()));u.signal.addEventListener("abort",Z,{once:!0}),u.signal.aborted&&Z(),i.then(Q,$)})}function Y(i){return new Promise(c=>{let a=()=>{clearTimeout(d),u.signal.removeEventListener("abort",a),c()},d=setTimeout(a,i);u.signal.addEventListener("abort",a,{once:!0}),u.signal.aborted&&a()})}function _(i,c){L();let a=f.get(i)??n.pendingCommands?.find(h=>h.requestId===i)??n.pendingCommand;if(a?.operation==="submit"&&a.requestId===i&&a.nodeId===I&&a.visit===w){c.type==="paywall_quote"&&a.input.type==="paywall_quote"&&a.input.predecessor&&!c.predecessor&&(c={...c,predecessor:a.input.predecessor});let h=Ae.parse(a),B=Ae.parse({...a,input:c});if(h.operation!=="submit"||B.operation!=="submit"||JSON.stringify(h.input)!==JSON.stringify(B.input))throw new b("CONFLICT","A purchase request cannot change its input");return f.set(i,h),h}let d=n.view;if(!d||d.nodeId!==I||d.visit!==w||d.paywall?.receiptId!==e)throw new b("PRECONDITION_FAILED","The Paywall visit has changed");let y=Ae.parse({operation:"submit",requestId:i,nodeId:I,visit:w,revision:d.revision,input:structuredClone(c)});if(y.operation!=="submit")throw new b("INVALID_REQUEST","A purchase submission is required");return f.set(i,y),y}async function C(i,c){L();let{requestId:a,input:d}=i,y=Date.now()+3e4;z.add(a);try{let h=await U(n.submit(i),y,a);for(;h.run.pendingRequest?.requestId===a&&Date.now()<y&&!v&&(await Y(Math.min(1e3,y-Date.now())),!(v||Date.now()>=y));)h=await U(n.resume(a),y,a);if(v)throw new b("IDENTITY_CHANGED","Paywall presentation has closed");if(h.run.pendingRequest?.requestId===a)throw new b("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a);if(!x(h,c,d.type==="paywall_confirm"||d.type==="paywall_cancel"?d.operationId:void 0))throw new b("PRECONDITION_FAILED","The purchase selection has changed");N===a&&(N=null)}catch(h){throw N=a,h instanceof b&&h.code==="COMMAND_PENDING"&&h.status===void 0&&f.delete(a),h}finally{z.delete(a)}}async function G(i){if(!o.quote)throw new b("INVALID_REQUEST","A quoted purchase is required");let c=i==="confirm"?"paywall_confirm":"paywall_cancel",a=[...f.values(),...n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])].find(y=>y.operation==="submit"&&y.input.type===c&&"operationId"in y.input&&y.input.operationId===o.quote.operationId),d=a?.operation==="submit"&&a.input.type===c&&"operationId"in a.input&&a.input.operationId===o.quote.operationId?a.requestId:crypto.randomUUID();if(await C(_(d,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.quote.operationId}),T),!o.operation)throw new b("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(o.operation)}let j={get view(){return structuredClone(p())},get quote(){return o.quote?structuredClone(o.quote):null},get operation(){return o.operation?structuredClone(o.operation):null},get webViewUrl(){return n.webViewUrl},get canReselect(){return o.canReselect===!0},get recovery(){let i=n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[]),c=n.pendingPurchase;if(c&&(c.receiptId!==e||c.operationId!==o.quote?.operationId))return{type:"recover",operationId:c.operationId,requestId:i[0]?.requestId??null};let a=Te({quote:o.quote,operation:o.operation,requestId:i[0]?.requestId??N??O,pending:z.size>0||i.length>0||N!==null,destroyed:v,canReselect:o.canReselect});return a.type==="recover"&&a.requestId===null&&!v&&n.hasDurableJournal===!0&&!o.quote&&!o.operation&&(o.selectionGeneration??0)===0&&!c&&!i.length&&!z.size&&!O?{type:"native",operationId:null}:a},get pendingCancellation(){return!v&&(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===I&&i.visit===w&&i.input.type==="paywall_cancel"&&i.input.operationId===o.quote?.operationId)},subscribe(i){return v?()=>{}:(S.add(i),()=>S.delete(i))},async refresh(){L();let i=T,c=await n.get();if(x(c,i),c.run.paywall?.receiptId!==e)throw new b("PRECONDITION_FAILED","Paywall presentation has changed");return q()},preview(i){let c=p();if(!c)return Promise.reject(new b("PRECONDITION_FAILED","Load the Paywall presentation first"));if(O&&O!==i.requestId&&(D||o.canReselect!==!0))return Promise.reject(new b("COMMAND_PENDING","Retry the original purchase before starting another"));let a=c.document.buttons[i.actionId],d=a?.type==="checkout"?xe(a.product,i.selection,c.capabilities):null;if(!d)return Promise.reject(new b("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let y=Ye(c.document.screen,d,i.selection,c.capabilities),h=O!==i.requestId&&(o.selectionGeneration??0)>0?{operationId:o.quote?.operationId??null,generation:o.selectionGeneration??0}:void 0;if(h&&o.canReselect!==!0)return Promise.reject(new b("COMMAND_PENDING","Original purchase requires authoritative termination"));let B;try{B=_(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:d,...Object.keys(y).length?{featureQuantities:y}:{},...h?{predecessor:h}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}})}catch(Z){return Promise.reject(Z)}if(O===i.requestId&&D)return D;O!==i.requestId&&T++;let Q=T;O=i.requestId;let $=(async()=>{if(await C(B,Q),!o.quote)throw new b("INVALID_RESPONSE","The accepted quote is missing");return en(o.quote,{productVersionId:d,featureQuantities:y},"The selected purchase changed"),structuredClone(o.quote)})();return D=$,$.then(()=>{D===$&&(D=null)},Z=>{D===$&&(D=null),O===i.requestId&&n.pendingCommand?.requestId!==i.requestId&&Z instanceof b&&Z.status!==void 0&&Z.status<500&&![401,425].includes(Z.status)&&(O=null)}),$},confirm:()=>G("confirm"),cancel:()=>G("cancel"),async read(){if(L(),!o.quote)throw new b("INVALID_REQUEST","A quoted purchase is required");let i=o.quote.operationId,c=T,a=n.pendingCommands?.find(Q=>Q.operation==="submit"&&(Q.input.type==="paywall_confirm"||Q.input.type==="paywall_cancel")&&Q.input.operationId===i)??n.pendingCommand;a?.operation==="submit"&&(a.input.type==="paywall_confirm"||a.input.type==="paywall_cancel")&&a.input.operationId===i&&await n.settle?.(a.requestId);let d=await n.get(void 0,{receiptId:e,operationId:i});L();let y=M(d);if(y?.quote&&y.quote.operationId!==i||y?.operation&&y.operation.operationId!==i)throw new b("INVALID_RESPONSE","Purchase operation changed");let h=x(d,c,i),B=h?o.operation:y?.operation;if(!B)throw new b("INVALID_RESPONSE","The current purchase result is missing");return h&&z.size===0&&!(n.pendingCommands?.length??(n.pendingCommand?1:0))&&(N=null),structuredClone(B)},destroy(){v=!0,ie(),S.clear(),u.abort(),f.clear()}},ie=n.subscribe(i=>{v||i.nodeId!==I||i.visit!==w||i.paywall?.receiptId!==e||(i.paywall.selectionGeneration??0)<(o.selectionGeneration??0)||(r(i.paywall.resolution),o={...o,resolution:i.paywall.resolution},F())});return{session:j,load:q}}function cn(n){let E=new Set,e=new Set,I=null;async function w(p,r){let v=!1;for(;!n.stopped&&n.key===p&&n.client.pendingCommand?.requestId===r;){if(!n.client.settle)throw new b("COMMAND_PENDING","The original display acknowledgement is still pending");await n.client.settle(r),v=!0,n.client.pendingCommand?.requestId===r&&await new Promise(S=>setTimeout(S,1500))}n.stopped||n.key!==p||(v&&await n.client.get(),!(n.stopped||n.key!==p)&&E.add(p))}function P(p,r){I=r;let v=()=>{I===r&&(I=null),e.delete(p)};return r.then(v,S=>{v(),n.busy||n.fail(S)}),r}function o(p){if(n.reviewing||E.has(p)||e.has(p)||n.stopped)return;e.add(p);let r=async()=>{if(n.reviewing||n.stopped||n.key!==p||E.has(p)){e.delete(p);return}if(n.busy||n.client.pendingCommand){setTimeout(()=>{r()},250);return}let v=(async()=>{if(n.staleRead){if(await n.staleRead,n.stopped||n.key!==p)return;if(n.client.pendingCommand){setTimeout(()=>{r()},250);return}}let S=n.client.view,A=n.expected(),F=A.requestId;try{await n.client.submit({operation:"shown",...A})}catch(q){if(!(q instanceof b)||q.code!=="CONFLICT"||q.status!==409||n.client.pendingCommand)throw q;await n.client.get();let u=n.client.view;if(n.stopped||n.reviewing||n.key!==p||!u||!S||u.id!==S.id||u.source.versionId!==S.source.versionId||u.nodeId!==A.nodeId||u.visit!==A.visit||u.revision<=A.revision||u.stopped||!u.screen&&(!u.paywall||u.paywall.receiptId!==S.paywall?.receiptId)||!["running","waiting"].includes(u.status)||n.client.pendingCommand)throw q;let k=n.expected();F=k.requestId,await n.client.submit({operation:"shown",...k})}await w(p,F)})();P(p,v)};r()}function m(){if(I)return I;let p=n.client.pendingCommand;if(p?.operation!=="shown")return null;let r=n.key;return e.add(r),P(r,(async()=>{await n.client.retry(),await w(r,p.requestId)})())}return{report:o,settled:m,get inFlight(){return I}}}function pn(n){let E={},e=new Map;async function I(w){let P=n.client.view,o=P?.screen,m=o?.customerData.nodes[w.nodeId];if(n.stopped||n.busy||!P||!o||!m)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(w.action)){let q=n.document,u=q?We(q,w.nodeId):null,k=u?.type==="customer_data"?u.data.outputs?.[w.action]:void 0;k&&o.outputs.includes(k)?await n.perform(()=>n.client.submit({operation:"submit",...n.expected(),input:{type:"screen",output:k,answers:n.answers,selection:w.value?{[w.nodeId]:w.value}:{}}})):await n.onIntent?.(w,P);return}let r=w.action.startsWith("sources_")?m.resources.find(q=>q.key===w.value):null;if(w.action.startsWith("sources_")&&!r)throw new b("INVALID_REQUEST","Choose a current resource");let v=`${P.visit}:${w.nodeId}:${r?.key??""}`,S=e.get(v)??[null],F=E[w.nodeId]??{page:1,after:null,filter:"all",...r?{resourceKey:r.key}:{}};if(w.action==="filter"){let q=w.value;if(!q||!(m.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(q))throw new b("INVALID_REQUEST","Unknown data filter");F={page:1,after:null,filter:q},S.splice(0,S.length,null)}else if(w.action==="next"||w.action==="sources_next"){let q=r?.sources.at(-1),u=r?q?{kind:"ledger",cursor:{at:q.detail[0],id:q.id,type:"source"}}:null:o.dataCursors[w.nodeId];if(!u||!r&&!m.hasNext)return;S[F.page]=u,F={...F,page:F.page+1,after:u}}else if(w.action==="previous"||w.action==="sources_previous"){if(F.page<=1)return;F={...F,page:F.page-1,after:S[F.page-2]??null}}e.set(v,S),E={...E,[w.nodeId]:F},await n.perform(()=>n.client.get({nodeId:P.nodeId,visit:P.visit,revision:P.revision,components:E}))}return{get queries(){return E},intent:I,reset(){E={},e.clear()}}}function fn(n){let{doc:E,holder:e,reviewHolder:I,mountScreenPreview:w}=n,P=!1,o,m=0,p=null,r="",v,S=new Map,A=u=>u?`${u.id}:${u.nodeId}:${u.visit}:${u.revision}:${u.paywall?.quote?.operationId??""}`:"";async function F(u){if(n.stopped||!n.client.review||P&&u===o&&v?.active)return;let k=!P||u!==o;P||(r=A(n.client.view),S.set(r,structuredClone(n.answers))),P=!0,o=u,e.hidden=!0,n.suspend(!0),I.hidden=!1;let O=++m;k&&(v?.finish("dismissed"),p?.destroy(),p=null,I.replaceChildren(),v=_e(I,n.loadingOptions,"funnel",()=>{q()}));let T=k?v:void 0;try{if(T?.start(!1,n.client.view?.locale),O!==m||n.stopped)return;let D=n.client.review(u),z=await(T?.wait(D,qe)??D);if(n.stopped||O!==m||!P)return;if(!z.review)throw new b("INVALID_RESPONSE","Historical projection is missing");p?.destroy(),p=null,T||I.replaceChildren();let N=E.createElement("div"),f=T?Le(N,I):()=>{};I.append(N);let M=z.run.locale.startsWith("zh"),L=E.createElement("p");L.textContent=M?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",N.append(L);for(let[U,Y]of z.review.pages.entries()){let _=E.createElement("button");_.type="button",_.textContent=M?`\u7B2C ${U+1} \u9875`:`Page ${U+1}`,_.onclick=()=>{F(Y.receiptId)},N.append(_)}if(z.review.page){let U=z.review.page,Y=E.createElement("div");Y.inert=!0,N.append(Y),p=w(Y,{mode:"live",rendererUrl:n.client.webViewUrl,title:U.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{O===m&&!n.stopped&&T?.present(f)},onError:C=>{if(O!==m||n.stopped)return;let G=new Error(C);T?.finish("error",G),p?.destroy(),p=null,N.remove(),n.fail(G)},onEscape:()=>{q()}});let _=p;if(_.update(U.document,z.run.locale,{serverInput:{bindings:U.inputs,answers:U.answers,values:U.values}}),await _.ready,n.stopped||O!==m||!P)return}let x=M?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"};for(let U of[...z.review.coupons.map((Y,_)=>`${M?"\u4F18\u60E0\u5238":"Coupon"} ${_+1}: ${x[Y.status]}`),...z.review.purchases.map((Y,_)=>`${M?"\u8D2D\u4E70":"Purchase"} ${_+1}: ${sn(Y.status,M)}`)]){let Y=E.createElement("p");Y.textContent=U,N.append(Y)}z.review.page||T?.present(f),n.client.view&&await n.enqueue(n.client.view)}catch(D){if(O!==m||n.stopped)return;T?.finish("error",D),p?.destroy(),p=null,I.replaceChildren(),n.fail(D)}}async function q(){if(!P||n.stopped||!n.client.review)return;let u=++m;v?.finish("dismissed");try{if(await n.client.review(),n.stopped||u!==m)return;P=!1,m++,v?.finish("dismissed"),p?.destroy(),p=null,I.replaceChildren(),I.hidden=!0,e.hidden=!1;let k=n.client.view;A(k)!==r?(S.set(r,structuredClone(n.answers)),n.resetScreen()):(S.delete(r),n.suspend(!1)),k&&await n.enqueue(k)}catch(k){if(u!==m||n.stopped)return;p?.destroy(),p=null,I.replaceChildren(),n.fail(k)}}return{get active(){return P},get receipt(){return o},open:F,exit:q,get drafts(){return new Map([...S].map(([u,k])=>[u,structuredClone(k)]))},stop(){P=!1,m++,v?.finish("dismissed"),p?.destroy(),p=null,I.replaceChildren(),I.hidden=!0,e.hidden=!1}}}function mn(n){if(!n.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let E=n.client.pageExperiments.bind(n.client),e=!1,I=!1,w=0,P=!1,o=!1,m="",p=()=>{let f=n.client.view;return JSON.stringify([f?.id,f?.source.versionId,f?.visit,f?.revision,f?.status,f?.stopped])},r=new Map,v=new Set,S={},A=new Map,F=an(n.appManifestRelease),q=()=>{for(let f of r.values())f.effect.revert();r.clear()},u=()=>{q();for(let f of A.values())f();A.clear()};function k(f){if(e||v.has(f))return;v.add(f);let M=w;E(n.appManifestRelease,[f]).catch(L=>{v.delete(f),!e&&M===w&&le(n.onError,L)})}async function O(){if(e)return;m=p();let f=n.client.view;if(!f||f.stopped||!["running","waiting"].includes(f.status)){w++,u();return}if(document.visibilityState==="hidden")return;if(P){o=!0;return}P=!0;let M=++w,L=`${f.id}:${f.visit}:${f.revision}`,x=location.href;try{let[U,{applyVisualVariation:Y}]=await Promise.all([E(n.appManifestRelease),import("./visual-dom-7IF7ITAK.js")]),_=n.client.view;if(e||M!==w||!_||_.stopped||!["running","waiting"].includes(_.status)||`${_.id}:${_.visit}:${_.revision}`!==L||location.href!==x)return;let C=new Set,G=new Set;for(let j of U.assignments){let ie=`${U.payload.environmentId}:${j.experimentKey}`;if(G.add(ie),A.has(ie)||A.set(ie,un(ie,S)),!!j.inExperiment)for(let i of U.payload.experiments){if(i.key!==j.experimentKey||!Be(location.href,i.urlPatterns??[]))continue;let c=i.meta?.findIndex(Q=>Q.key===j.variationKey)??-1,a=i.variations[c];if(!a?.renderGuard)continue;let d=j.receiptId+":"+i.changeId,y=JSON.stringify([j.variationKey,a]);C.add(d);let h=r.get(d);if(h?.signature===y){h.effect.applied&&k(j.receiptId);continue}r.get(d)?.effect.revert(),r.delete(d);let B=Y(a,{requireUniqueTargets:!0,boundVariations:i.variations,allowJs:!1,onApplied:()=>k(j.receiptId),onError:Q=>le(n.onError,Q)});r.set(d,{signature:y,effect:B}),B.applied&&k(j.receiptId)}}for(let[j,ie]of r)C.has(j)||(ie.effect.revert(),r.delete(j));for(let[j,ie]of A)G.has(j)||(ie(),A.delete(j))}catch(U){M===w&&u(),!e&&M===w&&le(n.onError,U)}finally{P=!1,o&&!e&&(o=!1,O())}}let T=n.client.subscribe(()=>{if(p()===m)return;m=p(),w++;let f=n.client.view;(!f||f.stopped||!["running","waiting"].includes(f.status))&&u(),I&&O()}),D=ln(()=>{w++,u(),I&&O()}),z=()=>{w++,q()};document.addEventListener("visibilitychange",z);let N=Ve({document,run:async()=>{I&&await O()},delay:()=>I&&!e?15e3:void 0});return{async start(){I||e||(I=!0,await N.refresh())},refresh:O,destroy(){e=!0,w++,N.destroy(),document.removeEventListener("visibilitychange",z),T(),D(),u(),F.destroy()}}}var Qe=5e3;async function rt(n,E){let e=E,[{mountScreenPreview:I},{showPaywall:w}]=await Promise.all([import("./screen-renderer-TEVGVUT5.js"),import("./paywall-5Q4VATYY.js")]),P=e.client.identitySignal;e.signal?.throwIfAborted(),P?.throwIfAborted();let o=e.appManifestRelease?mn({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;o?.start();let m=n.ownerDocument,p=on(m),r=m.createElement("section"),v=m.createElement("div"),S=m.createElement("div"),A=m.createElement("div"),F=m.createElement("button");A.hidden=!0,F.type="button";let q=m.createElement("p"),u=m.createElement("p"),k=m.createElement("button"),O=m.createElement("button"),T=m.createElement("button"),D=m.createElement("dialog"),z;r.dataset.indianaFunnel="",r.setAttribute("aria-busy","false"),r.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",S.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",q.setAttribute("role","status"),u.setAttribute("role","alert"),u.hidden=!0,k.type=O.type=T.type="button",S.append(k,q,u,T,F,O),r.append(v,A,S),n.append(r);let N=null,f=null,M=null,L="",x="",U="",Y="",_="",C=!1,G=0,j=!1,ie="",i=null,c=Promise.resolve(),a=!e.client.view,d,y,h,B="",Q,$=!1,Z=null,ce=!1,ye=()=>e.client.pendingCommand?.operation==="close",re=null,K=null,Je=Ve({document:m,run:async()=>{(!f?.observing||e.client.pendingCommand)&&await Ue()},delay:()=>{if(!(C||!M||!["running","waiting"].includes(M.status)&&!e.client.pendingCommand)&&!(f?.observing&&!e.client.pendingCommand))return M.pendingRequest||e.client.pendingCommand?1500:Qe},hiddenDelay:()=>!C&&e.client.pendingCommand?15e3:void 0}),X=null;function Me(){return K&&e.client.hasDurableJournal===!0&&X?.acknowledged===!0&&X.operationId===K.operationId&&e.client.view?.id===X.runId&&e.client.view?.status==="closed"&&e.client.view.revision===X.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?K:null}function ze(t){let s=t.run.paywall;if(X&&t.settlement?.requestId===X.requestId&&t.settlement.state==="settled"&&t.settlement.operationId===null&&t.run.id===X.runId&&t.run.status==="closed"&&!t.run.pendingRequest&&t.run.revision===X.revision+1&&t.run.nodeId===X.nodeId&&t.run.visit===X.visit&&s?.receiptId===X.receiptId&&s.selectionGeneration===X.selectionGeneration&&(s.quote?.operationId??null)===X.operationId&&(s.operation?.operationId??s.quote?.operationId??null)===X.operationId){let l=X.operationId===null&&s.selectionGeneration===0&&!s.quote&&!s.operation&&!s.purchaseRequestId,ue=Te({quote:s.quote,operation:s.operation,requestId:s.purchaseRequestId,pending:!1,destroyed:!1,canReselect:s.canReselect});(l||s.canReselect===!0&&ue.type==="native")&&(X.acknowledged=!0)}}let Ce=null,De=new Set,pe={},oe=(t,s=null)=>{C||(Ce=s,u.textContent=t instanceof Error?t.message:"Request failed",u.hidden=!1,T.hidden=e.client.pendingCommand===null,le(e.onError,t))};function he(){let t=e.client.view;if(!t)throw new b("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let V=fn({client:e.client,doc:m,holder:v,reviewHolder:A,mountScreenPreview:I,loadingOptions:e,get stopped(){return C},get answers(){return pe},suspend(t){f?.setSuspended(t)},resetScreen(){L="",x="",U=""},enqueue:fe,fail:oe}),Se=cn({client:e.client,expected:he,fail:oe,get stopped(){return C},get reviewing(){return V.active},get key(){return L},get busy(){return G},get staleRead(){return i}}),Fe=pn({client:e.client,expected:he,perform:Re,onIntent:e.onCustomerDataIntent,get stopped(){return C},get busy(){return G},get document(){return N?.document},get answers(){return pe}}),ke=t=>`${t.id}:${t.nodeId}:${t.visit}`,Pe=t=>t&&(t.screen||t.paywall)?ke(t):"";function Ie(){let t=e.client.view;k.disabled=!V.active&&(G>0||!!e.client.pendingCommand||!t?.canBack||t.stopped||!["running","waiting"].includes(t.status)||!Pe(t)||x!==Pe(t))}async function je(t){if(!t)return;let s=e.client.view;await t;let l=e.client.view;if(!s||!l||l.id!==s.id||l.nodeId!==s.nodeId||l.visit!==s.visit||l.stopped||!["running","waiting"].includes(l.status))throw new b("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Re(t,s=!1){if(!((G||ce||re||K)&&!s||C||V.active&&!s)){G++,r.setAttribute("aria-busy","true"),Ie(),u.hidden=!0,Ce=null;try{if(s||await je(Se.inFlight),C)return;let l=await t();C||await fe(e.client.view??l.run)}catch(l){oe(l,e.client.pendingCommand?.requestId??null)}finally{G=Math.max(0,G-1),r.setAttribute("aria-busy",String(G>0)),C||(T.hidden=e.client.pendingCommand===null,Ie())}}}function Ee(){Je.schedule()}async function Ue(){if(!(C||j||G)){if(V.active){await V.open(V.receipt);return}j=!0;try{let t=e.client.pendingCommand;t&&e.client.settle&&await e.client.settle(t.requestId);let s=e.client.view,l=Fe.queries,ue=await e.client.get(s?.screen&&Object.keys(l).length?{nodeId:s.nodeId,visit:s.visit,revision:s.revision,components:l}:void 0);!C&&l===Fe.queries&&await fe(e.client.view??ue.run)}catch(t){oe(t)}finally{j=!1}}}function Oe(t,s){if(d?.active)return d;let l=_e(n,e,"funnel",()=>{C||$||($=!0,l.finish("dismissed"),ge(),r.hidden=!0,e.client.view?be().finally(se):se())});return d=l,l.start(t,s),l}function $e(){clearTimeout(Q?.timeout),Q=void 0}function ge(){$e(),y?.abort(),y=void 0,N?.destroy(),N=null,f?.destroy(),f=null,h?.(),h=void 0,D.open&&D.close(),v.replaceChildren(),L="",x="",U="",_=""}function He(t){let s=t.screen?.presentation;if(!s||s.type==="inline"){D.open&&D.close(),r.parentElement!==n&&n.append(r);return}r.parentElement!==D&&(D.append(r),n.append(D));let l={sm:420,md:640,lg:900};D.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in s?l[s.size]+"px":"100vw"}`,D.setAttribute("aria-label",(z?.screen===t.screen?.content.document.name?z?.label:void 0)??N?.document?.name??t.screen?.content.document.name??"Funnel")}async function wn(t){if(C||$||ce&&(ye()||["running","waiting"].includes(t.status)))return;M=t,Ce&&e.client.pendingCommand?.requestId!==Ce&&(u.hidden=!0,Ce=null);let s=t.locale.startsWith("zh");if(F.textContent=s?"\u56DE\u770B":"History",F.hidden=!e.client.review,k.textContent=V.active?s?"\u8FD4\u56DE\u5F53\u524D":"Return to current":s?"\u8FD4\u56DE":"Back",O.textContent=s?"\u5173\u95ED":"Close",T.textContent=s?"\u91CD\u8BD5":"Retry",Ie(),T.hidden=e.client.pendingCommand===null,q.textContent=t.pendingRequest?s?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?s?"\u7B49\u5F85\u4E2D":"Waiting":"",ie!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(ie=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,le(e.onState,structuredClone(t))),C||$)return;if((!t.pendingRequest||ce&&t.status==="closed")&&["closed","ineligible","failed"].includes(t.status)){se();return}if(t.stopped||e.client.configurationReady===!1){V.stop(),ge(),d?.finish("skipped"),r.hidden=!0,Ee();return}if(r.hidden=!1,V.active){Ee();return}let l=Pe(t),ue=e.client.view;if(ue&&ue.revision>t.revision&&Pe(ue)!==l)return;let Ge=!t.instruction&&!t.pendingRequest&&t.nodeType==="screen"&&["running","waiting"].includes(t.status);l!==L&&(L&&d?.finish("dismissed"),ge(),L=l,pe={...t.answers},Fe.reset());let me=ke(t);if(B===me){r.hidden=!0;return}if(Ge&&!l){r.hidden=!0;let R=Oe(!0,t.locale);!C&&!$&&Q?.key!==me&&($e(),Q={key:me,timeout:setTimeout(()=>{let g=e.client.view;if(!R.active||!g||ke(g)!==me)return;B=me;let ne=new Error("Funnel screen preparation timed out");R.finish("error",ne),ge(),oe(ne)},qe)}),Ee();return}$e();let te=R=>{let g=e.client.view;return!C&&!$&&!Z&&!R.aborted&&e.client.configurationReady!==!1&&!!g&&!g.stopped&&!["closed","ineligible","failed"].includes(g.status)&&Pe(g)===l},ee=(R,g)=>{te(g)&&(B=l,d?.finish("error",R),ge(),r.hidden=!0,oe(R))};if(l||(He(t),t.instruction?.type!=="event"&&t.instruction?.type!=="open_url"&&d?.finish("skipped")),t.screen){let R=t.screen.content;if(!N){let J=t.screen.presentation.type!=="inline",we=Oe(J,t.locale);if(C||$)return;let ae=(y=new AbortController).signal;He(t),h=J?rn(D):Le(r,n),N=I(v,{mode:"live",rendererUrl:e.client.webViewUrl,title:R.document.name,onAction(de,ve={},hn={}){if(V.active||!te(ae)||x!==l)return;pe={...pe,...hn};let In=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:Ne})=>Object.hasOwn(pe,Ne)).map(({variable:Ne})=>[Ne,pe[Ne]]));Re(()=>e.client.submit({operation:"submit",...he(),input:{type:"screen",output:de,answers:In,selection:ve}}))},onAnswers:de=>{V.active||!te(ae)||x!==l||(pe={...pe,...de})},onCustomerDataIntent:de=>{V.active||!te(ae)||x!==l||Fe.intent(de).catch(oe)},onEscape:()=>{!te(ae)||x!==l||V.active||re||K||be()},onError:de=>{let ve=new Error(de);x===l?oe(ve):ee(ve,ae)},onRendered:de=>{if(!(!te(ae)||x===l))try{we.present(ve=>{h?.(),h=void 0,de&&(z={screen:R.document.name,label:de},D.setAttribute("aria-label",de)),J&&(D.showModal(),!ve&&e.loading!=="host"&&tn(D,t.screen.presentation.type)),x=l,Ie()}),te(ae)&&Se.report(l)}catch(ve){ee(ve,ae)}}})}let g={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:pe,values:t.screen.values}},ne=JSON.stringify([R,t.locale,g.parameters,t.screen.inputs,t.screen.values]);if(ne!==U)N.update(R.document,t.locale,g),U=ne,Y=JSON.stringify(g.capabilities),_=JSON.stringify(g.customerData);else{let J=JSON.stringify(g.capabilities);J!==Y&&(N.updateCapabilities(g.capabilities),Y=J),JSON.stringify(g.customerData)!==_&&(N.updateCustomerData(g.customerData),_=JSON.stringify(g.customerData))}let W=N;if(W)try{await(d?.wait(W.ready)??W.ready)}catch(J){y&&ee(J,y.signal)}}else if(t.paywall&&!f){let R=Oe(!0,t.locale);if(C||$)return;let g=(y=new AbortController).signal;He(t);let ne=await w(v,{loading:"host",signal:g,canInteract:()=>te(g)&&!V.active&&!re&&!K,beforeAction:async()=>{G++;try{await je(Se.settled()),u.hidden=!0,Ce=null}finally{G=Math.max(0,G-1)}},start:()=>dn(e.client),onObservationChange:Ee,onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,resolveOfferId:e.resolveOfferId,onEvent:e.onEvent,onOpenUrl:W=>e.onOpenUrl?e.onOpenUrl({receiptId:t.paywall.receiptId,url:W,openIn:"same_window"}):m.defaultView?.location.assign(W),onAction:async W=>{if(V.active)return;let J=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:e.client.view?.revision??t.revision,input:{type:"screen",output:W,answers:{}}});await fe(e.client.view??J.run)},onError:W=>{x===l?oe(W):ee(W,g)}},{present(W){te(g)&&(R.present(()=>{W(),x=l,Ie()}),te(g)&&Se.report(l))},async dismiss(){C||g.aborted||V.active||re||K||!ce&&!te(g)||(ce=!0,await be())}}).catch(W=>(ee(W,g),null));!te(g)&&!(ce&&!C&&!g.aborted)?ne?.host?.destroy():ne&&(f=ne.host,f?.setSuspended(V.active))}if(C||$)return;Ie();let H=t.instruction;if(H&&(H.type==="open_url"||H.type==="event")&&!De.has(H.receiptId)){let R=m.createElement("button");R.type="button",R.textContent=H.type==="open_url"?`${s?"\u524D\u5F80":"Continue to"} ${new URL(H.url).host}`:s?"\u7EE7\u7EED":"Continue",R.onclick=()=>{let g=he(),ne=H.type==="open_url"&&!e.onOpenUrl&&H.openIn==="new_window"?yn(H.url):null;Re(async()=>{let W="success";if(H.type==="open_url")if(e.onOpenUrl)try{W=await e.onOpenUrl({receiptId:H.receiptId,url:H.url,openIn:H.openIn})===!1?"failed":"opened"}catch(we){le(e.onError,we),W="failed"}else W=H.openIn==="new_window"&&!ne?"failed":"opened";if(H.type==="event"){if(!e.onEvent)throw new b("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(H.event)}if(C||e.client.view?.nodeId!==g.nodeId||e.client.view.visit!==g.visit)throw new b("PRECONDITION_FAILED","The client action visit changed");let J=await e.client.submit({operation:"submit",...g,input:{type:"client_action",receiptId:H.receiptId,outcome:W}});return De.add(H.receiptId),H.type==="open_url"&&!e.onOpenUrl&&H.openIn==="same_window"&&m.defaultView?.location.assign(H.url),J})},d?.active?d.present(()=>v.replaceChildren(R)):v.replaceChildren(R)}!t.pendingRequest&&t.status==="completed"&&!De.has(`complete:${t.id}`)&&(De.add(`complete:${t.id}`),le(e.onComplete,structuredClone(t))),Ee()}function yn(t){let s=m.defaultView?.open(t,"_blank")??null;return s&&(s.opener=null),s}function fe(t){return Ie(),c=c.catch(()=>{}).then(async()=>{try{await wn(t)}catch(s){throw d?.active&&(B=ke(t),d.finish("error",s),ge(),r.hidden=!0),s}}),c}let gn=e.client.subscribe(t=>{a||(!ce&&(t.stopped||e.client.configurationReady===!1||L&&x!==L&&(Pe(t)!==L||["closed","ineligible","failed"].includes(t.status)))&&(ge(),d?.finish("dismissed"),r.hidden=!0),fe(t).catch(oe))}),vn=e.client.subscribeError?.(oe);function be(t){if(Z)return Z;if(C||!t&&(re||K))return Promise.resolve();let s=!t&&ye();return!s&&e.client.view&&!["running","waiting"].includes(e.client.view.status)?(M=e.client.view,se(),Promise.resolve()):(Z=Re(async()=>{let l=s?await e.client.retry():await e.client.submit({operation:"close",...t??he()});return t&&ze(l),l},!0).then(()=>{let l=e.client.view;l?.status==="closed"&&!ye()&&(M=l,se())}).finally(()=>{Z=null}),Z)}function se(){o?.destroy(),!C&&(C=!0,e.signal?.removeEventListener("abort",se),P?.removeEventListener("abort",se),d?.finish("dismissed"),Je.destroy(),gn(),vn?.(),ge(),V.stop(),D.remove(),r.remove(),p(),le(e.onDismiss,M?structuredClone(M):null))}k.onclick=()=>{if(!k.disabled){if(V.active){V.exit();return}Re(()=>e.client.submit({operation:"back",...he()}))}},F.onclick=()=>{V.open()},O.onclick=()=>{d?.active?d.dismiss():re||be()},T.onclick=()=>{ye()?be():Re(()=>e.client.retry())},D.addEventListener("cancel",t=>{t.preventDefault(),d?.active?d.dismiss():re||be()}),e.signal?.addEventListener("abort",se,{once:!0}),P?.addEventListener("abort",se,{once:!0});try{let t=e.client.view;if(t)((e.client.viewAgeMs??Qe)>=Qe||t.instruction?.type==="evaluate_segment")&&(i=Ue().finally(()=>{i=null})),await fe(t);else{r.hidden=!0;let s=Oe(e.client.view?.screen?.presentation.type!=="inline",e.client.view?.locale);if(C||$)throw new DOMException("Presentation cancelled","AbortError");let l=await s.wait(e.client.get(),qe);a=!1,await fe(e.client.view??l.run)}}catch(t){throw d?.finish("error",t),se(),t}return{destroy:se,refresh:Ue,get recovery(){let t=Me();if(t)return t;if(!C&&!G&&!ce&&!re&&f){let s=f.recovery;if(s.type!=="native")return s}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??K?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(re)return re;let t=Me();if(t)return Promise.resolve(t);let s=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??K?.operationId??null,l=()=>({type:"recover",operationId:s,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let ee=f?.recovery;return Promise.resolve(ee&&ee.type!=="native"&&ee.type!=="cancel"?ee:l())}let ue=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(ee=>ee.operation==="close");if(C&&!(ue||K&&e.client.view?.status==="closed")||G||j||Z||V.active||!f&&!K&&!ue)return Promise.resolve(l());let Ge=f,me=(async()=>{try{if(!K&&ue){let R=await e.client.retry();return await fe(e.client.view??R.run),l()}if(!K){let R=await Ge.prepareFallback();if(R.type!=="native")return R;if(e.client.hasDurableJournal!==!0)return l();K=R}let ee=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(ee.length){let R=ee.find(ne=>ne.operation==="close");if(!R||!X||R.requestId!==X.requestId)return l();let g=await e.client.retry();ze(g),await fe(e.client.view??g.run)}else{let R=e.client.view,g=R?.paywall;if(!R||!g||g.selectionGeneration===void 0||(g.quote?.operationId??null)!==K.operationId||K.operationId!==null&&g.canReselect!==!0)return l();let ne=g.selectionGeneration,W=await e.client.get();await fe(e.client.view??W.run);let J=e.client.view,we=J?.paywall;if(!J||!we||!["running","waiting"].includes(J.status)||J.stopped||J.id!==R.id||J.nodeId!==R.nodeId||J.visit!==R.visit||we.receiptId!==g.receiptId||we.selectionGeneration!==ne||(we.quote?.operationId??null)!==K.operationId||K.operationId!==null&&we.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return l();let ae=he();X={runId:J.id,operationId:K.operationId,revision:ae.revision,requestId:ae.requestId,nodeId:J.nodeId,visit:J.visit,receiptId:we.receiptId,selectionGeneration:ne,acknowledged:!1},await be(ae)}let H=Me();return H?(se(),H):l()}catch(ee){return oe(ee),l()}})();re=me;let te=()=>{re===me&&(re=null)};return me.then(te,te),me},review:V.open,exitReview:V.exit,get unappliedDrafts(){return V.drafts}}}export{mn as a,rt as b};
|
|
1
|
+
import{a as Ve,c as sn}from"./chunk-JGG4R75K.js";import{d as tn,f as qe,g as _e,h as rn,i as Le,k as on}from"./chunk-6DTGBDYG.js";import{a as Ke,b as Xe,c as Ze,d as en,e as nn,f as Te}from"./chunk-YAVWELIV.js";import{a as b}from"./chunk-QVGTHPWT.js";import{b as an,e as un}from"./chunk-SLUA7ABW.js";import{d as ln}from"./chunk-PKLLZXNM.js";import{Z as xe,ma as Ae}from"./chunk-KRQESEG2.js";import{a as oe}from"./chunk-DSPLGTQI.js";import{Da as We,I as Be,Na as Ye}from"./chunk-HDVLCRC6.js";async function dn(n){let{session:E,load:e}=bn(n);try{return await e(),E}catch(I){throw E.destroy(),I}}function bn(n){let E=n.view;if(!E?.paywall)throw new b("INVALID_REQUEST","The current node is not a Paywall");let e=E.paywall.receiptId,I=E.nodeId,w=E.visit,P=E.paywall.resolution,o=E.paywall,m="document"in P?{document:P.document,offering:P.offering,capabilities:P.capabilities}:null;function p(){let i=o.resolution;return"document"in i?i:m&&{...i,document:m.document,offering:m.offering,capabilities:Ke(i.capabilities,m.capabilities)}}function r(i){if(!Xe(i,P))throw new b("INVALID_RESPONSE","The pinned Paywall binding changed")}let v=!1,S=new Set,A=null;function F(){let i=p();if(i&&!v)for(let c of S)oe(c,structuredClone(i))}async function q(){L();let i=p();if(i)return structuredClone(i);if(!A){let c=(async()=>{if("document"in o.resolution||!n.resolvePaywall)throw new b("INVALID_RESPONSE","Public Paywall reader is unavailable");let d=await n.resolvePaywall(o.resolution);return L(),r(d),m={document:d.document,offering:d.offering,capabilities:d.capabilities},F(),p()})();A=c;let a=()=>{A===c&&(A=null)};c.then(a,a)}return A.then(c=>structuredClone(c))}let u=new AbortController,O=(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===I&&i.visit===w&&i.input.type==="paywall_quote")?.requestId??E.paywall.purchaseRequestId,T=0,D=null,j=new Set,N=null,f=new Map;function M(i){if(i.purchase&&i.purchase.receiptId!==e)throw new b("INVALID_RESPONSE","Purchase receipt changed");let c=i.run.paywall;return i.purchase??(c?.receiptId===e?c:null)}function L(){if(v)throw new b("IDENTITY_CHANGED","Paywall presentation has closed")}function x(i,c,a){if(L(),c!==T||a!==void 0&&o.quote?.operationId!==a)return!1;let d=o.selectionGeneration??0,y=i.run.paywall;if(y?.receiptId===e){if((y.selectionGeneration??0)<(o.selectionGeneration??0))return!1;r(y.resolution)}let h=M(i),W=y?.receiptId===e&&(y.selectionGeneration??0)>d,J=W?h?.quote??null:h?.quote??o.quote,$=h?.operation??(J?.operationId===o.quote?.operationId?o.operation:null);return J&&$&&Ze($,{operationId:J.operationId},"Purchase operation changed"),(W||J?.operationId!==o.quote?.operationId)&&(T++,y?.receiptId===e&&(O=y.purchaseRequestId)),o={...o,...y?.receiptId===e?y:{},quote:J,operation:nn(o.operation,$,!0)},F(),!0}function U(i,c,a){return new Promise((d,y)=>{let h=!1,W=()=>{clearTimeout(ce),u.signal.removeEventListener("abort",Z)},J=ye=>{h||(h=!0,W(),d(ye))},$=ye=>{h||(h=!0,W(),y(ye))},Z=()=>$(new b("IDENTITY_CHANGED","Paywall presentation has closed")),ce=setTimeout(()=>$(new b("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a)),Math.max(0,c-Date.now()));u.signal.addEventListener("abort",Z,{once:!0}),u.signal.aborted&&Z(),i.then(J,$)})}function Y(i){return new Promise(c=>{let a=()=>{clearTimeout(d),u.signal.removeEventListener("abort",a),c()},d=setTimeout(a,i);u.signal.addEventListener("abort",a,{once:!0}),u.signal.aborted&&a()})}function _(i,c){L();let a=f.get(i)??n.pendingCommands?.find(h=>h.requestId===i)??n.pendingCommand;if(a?.operation==="submit"&&a.requestId===i&&a.nodeId===I&&a.visit===w){c.type==="paywall_quote"&&a.input.type==="paywall_quote"&&a.input.predecessor&&!c.predecessor&&(c={...c,predecessor:a.input.predecessor});let h=Ae.parse(a),W=Ae.parse({...a,input:c});if(h.operation!=="submit"||W.operation!=="submit"||JSON.stringify(h.input)!==JSON.stringify(W.input))throw new b("CONFLICT","A purchase request cannot change its input");return f.set(i,h),h}let d=n.view;if(!d||d.nodeId!==I||d.visit!==w||d.paywall?.receiptId!==e)throw new b("PRECONDITION_FAILED","The Paywall visit has changed");let y=Ae.parse({operation:"submit",requestId:i,nodeId:I,visit:w,revision:d.revision,input:structuredClone(c)});if(y.operation!=="submit")throw new b("INVALID_REQUEST","A purchase submission is required");return f.set(i,y),y}async function C(i,c){L();let{requestId:a,input:d}=i,y=Date.now()+3e4;j.add(a);try{let h=await U(n.submit(i),y,a);for(;h.run.pendingRequest?.requestId===a&&Date.now()<y&&!v&&(await Y(Math.min(1e3,y-Date.now())),!(v||Date.now()>=y));)h=await U(n.resume(a),y,a);if(v)throw new b("IDENTITY_CHANGED","Paywall presentation has closed");if(h.run.pendingRequest?.requestId===a)throw new b("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a);if(!x(h,c,d.type==="paywall_confirm"||d.type==="paywall_cancel"?d.operationId:void 0))throw new b("PRECONDITION_FAILED","The purchase selection has changed");N===a&&(N=null)}catch(h){throw N=a,h instanceof b&&h.code==="COMMAND_PENDING"&&h.status===void 0&&f.delete(a),h}finally{j.delete(a)}}async function Q(i){if(!o.quote)throw new b("INVALID_REQUEST","A quoted purchase is required");let c=i==="confirm"?"paywall_confirm":"paywall_cancel",a=[...f.values(),...n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])].find(y=>y.operation==="submit"&&y.input.type===c&&"operationId"in y.input&&y.input.operationId===o.quote.operationId),d=a?.operation==="submit"&&a.input.type===c&&"operationId"in a.input&&a.input.operationId===o.quote.operationId?a.requestId:crypto.randomUUID();if(await C(_(d,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.quote.operationId}),T),!o.operation)throw new b("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(o.operation)}let B={get view(){return structuredClone(p())},get quote(){return o.quote?structuredClone(o.quote):null},get operation(){return o.operation?structuredClone(o.operation):null},get webViewUrl(){return n.webViewUrl},get canReselect(){return o.canReselect===!0},get recovery(){let i=n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[]),c=n.pendingPurchase;if(c&&(c.receiptId!==e||c.operationId!==o.quote?.operationId))return{type:"recover",operationId:c.operationId,requestId:i[0]?.requestId??null};let a=Te({quote:o.quote,operation:o.operation,requestId:i[0]?.requestId??N??O,pending:j.size>0||i.length>0||N!==null,destroyed:v,canReselect:o.canReselect});return a.type==="recover"&&a.requestId===null&&!v&&n.hasDurableJournal===!0&&!o.quote&&!o.operation&&(o.selectionGeneration??0)===0&&!c&&!i.length&&!j.size&&!O?{type:"native",operationId:null}:a},get pendingCancellation(){return!v&&(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===I&&i.visit===w&&i.input.type==="paywall_cancel"&&i.input.operationId===o.quote?.operationId)},subscribe(i){return v?()=>{}:(S.add(i),()=>S.delete(i))},async refresh(){L();let i=T,c=await n.get();if(x(c,i),c.run.paywall?.receiptId!==e)throw new b("PRECONDITION_FAILED","Paywall presentation has changed");return q()},preview(i){let c=p();if(!c)return Promise.reject(new b("PRECONDITION_FAILED","Load the Paywall presentation first"));if(O&&O!==i.requestId&&(D||o.canReselect!==!0))return Promise.reject(new b("COMMAND_PENDING","Retry the original purchase before starting another"));let a=c.document.buttons[i.actionId],d=a?.type==="checkout"?xe(a.product,i.selection,c.capabilities):null;if(!d)return Promise.reject(new b("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let y=Ye(c.document.screen,d,i.selection,c.capabilities),h=O!==i.requestId&&(o.selectionGeneration??0)>0?{operationId:o.quote?.operationId??null,generation:o.selectionGeneration??0}:void 0;if(h&&o.canReselect!==!0)return Promise.reject(new b("COMMAND_PENDING","Original purchase requires authoritative termination"));let W;try{W=_(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:d,...Object.keys(y).length?{featureQuantities:y}:{},...h?{predecessor:h}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}})}catch(Z){return Promise.reject(Z)}if(O===i.requestId&&D)return D;O!==i.requestId&&T++;let J=T;O=i.requestId;let $=(async()=>{if(await C(W,J),!o.quote)throw new b("INVALID_RESPONSE","The accepted quote is missing");return en(o.quote,{productVersionId:d,featureQuantities:y},"The selected purchase changed"),structuredClone(o.quote)})();return D=$,$.then(()=>{D===$&&(D=null)},Z=>{D===$&&(D=null),O===i.requestId&&n.pendingCommand?.requestId!==i.requestId&&Z instanceof b&&Z.status!==void 0&&Z.status<500&&![401,425].includes(Z.status)&&(O=null)}),$},confirm:()=>Q("confirm"),cancel:()=>Q("cancel"),async read(){if(L(),!o.quote)throw new b("INVALID_REQUEST","A quoted purchase is required");let i=o.quote.operationId,c=T,a=n.pendingCommands?.find(J=>J.operation==="submit"&&(J.input.type==="paywall_confirm"||J.input.type==="paywall_cancel")&&J.input.operationId===i)??n.pendingCommand;a?.operation==="submit"&&(a.input.type==="paywall_confirm"||a.input.type==="paywall_cancel")&&a.input.operationId===i&&await n.settle?.(a.requestId);let d=await n.get(void 0,{receiptId:e,operationId:i});L();let y=M(d);if(y?.quote&&y.quote.operationId!==i||y?.operation&&y.operation.operationId!==i)throw new b("INVALID_RESPONSE","Purchase operation changed");let h=x(d,c,i),W=h?o.operation:y?.operation;if(!W)throw new b("INVALID_RESPONSE","The current purchase result is missing");return h&&j.size===0&&!(n.pendingCommands?.length??(n.pendingCommand?1:0))&&(N=null),structuredClone(W)},destroy(){v=!0,ie(),S.clear(),u.abort(),f.clear()}},ie=n.subscribe(i=>{v||i.nodeId!==I||i.visit!==w||i.paywall?.receiptId!==e||(i.paywall.selectionGeneration??0)<(o.selectionGeneration??0)||(r(i.paywall.resolution),o={...o,resolution:i.paywall.resolution},F())});return{session:B,load:q}}function cn(n){let E=new Set,e=new Set,I=null;async function w(p,r){let v=!1;for(;!n.stopped&&n.key===p&&n.client.pendingCommand?.requestId===r;){if(!n.client.settle)throw new b("COMMAND_PENDING","The original display acknowledgement is still pending");await n.client.settle(r),v=!0,n.client.pendingCommand?.requestId===r&&await new Promise(S=>setTimeout(S,1500))}n.stopped||n.key!==p||(v&&await n.client.get(),!(n.stopped||n.key!==p)&&E.add(p))}function P(p,r){I=r;let v=()=>{I===r&&(I=null),e.delete(p)};return r.then(v,S=>{v(),n.busy||n.fail(S)}),r}function o(p){if(n.reviewing||E.has(p)||e.has(p)||n.stopped)return;e.add(p);let r=async()=>{if(n.reviewing||n.stopped||n.key!==p||E.has(p)){e.delete(p);return}if(n.busy||n.client.pendingCommand){setTimeout(()=>{r()},250);return}let v=(async()=>{if(n.staleRead){if(await n.staleRead,n.stopped||n.key!==p)return;if(n.client.pendingCommand){setTimeout(()=>{r()},250);return}}let S=n.client.view,A=n.expected(),F=A.requestId;try{await n.client.submit({operation:"shown",...A})}catch(q){if(!(q instanceof b)||q.code!=="CONFLICT"||q.status!==409||n.client.pendingCommand)throw q;await n.client.get();let u=n.client.view;if(n.stopped||n.reviewing||n.key!==p||!u||!S||u.id!==S.id||u.source.versionId!==S.source.versionId||u.nodeId!==A.nodeId||u.visit!==A.visit||u.revision<=A.revision||u.stopped||!u.screen&&(!u.paywall||u.paywall.receiptId!==S.paywall?.receiptId)||!["running","waiting"].includes(u.status)||n.client.pendingCommand)throw q;let k=n.expected();F=k.requestId,await n.client.submit({operation:"shown",...k})}await w(p,F)})();P(p,v)};r()}function m(){if(I)return I;let p=n.client.pendingCommand;if(p?.operation!=="shown")return null;let r=n.key;return e.add(r),P(r,(async()=>{await n.client.retry(),await w(r,p.requestId)})())}return{report:o,settled:m,get inFlight(){return I}}}function pn(n){let E={},e=new Map;async function I(w){let P=n.client.view,o=P?.screen,m=o?.customerData.nodes[w.nodeId];if(n.stopped||n.busy||!P||!o||!m)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(w.action)){let q=n.document,u=q?We(q,w.nodeId):null,k=u?.type==="customer_data"?u.data.outputs?.[w.action]:void 0;k&&o.outputs.includes(k)?await n.perform(()=>n.client.submit({operation:"submit",...n.expected(),input:{type:"screen",output:k,answers:n.answers,selection:w.value?{[w.nodeId]:w.value}:{}}})):await n.onIntent?.(w,P);return}let r=w.action.startsWith("sources_")?m.resources.find(q=>q.key===w.value):null;if(w.action.startsWith("sources_")&&!r)throw new b("INVALID_REQUEST","Choose a current resource");let v=`${P.visit}:${w.nodeId}:${r?.key??""}`,S=e.get(v)??[null],F=E[w.nodeId]??{page:1,after:null,filter:"all",...r?{resourceKey:r.key}:{}};if(w.action==="filter"){let q=w.value;if(!q||!(m.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(q))throw new b("INVALID_REQUEST","Unknown data filter");F={page:1,after:null,filter:q},S.splice(0,S.length,null)}else if(w.action==="next"||w.action==="sources_next"){let q=r?.sources.at(-1),u=r?q?{kind:"ledger",cursor:{at:q.detail[0],id:q.id,type:"source"}}:null:o.dataCursors[w.nodeId];if(!u||!r&&!m.hasNext)return;S[F.page]=u,F={...F,page:F.page+1,after:u}}else if(w.action==="previous"||w.action==="sources_previous"){if(F.page<=1)return;F={...F,page:F.page-1,after:S[F.page-2]??null}}e.set(v,S),E={...E,[w.nodeId]:F},await n.perform(()=>n.client.get({nodeId:P.nodeId,visit:P.visit,revision:P.revision,components:E}))}return{get queries(){return E},intent:I,reset(){E={},e.clear()}}}function fn(n){let{doc:E,holder:e,reviewHolder:I,mountScreenPreview:w}=n,P=!1,o,m=0,p=null,r="",v,S=new Map,A=u=>u?`${u.id}:${u.nodeId}:${u.visit}:${u.revision}:${u.paywall?.quote?.operationId??""}`:"";async function F(u){if(n.stopped||!n.client.review||P&&u===o&&v?.active)return;let k=!P||u!==o;P||(r=A(n.client.view),S.set(r,structuredClone(n.answers))),P=!0,o=u,e.hidden=!0,n.suspend(!0),I.hidden=!1;let O=++m;k&&(v?.finish("dismissed"),p?.destroy(),p=null,I.replaceChildren(),v=_e(I,n.loadingOptions,"funnel",()=>{q()}));let T=k?v:void 0;try{if(T?.start(!1,n.client.view?.locale),O!==m||n.stopped)return;let D=n.client.review(u),j=await(T?.wait(D,qe)??D);if(n.stopped||O!==m||!P)return;if(!j.review)throw new b("INVALID_RESPONSE","Historical projection is missing");p?.destroy(),p=null,T||I.replaceChildren();let N=E.createElement("div"),f=T?Le(N,I):()=>{};I.append(N);let M=j.run.locale.startsWith("zh"),L=E.createElement("p");L.textContent=M?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",N.append(L);for(let[U,Y]of j.review.pages.entries()){let _=E.createElement("button");_.type="button",_.textContent=M?`\u7B2C ${U+1} \u9875`:`Page ${U+1}`,_.onclick=()=>{F(Y.receiptId)},N.append(_)}if(j.review.page){let U=j.review.page,Y=E.createElement("div");Y.inert=!0,N.append(Y),p=w(Y,{mode:"live",rendererUrl:n.client.webViewUrl,title:U.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{O===m&&!n.stopped&&T?.present(f)},onError:C=>{if(O!==m||n.stopped)return;let Q=new Error(C);T?.finish("error",Q),p?.destroy(),p=null,N.remove(),n.fail(Q)},onEscape:()=>{q()}});let _=p;if(_.update(U.document,j.run.locale,{serverInput:{bindings:U.inputs,answers:U.answers,values:U.values}}),await _.ready,n.stopped||O!==m||!P)return}let x=M?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"};for(let U of[...j.review.coupons.map((Y,_)=>`${M?"\u4F18\u60E0\u5238":"Coupon"} ${_+1}: ${x[Y.status]}`),...j.review.purchases.map((Y,_)=>`${M?"\u8D2D\u4E70":"Purchase"} ${_+1}: ${sn(Y.status,M)}`)]){let Y=E.createElement("p");Y.textContent=U,N.append(Y)}j.review.page||T?.present(f),n.client.view&&await n.enqueue(n.client.view)}catch(D){if(O!==m||n.stopped)return;T?.finish("error",D),p?.destroy(),p=null,I.replaceChildren(),n.fail(D)}}async function q(){if(!P||n.stopped||!n.client.review)return;let u=++m;v?.finish("dismissed");try{if(await n.client.review(),n.stopped||u!==m)return;P=!1,m++,v?.finish("dismissed"),p?.destroy(),p=null,I.replaceChildren(),I.hidden=!0,e.hidden=!1;let k=n.client.view;A(k)!==r?(S.set(r,structuredClone(n.answers)),n.resetScreen()):(S.delete(r),n.suspend(!1)),k&&await n.enqueue(k)}catch(k){if(u!==m||n.stopped)return;p?.destroy(),p=null,I.replaceChildren(),n.fail(k)}}return{get active(){return P},get receipt(){return o},open:F,exit:q,get drafts(){return new Map([...S].map(([u,k])=>[u,structuredClone(k)]))},stop(){P=!1,m++,v?.finish("dismissed"),p?.destroy(),p=null,I.replaceChildren(),I.hidden=!0,e.hidden=!1}}}function mn(n){if(!n.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let E=n.client.pageExperiments.bind(n.client),e=!1,I=!1,w=0,P=!1,o=!1,m="",p=()=>{let f=n.client.view;return JSON.stringify([f?.id,f?.source.versionId,f?.visit,f?.revision,f?.status,f?.stopped])},r=new Map,v=new Set,S={},A=new Map,F=an(n.appManifestRelease),q=()=>{for(let f of r.values())f.effect.revert();r.clear()},u=()=>{q();for(let f of A.values())f();A.clear()};function k(f){if(e||v.has(f))return;v.add(f);let M=w;E(n.appManifestRelease,[f]).catch(L=>{v.delete(f),!e&&M===w&&oe(n.onError,L)})}async function O(){if(e)return;m=p();let f=n.client.view;if(!f||f.stopped||!["running","waiting"].includes(f.status)){w++,u();return}if(document.visibilityState==="hidden")return;if(P){o=!0;return}P=!0;let M=++w,L=`${f.id}:${f.visit}:${f.revision}`,x=location.href;try{let[U,{applyVisualVariation:Y}]=await Promise.all([E(n.appManifestRelease),import("./visual-dom-7IF7ITAK.js")]),_=n.client.view;if(e||M!==w||!_||_.stopped||!["running","waiting"].includes(_.status)||`${_.id}:${_.visit}:${_.revision}`!==L||location.href!==x)return;let C=new Set,Q=new Set;for(let B of U.assignments){let ie=`${U.payload.environmentId}:${B.experimentKey}`;if(Q.add(ie),A.has(ie)||A.set(ie,un(ie,S)),!!B.inExperiment)for(let i of U.payload.experiments){if(i.key!==B.experimentKey||!Be(location.href,i.urlPatterns??[]))continue;let c=i.meta?.findIndex(J=>J.key===B.variationKey)??-1,a=i.variations[c];if(!a?.renderGuard)continue;let d=B.receiptId+":"+i.changeId,y=JSON.stringify([B.variationKey,a]);C.add(d);let h=r.get(d);if(h?.signature===y){h.effect.applied&&k(B.receiptId);continue}r.get(d)?.effect.revert(),r.delete(d);let W=Y(a,{requireUniqueTargets:!0,boundVariations:i.variations,allowJs:!1,onApplied:()=>k(B.receiptId),onError:J=>oe(n.onError,J)});r.set(d,{signature:y,effect:W}),W.applied&&k(B.receiptId)}}for(let[B,ie]of r)C.has(B)||(ie.effect.revert(),r.delete(B));for(let[B,ie]of A)Q.has(B)||(ie(),A.delete(B))}catch(U){M===w&&u(),!e&&M===w&&oe(n.onError,U)}finally{P=!1,o&&!e&&(o=!1,O())}}let T=n.client.subscribe(()=>{if(p()===m)return;m=p(),w++;let f=n.client.view;(!f||f.stopped||!["running","waiting"].includes(f.status))&&u(),I&&O()}),D=ln(()=>{w++,u(),I&&O()}),j=()=>{w++,q()};document.addEventListener("visibilitychange",j);let N=Ve({document,run:async()=>{I&&await O()},delay:()=>I&&!e?15e3:void 0});return{async start(){I||e||(I=!0,await N.refresh())},refresh:O,destroy(){e=!0,w++,N.destroy(),document.removeEventListener("visibilitychange",j),T(),D(),u(),F.destroy()}}}var Qe=5e3;async function rt(n,E){let e=E,[{mountScreenPreview:I},{showPaywall:w}]=await Promise.all([import("./screen-renderer-TEVGVUT5.js"),import("./paywall-JL4SXFXT.js")]),P=e.client.identitySignal;e.signal?.throwIfAborted(),P?.throwIfAborted();let o=e.appManifestRelease?mn({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;o?.start();let m=n.ownerDocument,p=on(m),r=m.createElement("section"),v=m.createElement("div"),S=m.createElement("div"),A=m.createElement("div"),F=m.createElement("button");A.hidden=!0,F.type="button";let q=m.createElement("p"),u=m.createElement("p"),k=m.createElement("button"),O=m.createElement("button"),T=m.createElement("button"),D=m.createElement("dialog"),j;r.dataset.indianaFunnel="",r.setAttribute("aria-busy","false"),r.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",S.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",q.setAttribute("role","status"),u.setAttribute("role","alert"),u.hidden=!0,k.type=O.type=T.type="button",S.append(k,q,u,T,F,O),r.append(v,A,S),n.append(r);let N=null,f=null,M=null,L="",x="",U="",Y="",_="",C=!1,Q=0,B=!1,ie="",i=null,c=Promise.resolve(),a=!e.client.view,d,y,h,W="",J,$=!1,Z=null,ce=!1,ye=()=>e.client.pendingCommand?.operation==="close",re=null,K=null,Je=Ve({document:m,run:async()=>{(!f?.observing||e.client.pendingCommand)&&await Ue()},delay:()=>{if(!(C||!M||!["running","waiting"].includes(M.status)&&!e.client.pendingCommand)&&!(f?.observing&&!e.client.pendingCommand))return M.pendingRequest||e.client.pendingCommand?1500:Qe},hiddenDelay:()=>!C&&e.client.pendingCommand?15e3:void 0}),X=null;function Me(){return K&&e.client.hasDurableJournal===!0&&X?.acknowledged===!0&&X.operationId===K.operationId&&e.client.view?.id===X.runId&&e.client.view?.status==="closed"&&e.client.view.revision===X.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?K:null}function ze(t){let s=t.run.paywall;if(X&&t.settlement?.requestId===X.requestId&&t.settlement.state==="settled"&&t.settlement.operationId===null&&t.run.id===X.runId&&t.run.status==="closed"&&!t.run.pendingRequest&&t.run.revision===X.revision+1&&t.run.nodeId===X.nodeId&&t.run.visit===X.visit&&s?.receiptId===X.receiptId&&s.selectionGeneration===X.selectionGeneration&&(s.quote?.operationId??null)===X.operationId&&(s.operation?.operationId??s.quote?.operationId??null)===X.operationId){let l=X.operationId===null&&s.selectionGeneration===0&&!s.quote&&!s.operation&&!s.purchaseRequestId,ue=Te({quote:s.quote,operation:s.operation,requestId:s.purchaseRequestId,pending:!1,destroyed:!1,canReselect:s.canReselect});(l||s.canReselect===!0&&ue.type==="native")&&(X.acknowledged=!0)}}let Ce=null,De=new Set,pe={},se=(t,s=null)=>{C||(Ce=s,u.textContent=t instanceof Error?t.message:"Request failed",u.hidden=!1,T.hidden=e.client.pendingCommand===null,oe(e.onError,t))};function he(){let t=e.client.view;if(!t)throw new b("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let V=fn({client:e.client,doc:m,holder:v,reviewHolder:A,mountScreenPreview:I,loadingOptions:e,get stopped(){return C},get answers(){return pe},suspend(t){f?.setSuspended(t)},resetScreen(){L="",x="",U=""},enqueue:fe,fail:se}),Se=cn({client:e.client,expected:he,fail:se,get stopped(){return C},get reviewing(){return V.active},get key(){return L},get busy(){return Q},get staleRead(){return i}}),Fe=pn({client:e.client,expected:he,perform:Re,onIntent:e.onCustomerDataIntent,get stopped(){return C},get busy(){return Q},get document(){return N?.document},get answers(){return pe}}),ke=t=>`${t.id}:${t.nodeId}:${t.visit}`,Pe=t=>t&&(t.screen||t.paywall)?ke(t):"";function Ie(){let t=e.client.view;k.disabled=!V.active&&(Q>0||!!e.client.pendingCommand||!t?.canBack||t.stopped||!["running","waiting"].includes(t.status)||!Pe(t)||x!==Pe(t))}async function je(t){if(!t)return;let s=e.client.view;await t;let l=e.client.view;if(!s||!l||l.id!==s.id||l.nodeId!==s.nodeId||l.visit!==s.visit||l.stopped||!["running","waiting"].includes(l.status))throw new b("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Re(t,s=!1){if(!((Q||ce||re||K)&&!s||C||V.active&&!s)){Q++,r.setAttribute("aria-busy","true"),Ie(),u.hidden=!0,Ce=null;try{if(s||await je(Se.inFlight),C)return;let l=await t();C||await fe(e.client.view??l.run)}catch(l){se(l,e.client.pendingCommand?.requestId??null)}finally{Q=Math.max(0,Q-1),r.setAttribute("aria-busy",String(Q>0)),C||(T.hidden=e.client.pendingCommand===null,Ie())}}}function Ee(){Je.schedule()}async function Ue(){if(!(C||B||Q)){if(V.active){await V.open(V.receipt);return}B=!0;try{let t=e.client.pendingCommand;t&&e.client.settle&&await e.client.settle(t.requestId);let s=e.client.view,l=Fe.queries,ue=await e.client.get(s?.screen&&Object.keys(l).length?{nodeId:s.nodeId,visit:s.visit,revision:s.revision,components:l}:void 0);!C&&l===Fe.queries&&await fe(e.client.view??ue.run)}catch(t){se(t)}finally{B=!1}}}function Oe(t,s){if(d?.active)return d;let l=_e(n,e,"funnel",()=>{C||$||($=!0,l.finish("dismissed"),ge(),r.hidden=!0,e.client.view?be().finally(ae):ae())});return d=l,l.start(t,s),l}function $e(){clearTimeout(J?.timeout),J=void 0}function ge(){$e(),y?.abort(),y=void 0,N?.destroy(),N=null,f?.destroy(),f=null,h?.(),h=void 0,D.open&&D.close(),v.replaceChildren(),L="",x="",U="",_=""}function He(t){let s=t.screen?.presentation;if(!s||s.type==="inline"){D.open&&D.close(),r.parentElement!==n&&n.append(r);return}r.parentElement!==D&&(D.append(r),n.append(D));let l={sm:420,md:640,lg:900};D.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in s?l[s.size]+"px":"100vw"}`,D.setAttribute("aria-label",(j?.screen===t.screen?.content.document.name?j?.label:void 0)??N?.document?.name??t.screen?.content.document.name??"Funnel")}async function wn(t){if(C||$||ce&&(ye()||["running","waiting"].includes(t.status)))return;M=t,Ce&&e.client.pendingCommand?.requestId!==Ce&&(u.hidden=!0,Ce=null);let s=t.locale.startsWith("zh");if(F.textContent=s?"\u56DE\u770B":"History",F.hidden=!e.client.review,k.textContent=V.active?s?"\u8FD4\u56DE\u5F53\u524D":"Return to current":s?"\u8FD4\u56DE":"Back",O.textContent=s?"\u5173\u95ED":"Close",T.textContent=s?"\u91CD\u8BD5":"Retry",Ie(),T.hidden=e.client.pendingCommand===null,q.textContent=t.pendingRequest?s?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?s?"\u7B49\u5F85\u4E2D":"Waiting":"",ie!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(ie=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,oe(e.onState,structuredClone(t))),C||$)return;if((!t.pendingRequest||ce&&t.status==="closed")&&["closed","ineligible","failed"].includes(t.status)){ae();return}if(t.stopped||e.client.configurationReady===!1){V.stop(),ge(),d?.finish("skipped"),r.hidden=!0,Ee();return}if(r.hidden=!1,V.active){Ee();return}let l=Pe(t),ue=e.client.view;if(ue&&ue.revision>t.revision&&Pe(ue)!==l)return;let Ge=!t.instruction&&!t.pendingRequest&&t.nodeType==="screen"&&["running","waiting"].includes(t.status);l!==L&&(L&&d?.finish("dismissed"),ge(),L=l,pe={...t.answers},Fe.reset());let me=ke(t);if(W===me){r.hidden=!0;return}if(Ge&&!l){r.hidden=!0;let R=Oe(!0,t.locale);!C&&!$&&J?.key!==me&&($e(),J={key:me,timeout:setTimeout(()=>{let g=e.client.view;if(!R.active||!g||ke(g)!==me)return;W=me;let ne=new Error("Funnel screen preparation timed out");R.finish("error",ne),ge(),se(ne)},qe)}),Ee();return}$e();let te=R=>{let g=e.client.view;return!C&&!$&&!Z&&!R.aborted&&e.client.configurationReady!==!1&&!!g&&!g.stopped&&!["closed","ineligible","failed"].includes(g.status)&&Pe(g)===l},ee=(R,g)=>{te(g)&&(W=l,d?.finish("error",R),ge(),r.hidden=!0,se(R))};if(l||(He(t),t.instruction?.type!=="event"&&t.instruction?.type!=="open_url"&&d?.finish("skipped")),t.screen){let R=t.screen.content;if(!N){let z=t.screen.presentation.type!=="inline",we=Oe(z,t.locale);if(C||$)return;let le=(y=new AbortController).signal;He(t),h=z?rn(D):Le(r,n),N=I(v,{mode:"live",rendererUrl:e.client.webViewUrl,title:R.document.name,onAction(de,ve={},hn={}){if(V.active||!te(le)||x!==l)return;pe={...pe,...hn};let In=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:Ne})=>Object.hasOwn(pe,Ne)).map(({variable:Ne})=>[Ne,pe[Ne]]));Re(()=>e.client.submit({operation:"submit",...he(),input:{type:"screen",output:de,answers:In,selection:ve}}))},onAnswers:de=>{V.active||!te(le)||x!==l||(pe={...pe,...de})},onCustomerDataIntent:de=>{V.active||!te(le)||x!==l||Fe.intent(de).catch(se)},onEscape:()=>{!te(le)||x!==l||V.active||re||K||be()},onError:de=>{let ve=new Error(de);x===l?se(ve):ee(ve,le)},onRendered:de=>{if(!(!te(le)||x===l))try{we.present(ve=>{h?.(),h=void 0,de&&(j={screen:R.document.name,label:de},D.setAttribute("aria-label",de)),z&&(D.showModal(),!ve&&e.loading!=="host"&&tn(D,t.screen.presentation.type)),x=l,Ie()}),te(le)&&Se.report(l)}catch(ve){ee(ve,le)}}})}let g={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:pe,values:t.screen.values}},ne=JSON.stringify([R,t.locale,g.parameters,t.screen.inputs,t.screen.values]);if(ne!==U)N.update(R.document,t.locale,g),U=ne,Y=JSON.stringify(g.capabilities),_=JSON.stringify(g.customerData);else{let z=JSON.stringify(g.capabilities);z!==Y&&(N.updateCapabilities(g.capabilities),Y=z),JSON.stringify(g.customerData)!==_&&(N.updateCustomerData(g.customerData),_=JSON.stringify(g.customerData))}let G=N;if(G)try{await(d?.wait(G.ready)??G.ready)}catch(z){y&&ee(z,y.signal)}}else if(t.paywall&&!f){let R=Oe(!0,t.locale);if(C||$)return;let g=(y=new AbortController).signal;He(t);let ne=await w(v,{loading:"host",signal:g,canInteract:()=>te(g)&&!V.active&&!re&&!K,beforeAction:async()=>{Q++;try{await je(Se.settled()),u.hidden=!0,Ce=null}finally{Q=Math.max(0,Q-1)}},start:()=>dn(e.client),onObservationChange:Ee,onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,resolveOfferId:e.resolveOfferId,onEvent:e.onEvent,onOpenUrl:G=>e.onOpenUrl?e.onOpenUrl({receiptId:t.paywall.receiptId,url:G,openIn:"same_window"}):m.defaultView?.location.assign(G),onAction:async G=>{if(V.active)return;let z=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:e.client.view?.revision??t.revision,input:{type:"screen",output:G,answers:{}}});await fe(e.client.view??z.run)},onError:G=>{x===l?se(G):ee(G,g)}},{quoteError:G=>oe(e.onError,G),present(G){te(g)&&(R.present(()=>{G(),x=l,Ie()}),te(g)&&Se.report(l))},async dismiss(){C||g.aborted||V.active||re||K||!ce&&!te(g)||(ce=!0,await be())}}).catch(G=>(ee(G,g),null));!te(g)&&!(ce&&!C&&!g.aborted)?ne?.host?.destroy():ne&&(f=ne.host,f?.setSuspended(V.active))}if(C||$)return;Ie();let H=t.instruction;if(H&&(H.type==="open_url"||H.type==="event")&&!De.has(H.receiptId)){let R=m.createElement("button");R.type="button",R.textContent=H.type==="open_url"?`${s?"\u524D\u5F80":"Continue to"} ${new URL(H.url).host}`:s?"\u7EE7\u7EED":"Continue",R.onclick=()=>{let g=he(),ne=H.type==="open_url"&&!e.onOpenUrl&&H.openIn==="new_window"?yn(H.url):null;Re(async()=>{let G="success";if(H.type==="open_url")if(e.onOpenUrl)try{G=await e.onOpenUrl({receiptId:H.receiptId,url:H.url,openIn:H.openIn})===!1?"failed":"opened"}catch(we){oe(e.onError,we),G="failed"}else G=H.openIn==="new_window"&&!ne?"failed":"opened";if(H.type==="event"){if(!e.onEvent)throw new b("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(H.event)}if(C||e.client.view?.nodeId!==g.nodeId||e.client.view.visit!==g.visit)throw new b("PRECONDITION_FAILED","The client action visit changed");let z=await e.client.submit({operation:"submit",...g,input:{type:"client_action",receiptId:H.receiptId,outcome:G}});return De.add(H.receiptId),H.type==="open_url"&&!e.onOpenUrl&&H.openIn==="same_window"&&m.defaultView?.location.assign(H.url),z})},d?.active?d.present(()=>v.replaceChildren(R)):v.replaceChildren(R)}!t.pendingRequest&&t.status==="completed"&&!De.has(`complete:${t.id}`)&&(De.add(`complete:${t.id}`),oe(e.onComplete,structuredClone(t))),Ee()}function yn(t){let s=m.defaultView?.open(t,"_blank")??null;return s&&(s.opener=null),s}function fe(t){return Ie(),c=c.catch(()=>{}).then(async()=>{try{await wn(t)}catch(s){throw d?.active&&(W=ke(t),d.finish("error",s),ge(),r.hidden=!0),s}}),c}let gn=e.client.subscribe(t=>{a||(!ce&&(t.stopped||e.client.configurationReady===!1||L&&x!==L&&(Pe(t)!==L||["closed","ineligible","failed"].includes(t.status)))&&(ge(),d?.finish("dismissed"),r.hidden=!0),fe(t).catch(se))}),vn=e.client.subscribeError?.(se);function be(t){if(Z)return Z;if(C||!t&&(re||K))return Promise.resolve();let s=!t&&ye();return!s&&e.client.view&&!["running","waiting"].includes(e.client.view.status)?(M=e.client.view,ae(),Promise.resolve()):(Z=Re(async()=>{let l=s?await e.client.retry():await e.client.submit({operation:"close",...t??he()});return t&&ze(l),l},!0).then(()=>{let l=e.client.view;l?.status==="closed"&&!ye()&&(M=l,ae())}).finally(()=>{Z=null}),Z)}function ae(){o?.destroy(),!C&&(C=!0,e.signal?.removeEventListener("abort",ae),P?.removeEventListener("abort",ae),d?.finish("dismissed"),Je.destroy(),gn(),vn?.(),ge(),V.stop(),D.remove(),r.remove(),p(),oe(e.onDismiss,M?structuredClone(M):null))}k.onclick=()=>{if(!k.disabled){if(V.active){V.exit();return}Re(()=>e.client.submit({operation:"back",...he()}))}},F.onclick=()=>{V.open()},O.onclick=()=>{d?.active?d.dismiss():re||be()},T.onclick=()=>{ye()?be():Re(()=>e.client.retry())},D.addEventListener("cancel",t=>{t.preventDefault(),d?.active?d.dismiss():re||be()}),e.signal?.addEventListener("abort",ae,{once:!0}),P?.addEventListener("abort",ae,{once:!0});try{let t=e.client.view;if(t)((e.client.viewAgeMs??Qe)>=Qe||t.instruction?.type==="evaluate_segment")&&(i=Ue().finally(()=>{i=null})),await fe(t);else{r.hidden=!0;let s=Oe(e.client.view?.screen?.presentation.type!=="inline",e.client.view?.locale);if(C||$)throw new DOMException("Presentation cancelled","AbortError");let l=await s.wait(e.client.get(),qe);a=!1,await fe(e.client.view??l.run)}}catch(t){throw d?.finish("error",t),ae(),t}return{destroy:ae,refresh:Ue,get recovery(){let t=Me();if(t)return t;if(!C&&!Q&&!ce&&!re&&f){let s=f.recovery;if(s.type!=="native")return s}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??K?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(re)return re;let t=Me();if(t)return Promise.resolve(t);let s=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??K?.operationId??null,l=()=>({type:"recover",operationId:s,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let ee=f?.recovery;return Promise.resolve(ee&&ee.type!=="native"&&ee.type!=="cancel"?ee:l())}let ue=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(ee=>ee.operation==="close");if(C&&!(ue||K&&e.client.view?.status==="closed")||Q||B||Z||V.active||!f&&!K&&!ue)return Promise.resolve(l());let Ge=f,me=(async()=>{try{if(!K&&ue){let R=await e.client.retry();return await fe(e.client.view??R.run),l()}if(!K){let R=await Ge.prepareFallback();if(R.type!=="native")return R;if(e.client.hasDurableJournal!==!0)return l();K=R}let ee=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(ee.length){let R=ee.find(ne=>ne.operation==="close");if(!R||!X||R.requestId!==X.requestId)return l();let g=await e.client.retry();ze(g),await fe(e.client.view??g.run)}else{let R=e.client.view,g=R?.paywall;if(!R||!g||g.selectionGeneration===void 0||(g.quote?.operationId??null)!==K.operationId||K.operationId!==null&&g.canReselect!==!0)return l();let ne=g.selectionGeneration,G=await e.client.get();await fe(e.client.view??G.run);let z=e.client.view,we=z?.paywall;if(!z||!we||!["running","waiting"].includes(z.status)||z.stopped||z.id!==R.id||z.nodeId!==R.nodeId||z.visit!==R.visit||we.receiptId!==g.receiptId||we.selectionGeneration!==ne||(we.quote?.operationId??null)!==K.operationId||K.operationId!==null&&we.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return l();let le=he();X={runId:z.id,operationId:K.operationId,revision:le.revision,requestId:le.requestId,nodeId:z.nodeId,visit:z.visit,receiptId:we.receiptId,selectionGeneration:ne,acknowledged:!1},await be(le)}let H=Me();return H?(ae(),H):l()}catch(ee){return se(ee),l()}})();re=me;let te=()=>{re===me&&(re=null)};return me.then(te,te),me},review:V.open,exitReview:V.exit,get unappliedDrafts(){return V.drafts}}}export{mn as a,rt as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as u}from"./chunk-QVGTHPWT.js";import{Aa as j,Ba as O,Ca as T,ya as E,za as M}from"./chunk-
|
|
1
|
+
import{a as u}from"./chunk-QVGTHPWT.js";import{Aa as j,Ba as O,Ca as T,ya as E,za as M}from"./chunk-KRQESEG2.js";import{q as w}from"./chunk-HDVLCRC6.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as t}from"./chunk-WMIDEJTZ.js";import{gb as n}from"./chunk-KRQESEG2.js";function r(e,o,a){return n(e,o,a,t)}export{r as a};
|