@tinkerlandai/longplay-sdk 0.10.25 → 0.10.26
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 +7 -0
- package/THIRD_PARTY_NOTICES.md +26 -0
- package/dist/{ai-usage-B6RepnmH.d.ts → ai-usage-E4c9NSJK.d.ts} +1 -1
- package/dist/{api-C9P338XT.d.ts → api-BpeJkr6U.d.ts} +390 -390
- package/dist/chunk-2KOQBV3Y.js +1 -0
- package/dist/chunk-2MTTK3BT.js +1 -0
- package/dist/chunk-3FPYCF7Z.js +1 -0
- package/dist/chunk-3VUPVXAV.js +1 -0
- package/dist/chunk-5RXU57I5.js +1 -0
- package/dist/chunk-6VY4PZZ6.js +1 -0
- package/dist/chunk-7CFF6SWH.js +1 -0
- package/dist/chunk-B5JHPPR4.js +10 -0
- package/dist/chunk-BZSKOOMM.js +1 -0
- package/dist/chunk-C6JRUYKW.js +1 -0
- package/dist/chunk-CILM5XMH.js +1 -0
- package/dist/chunk-CNIBGSVO.js +1 -0
- package/dist/chunk-CZ3H2X7D.js +1 -0
- package/dist/chunk-DCCM7FYR.js +1 -0
- package/dist/chunk-DCIGO3NJ.js +1 -0
- package/dist/chunk-DOJE7VUR.js +1 -0
- package/dist/{chunk-34I23EKZ.js → chunk-ECMWY3G2.js} +1 -1
- package/dist/chunk-G7NSECIG.js +1 -0
- package/dist/chunk-GIV4FOOW.js +1 -0
- package/dist/chunk-HMRIMJ5W.js +1 -0
- package/dist/chunk-JAKOBECD.js +1 -0
- package/dist/{chunk-O3LZPMS4.js → chunk-KRTX4QEH.js} +1 -1
- package/dist/chunk-LPDUK7HT.js +1 -0
- package/dist/chunk-MRFBMFNK.js +1 -0
- package/dist/chunk-MWDR5FEU.js +1 -0
- package/dist/chunk-MYUYN7ZG.js +1 -0
- package/dist/chunk-NMKZ724L.js +1 -0
- package/dist/chunk-O4KXODTJ.js +17 -0
- package/dist/chunk-ORPOCB2J.js +1 -0
- package/dist/chunk-PMCGTXGH.js +1 -0
- package/dist/{chunk-RKREEPCT.js → chunk-PWQ5BHBJ.js} +1 -1
- package/dist/chunk-SMIO7OG5.js +1 -0
- package/dist/chunk-T4GTAH43.js +1 -0
- package/dist/chunk-UBKD6VMS.js +1 -0
- package/dist/chunk-UHI7SPHK.js +1 -0
- package/dist/chunk-WM27UTWT.js +62 -0
- package/dist/chunk-WOT6VMZA.js +1 -0
- package/dist/{chunk-SJNF6JDJ.js → chunk-X7G7JMZ3.js} +1 -1
- package/dist/chunk-YSNMXK4R.js +1 -0
- package/dist/{configuration-sync-eEFj_oKG.d.ts → configuration-sync-DdTRUv7A.d.ts} +17 -17
- package/dist/content-UDP5VQS4.js +1 -0
- package/dist/funnel-host-purchase-5NLPYJRK.js +1 -0
- package/dist/{funnel-local-client-CSA9XoC4.d.ts → funnel-local-client-DoYVcZ1z.d.ts} +1696 -1696
- package/dist/funnel-node-evaluation-COxXtZEQ.d.ts +1003 -0
- package/dist/{funnel-process-client-RXgS2i-R.d.ts → funnel-process-client-DtXNiFQ-.d.ts} +1736 -1736
- package/dist/funnel-runtime-host-ZWUAGDBU.js +1 -0
- package/dist/index.d.ts +70 -69
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-N3Q4W6ZU.js +1 -0
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +3 -3
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-VURXKAFX.js +1 -0
- package/dist/page.d.ts +12 -12
- package/dist/page.js +1 -1
- package/dist/paywall-QQ2MC4KO.js +1 -0
- package/dist/paywall-session-WC2WFWBQ.js +1 -0
- package/dist/popup.d.ts +4 -4
- package/dist/popup.js +1 -1
- package/dist/react-native.d.ts +8 -8
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-G2EWN3WB.js +1 -0
- package/dist/server.d.ts +1752 -23
- package/dist/server.js +6 -1
- package/dist/visual-dom-5LUN4AHO.js +1 -0
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-2KI63SPJ.js +0 -10
- package/dist/chunk-2ZJ5CS5Q.js +0 -1
- package/dist/chunk-5HJMAZ7A.js +0 -1
- package/dist/chunk-7AXCG6NU.js +0 -1
- package/dist/chunk-BB5P5HPS.js +0 -1
- package/dist/chunk-C2BODHNY.js +0 -1
- package/dist/chunk-EIYWDWXP.js +0 -1
- package/dist/chunk-LFFBNGXP.js +0 -1
- package/dist/chunk-MHEYMXGZ.js +0 -17
- package/dist/chunk-ML3BIPM6.js +0 -1
- package/dist/chunk-O4535GJR.js +0 -6
- package/dist/chunk-OEH47Y2L.js +0 -1
- package/dist/chunk-THGLNE4K.js +0 -1
- package/dist/chunk-TUYBXAAK.js +0 -1
- package/dist/chunk-ZX2RWS3T.js +0 -1
- package/dist/content-FD2Q6XD6.js +0 -1
- package/dist/funnel-host-purchase-XW7IF52Y.js +0 -1
- package/dist/funnel-node-evaluation-Cg-4tcAs.d.ts +0 -2731
- package/dist/funnel-runtime-host-I6PJXVRC.js +0 -1
- package/dist/paywall-CGBFHFRU.js +0 -1
- package/dist/screen-renderer-WOMWOEYL.js +0 -1
- package/dist/visual-dom-7IF7ITAK.js +0 -1
- package/dist/{coupon-DyKA-BRG.d.ts → coupon-kfkIVf9n.d.ts} +4 -4
- package/dist/{presentation-loading-D0A9G_kT.d.ts → presentation-loading-iSaRiDP2.d.ts} +3 -3
- package/dist/{screen-DRP7nsrQ.d.ts → screen-CGCJ46b1.d.ts} +3 -3
package/dist/chunk-BB5P5HPS.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as R,b as re}from"./chunk-THGLNE4K.js";import{a as ne,b as j,c as ie,f as se}from"./chunk-TUYBXAAK.js";import{a as m,q as U}from"./chunk-LFFBNGXP.js";import{b as te}from"./chunk-5HJMAZ7A.js";import{a as o}from"./chunk-SJNF6JDJ.js";import{Da as d,Fa as G,Ra 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 B}from"./chunk-O4535GJR.js";import{a as J}from"./chunk-DSPLGTQI.js";import{a as Y}from"./chunk-MHEYMXGZ.js";var L=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 _(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 oe(t,e,n){let r=null,s=0,a=0,l=0,y=Promise.resolve(),g=!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 p=()=>{if(g)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},A=i=>{if(i!==s)throw new o("IDENTITY_CHANGED","Identity changed during Push operation")};async function D(i){let c=p();if(!c.sha256&&!globalThis.crypto?.subtle)throw new o("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,b=>b.charCodeAt(0))):await ve(i);if(!/^[a-f0-9]{64}$/.test(u))throw new o("INVALID_STATE","Push credential digest is invalid");return u}function f(i){let c=H.parse(i);if(c.installationId.toLowerCase()!==p().installationId.toLowerCase())throw new o("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=p(),b={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},P=await u.sign(X(i,u.scope,b));return{...b,signature:P}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=p(),c=s,u=r?await(e.session?.access()??r):null,b=_(i,w=>w),P;if(b.detachSeq!==null){let w=b.detachSeq,x=K.parse(await S("detach",{sequence:w,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...x},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new o("INVALID_RESPONSE","Push detach acknowledgement is invalid");let F=f(k.installation);if(F.bound||F.identitySeq!==w)throw new o("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof o&&k.status===404)P=k;else if(!(k instanceof o)||k.status!==412)throw k}P||_(i,k=>({...k,detachSeq:k.detachSeq===w?null:k.detachSeq}))}if(A(c),!u){if(P)throw P;return null}let E=d.bindPushInstallation,N=E.request.parse(await S("bind",{sequence:l,platform:i.platform,credentialDigest:await D(u)}));A(c);let C=E.response.parse(await I(E.path,N,u));A(c);let T=f(C.installation);if(!T.bound||T.identitySeq!==l)throw new o("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return P&&b.detachSeq!==null&&l>b.detachSeq&&_(i,w=>({...w,detachSeq:w.detachSeq===b.detachSeq?null:w.detachSeq})),T}async function h(){p();let i=s,c=r?await(e.session?.access()??r):null;if(!c)throw new o("NOT_IDENTIFIED","Identify before reading this installation");let u=d.readPushInstallation,b=u.request.parse(await S("read",{credentialDigest:await D(c)}));A(i);let P=u.response.parse(await I(u.path,b,c));return A(i),f(P.installation)}function O(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function v(i,c,u){let b=p(),P=c.identity,E=c.observation,N=r?await(e.session?.access()??r):null;if(A(P),E!==a)throw new o("INVALID_STATE","Push observation changed during recovery");if(!N)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 O(async()=>{if(A(P),await q(),A(P),E!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let C=_(b,F=>u?F:{...F,addressSeq:L(F.addressSeq)}),w=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:C.addressSeq,credentialDigest:await D(N),...u?{challenge:u}:{}}),x=u?W.parse(w):Q.parse(w);if(A(P),E!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,x,N);if(A(P),E!==a||_(b,F=>F).addressSeq!==C.addressSeq)throw new o("INVALID_STATE","Push observation changed during recovery");if(u){let F=d.updatePushAddress.response.parse(k),V=f(F.installation);if(!V.bound||V.identitySeq!==l||V.addressSeq!==C.addressSeq||V.connectionId!==i.connectionId||V.addressStatus!=="active")throw new o("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return V}if(!k||typeof k!="object"||!("recovery"in k))throw new o("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return M.parse(k.recovery)})}return{recoveryObserver(){p();let i={identity:s,observation:++a};return{async request(c){return M.parse(await v(c,i))},async confirm(c,u){return H.parse(await v(u,i,c))}}},identify(i){if(!t)return;l=_(t,u=>({...u,identitySeq:L(u.identitySeq)})).identitySeq,r=i,s++,a++},reset(){if(t)try{_(t,i=>{let c=L(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,s++,a++}},start(){t&&!g&&O()},destroy(){g=!0,r=null,s++,a++},async sync(){return await O()},read:h,async recover(){let i=p(),c=s,u=l;return a++,await O(async()=>{A(c);let b=await h();return A(c),l=_(i,E=>{if(E.identitySeq!==u)throw new o("IDENTITY_CHANGED","A newer installation intent exists");return{...E,identitySeq:L(Math.max(E.identitySeq,b.identitySeq)),addressSeq:Math.max(E.addressSeq,b.addressSeq)}}).identitySeq,await q()})},tokenObserver(){p();let i=++a,c=s;return async u=>{if(i!==a||c!==s)return null;let b=p(),P=r?await(e.session?.access()??r):null;if(!P)throw new o("NOT_IDENTIFIED","Identify before registering a Push token");if(await O(),A(c),i!==a)return null;let E=_(b,w=>({...w,addressSeq:L(w.addressSeq)})),N=d.updatePushAddress,C=N.request.parse(await S("address",{...u,sequence:E.addressSeq,credentialDigest:await D(P)}));if(A(c),i!==a)return null;let T=await I(N.path,C,P);return A(c),i!==a||_(b,w=>w).addressSeq!==E.addressSeq?null:f(N.response.parse(T).installation)}}}}function ae(t,e){let n={async preference(r){let s=d.readMessagingPreference;return(await m(t,s,{channel:r})).preference},async setPreference(r){let s=d.setMessagingPreference;return(await m(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 ce(t,e,n={}){let r=!1;function s(){if(r)throw new o("CLOSED","SDK client was destroyed")}let a=new Set,l=g=>{for(let p of a)try{p(g)}catch{}},y=t.session.subscribeIdentity(()=>{l(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:s,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return s(),a.add(g),()=>{a.delete(g)}},identify(g){s();let p=typeof g=="string"?g:g.accessToken;if(!B.test(p))throw new o("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(p),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}var Ee={...d.readHoldings,request:d.readHoldings.request.omit({customerId:!0})};function ue(t){return{async checkEntitlement(e){R(e);let n=d.checkEntitlement,r=n.request.parse(e),s=await m(t,n,r);return ne(r.requirement,s.check,void 0,s.scope),s},async readHoldings(e={}){return m(t,Ee,e)}}}function de(t){return{async readLedger(e){let n=d.readLedger;return m(t,n,{query:e})},async readCreditStatement(e){R(e);let n=d.readCreditStatement;return m(t,n,e)},async quoteBalance(e){R(e);let n=d.quoteBalance;return m(t,n,{command:e})}}}function le(t){return{async setupPayment(e){R(e);let n=d.setupPayment;return m(t,n,e)},async readPaymentSetup(e){R(e);let n=d.readPaymentSetup;return m(t,n,e)},async readBillingInvoice(e){R(e);let n=d.readBillingInvoice;return m(t,n,e)},async readBillingControls(e={}){R(e);let n=d.readBillingControls;return m(t,n,e)},async prepareBillingAuthorization(e){R(e);let n=d.prepareBillingAuthorization;return m(t,n,e)},async confirmBillingAuthorization(e){R(e);let n=d.confirmBillingAuthorization;return m(t,n,e)},async setBillingCoupons(e){R(e);let n=d.setBillingCoupons;return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){R(e);let n=d.revokeBillingAuthorization;return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){R(e);let n=d.listBillingInvoices;return m(t,n,e)},async confirmBillingAdjustment(e){R(e);let n=d.confirmBillingAdjustment;return m(t,n,e)}}}function pe(t){return{async redeemReward(e){return R(e),(await m(t,d.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return R(e),(await m(t,d.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return R(e),(await m(t,d.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 m(t,d.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,d.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,d.listOffers,{},{response:"Invalid offers response"})).offers}}}function fe(t){return{...ue(t),...de(t),...le(t),...re(t),...pe(t)}}function me(t){return{async resolveContent(e){R(e);let n=d.resolveContent;return m(t,n,e)},async resolvePaywall(e){R(e);let n=d.resolvePaywall,r=n.request.parse(e),s=await m(t,n,r);return j(r,s.paywall.check,s.scope),s},async resolveOffering(e){R(e);let n=d.resolveOffering,r=n.request.parse(e),s=await m(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,Ae=6e4,Se=5;function Oe(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,g=0;function p(){if(!e())throw new o("NOT_IDENTIFIED","Call identify before using Features or events")}function A(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(A)},Math.min(be*2**g,Ae)),typeof y=="object"&&"unref"in y&&y.unref())}function D(h){if(p(),r&&Date.now()<r.until&&!$(r.config,h.kind))return;q();let O=d.trackEvents.request.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(z({events:[O]})>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(O)),A()}function f(h,O={},v={}){D({kind:"custom",name:h,properties:O,...v})}async function S(h=!1){if(p(),l)return l;let O=n,v=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&O===n;){let u=[],b=z({events:[]});for(let N of a.slice(0,Math.min(c,100))){let C=z(N)+(u.length?1:0);if(u.length&&b+C>ye)break;u.push(N),b+=C}let P=d.trackEvents,E;try{if(E=await m(t,P,{events:u},void 0,{keepalive:h}),O!==n)throw new o("IDENTITY_CHANGED","Event identity changed during delivery");if(E.inserted+E.duplicates+E.rejected+E.skipped!==u.length||E.rejections.length!==E.rejected)throw new o("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(N){throw O===n&&(g++,(Oe(N)||g>=Se)&&(a.splice(0,u.length),g=0)),N}g=0,s(E.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=E.inserted,i.duplicates+=E.duplicates,i.rejected+=E.rejected,i.skipped+=E.skipped,i.rejections.push(...E.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:f,observe:D,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=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 ge(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 g(p={}){s||y();let A=a,D=!1,f=async()=>{if(D||A!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let C=d.getFeatures,T=s?{scope:{projectId:s.scope.projectId,environment:s.scope.environment},payload:await s.features()}:await m(t,C,{});if(A!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");if(r&&(T.scope.projectId!==r.projectId||T.scope.environment!==r.environment))throw new o("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(T.payload.analyticsConfig),T},S=await f(),I=!0,q,h=C=>{try{p.onError?.(C)}catch{}},O=(C,T)=>{try{let w=he(T);n.observe({...C,...w?{merchandise:w}:{}})}catch(w){h(w)}},v=ie({assertUsable:s?.assertFeatures,scope:S.scope,attributes:p.attributes,onError:p.onError,load:async()=>I?(I=!1,S.payload):(await f()).payload,evaluateRemote:async C=>{if(A!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let T=d.evaluateFeatures,w=await m(t,T,{...C,attributes:Ce(C.attributes)});if(w.scope.projectId!==S.scope.projectId||w.scope.environment!==S.scope.environment)throw new o("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:w.generation,evaluatedAt:w.evaluatedAt,expiresAt:w.expiresAt,features:w.features,...w.merchandiseContext?{merchandiseContext:w.merchandiseContext}:{}}},onExperimentViewed:(C,T,w,x)=>O({kind:"experiment_exposure",generation:x,experimentId:C.key,variationId:T.key},w),onFeatureUsage:(C,T,w,x)=>O({kind:"feature_usage",generation:x,feature:C,value:T.value??null,source:T.source,ruleId:T.ruleId,...T.experimentResult?{variationId:T.experimentResult.key}:{}},w)}),i=v.refresh;function c(){clearTimeout(q),!s&&(D||A!==a||!v.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(v.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let b=()=>{D||u().catch(h)},P=v.subscribe(c),E=s?.subscribe(()=>{!D&&s.fresh&&u().catch(h)});function N(){D||(D=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",b),P(),E?.(),v.reset(),l.delete(N))}l.add(N);try{await v.init(),(p.attributes?.merchandise||p.attributes?.merchandiseId)&&await v.refreshRemote()}catch(C){throw N(),C}return c(),!s&&typeof window<"u"&&window.addEventListener("focus",b),Object.assign(v,{refresh:u,destroy:N})}return{features:g,reset(p){a++,p();for(let A of l)A()}}}import{z as Re}from"zod";function we(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=Re.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 g=d.grantOffer,p=await m(t,g,a({couponId:l,requestId:y}));return{offer:p.offer,reason:p.reason}},async resolveOffering(l){let y=d.resolveOffering,g=y.request.parse(a(l)),p=await m(t,y,g);return j(g,p.check,p.scope),p},async resolvePaywall(l){let y=d.resolvePaywall,g=y.request.parse(a(l)),p=await m(t,y,g);return j(g,p.paywall.check,p.scope),p},async previewAttach(l){let y=d.previewAttach;return m(t,y,a(l))}}}function Vt(t){return Te(t)}function Te(t){let e=te(t),n=e.request,r;try{r=oe(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let s=ce(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=ge(n,s.isIdentified,a,t.scope,t.configuration);return{session:e.session,...ae(n,r),...fe(n),...me(n),forFunnel(y){return s.assertActive(),we(n,y)},async features(y={}){return s.assertActive(),l.features(y)},track(y,g,p={}){return a.track(y,g,p)},flush(){return a.flush()},...s.methods}}function Ht(t){if(!B.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=se({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),s=U({...t,runToken:r.runToken,initialResponse:r});s.identify(t.customerToken);let a=await s.get();return{...r,...a,controller:s}}}}function Qt(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(f){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(f),I])}finally{clearTimeout(S)}}function g(f){throw f instanceof o&&(f.status===401||f.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear()),f}function p(f,S){if(S!==r)throw new o("IDENTITY_CHANGED","Process was detached during a request");let I=ee.parse(f);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 b of s)J(b,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,...O}=I.run,{contract:v,settlement:i,...c}=I,u=i&&(({accepted:b,...P})=>P)(i);return{...c,run:{...O,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let A=f=>(a.has(f)||a.set(f,e?.run.identity.binding?.id??null),a.get(f));async function D(f){let S=r,I=e?.run.identity.binding?.id??null,q=O=>{if(I!==(e?.run.identity.binding?.id??null))throw O;return g(O)};if(f.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new o("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(f.release,f.usedReceiptIds)).catch(q)}let h;if(f.operation==="get"){let{operation:O,customerToken:v,...i}=f;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:A(i.settlementRequestId)}:{}})).catch(q)}else if(f.operation==="review")h=await y(()=>t.adapter.review(f.receiptId)).catch(q);else{if(f.operation==="start")throw new o("INVALID_REQUEST","Use process.open for entry");{let{customerToken:O,...v}=f;h=await y(()=>t.adapter.command(v,A(v.requestId))).catch(q)}}return p(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(f){let S=r,I=await y(()=>t.adapter.open(f)).catch(g),q=p(I,S);if(!n){n=U({...t,runToken:I.runToken,initialResponse:q,process:{request:D,binding:A,restore(v){for(let[i,c]of Object.entries(v))a.set(i,c)}}});let h=n,O=h.submit;h.submit=async v=>{try{return await O(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 O({...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 f=r;p(await y(()=>t.adapter.syncIdentity()).catch(g),f),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(f){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:f}},subscribe(f){return s.add(f),()=>{s.delete(f)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear(),s.clear()}}}export{Vt as a,Te as b,Ht as c,Qt as d};
|
package/dist/chunk-C2BODHNY.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as t}from"./chunk-LFFBNGXP.js";import{kb as n}from"./chunk-O4535GJR.js";function r(e,o,a){return n(e,o,a,t)}export{r as a};
|
package/dist/chunk-EIYWDWXP.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as Me,c as ln}from"./chunk-JGG4R75K.js";import{d as on,f as qe,g as Le,h as sn,i as Ve,k as an}from"./chunk-ZX2RWS3T.js";import{a as _e,e as Ze,f as en,g as nn,h as tn,i as rn}from"./chunk-RKREEPCT.js";import{a as h}from"./chunk-SJNF6JDJ.js";import{b as un,e as cn}from"./chunk-SLUA7ABW.js";import{d as dn}from"./chunk-OEH47Y2L.js";import{Z as Ke,ma as Te}from"./chunk-O4535GJR.js";import{a as oe}from"./chunk-DSPLGTQI.js";import{Da as Ye,I as xe,Na as Xe}from"./chunk-MHEYMXGZ.js";async function pn(n){let{session:P,load:v}=Pn(n);try{return await v(),P}catch(e){throw P.destroy(),e}}function Pn(n){let P=n.view;if(!P?.paywall)throw new h("INVALID_REQUEST","The current node is not a Paywall");let v=P.paywall.receiptId,e=P.nodeId,f=P.visit,D=P.paywall.resolution,o=P.paywall,F="document"in D?{document:D.document,offering:D.offering,capabilities:D.capabilities}:null;function r(){let i=o.resolution;return"document"in i?i:F&&{...i,document:F.document,offering:F.offering,capabilities:Ze(i.capabilities,F.capabilities)}}function w(i){if(!en(i,D))throw new h("INVALID_RESPONSE","The pinned Paywall binding changed")}let d=!1,R=new Set,_=null;function T(){let i=r();if(i&&!d)for(let p of R)oe(p,structuredClone(i))}async function E(){U();let i=r();if(i)return structuredClone(i);if(!_){let p=(async()=>{if("document"in o.resolution||!n.resolvePaywall)throw new h("INVALID_RESPONSE","Public Paywall reader is unavailable");let I=await n.resolvePaywall(o.resolution);return U(),w(I),F={document:I.document,offering:I.offering,capabilities:I.capabilities},T(),r()})();_=p;let a=()=>{_===p&&(_=null)};p.then(a,a)}return _.then(p=>structuredClone(p))}let c=new AbortController,O=(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===f&&i.input.type==="paywall_quote")?.requestId??P.paywall.purchaseRequestId,G=0,M=null,q=new Set,j=null,m=new Map;function A(i){if(i.purchase&&i.purchase.receiptId!==v)throw new h("INVALID_RESPONSE","Purchase receipt changed");let p=i.run.paywall;return i.purchase??(p?.receiptId===v?p:null)}function U(){if(d)throw new h("IDENTITY_CHANGED","Paywall presentation has closed")}function X(i,p,a){if(U(),p!==G||a!==void 0&&o.quote?.operationId!==a)return!1;let I=o.selectionGeneration??0,u=i.run.paywall;if(u?.receiptId===v){if((u.selectionGeneration??0)<(o.selectionGeneration??0))return!1;w(u.resolution)}let g=A(i),Q=u?.receiptId===v&&(u.selectionGeneration??0)>I,J=Q?g?.quote??null:g?.quote??o.quote,K=g?.operation??(J?.operationId===o.quote?.operationId?o.operation:null);return J&&K&&nn(K,{operationId:J.operationId},"Purchase operation changed"),(Q||J?.operationId!==o.quote?.operationId)&&(G++,u?.receiptId===v&&(O=u.purchaseRequestId)),o={...o,...u?.receiptId===v?u:{},quote:J,operation:rn(o.operation,K,!0)},T(),!0}function k(i,p,a){return new Promise((I,u)=>{let g=!1,Q=()=>{clearTimeout(ye),c.signal.removeEventListener("abort",W)},J=ae=>{g||(g=!0,Q(),I(ae))},K=ae=>{g||(g=!0,Q(),u(ae))},W=()=>K(new h("IDENTITY_CHANGED","Paywall presentation has closed")),ye=setTimeout(()=>K(new h("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a)),Math.max(0,p-Date.now()));c.signal.addEventListener("abort",W,{once:!0}),c.signal.aborted&&W(),i.then(J,K)})}function B(i){return new Promise(p=>{let a=()=>{clearTimeout(I),c.signal.removeEventListener("abort",a),p()},I=setTimeout(a,i);c.signal.addEventListener("abort",a,{once:!0}),c.signal.aborted&&a()})}function L(i,p){U();let a=m.get(i)??n.pendingCommands?.find(g=>g.requestId===i)??n.pendingCommand;if(a?.operation==="submit"&&a.requestId===i&&a.nodeId===e&&a.visit===f){p.type==="paywall_quote"&&a.input.type==="paywall_quote"&&a.input.predecessor&&!p.predecessor&&(p={...p,predecessor:a.input.predecessor});let g=Te.parse(a),Q=Te.parse({...a,input:p});if(g.operation!=="submit"||Q.operation!=="submit"||JSON.stringify(g.input)!==JSON.stringify(Q.input))throw new h("CONFLICT","A purchase request cannot change its input");return m.set(i,g),g}let I=n.view;if(!I||I.nodeId!==e||I.visit!==f||I.paywall?.receiptId!==v)throw new h("PRECONDITION_FAILED","The Paywall visit has changed");let u=Te.parse({operation:"submit",requestId:i,nodeId:e,visit:f,revision:I.revision,input:structuredClone(p)});if(u.operation!=="submit")throw new h("INVALID_REQUEST","A purchase submission is required");return m.set(i,u),u}async function se(i,p){U();let{requestId:a,input:I}=i,u=Date.now()+3e4;q.add(a);try{let g=await k(n.submit(i),u,a);for(;g.run.pendingRequest?.requestId===a&&Date.now()<u&&!d&&(await B(Math.min(1e3,u-Date.now())),!(d||Date.now()>=u));)g=await k(n.resume(a),u,a);if(d)throw new h("IDENTITY_CHANGED","Paywall presentation has closed");if(g.run.pendingRequest?.requestId===a)throw new h("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a);if(!X(g,p,I.type==="paywall_confirm"||I.type==="paywall_cancel"?I.operationId:void 0))throw new h("PRECONDITION_FAILED","The purchase selection has changed");j===a&&(j=null)}catch(g){throw j=a,g instanceof h&&g.code==="COMMAND_PENDING"&&g.status===void 0&&m.delete(a),g}finally{q.delete(a)}}async function b(i){if(!o.quote)throw new h("INVALID_REQUEST","A quoted purchase is required");let p=i==="confirm"?"paywall_confirm":"paywall_cancel",a=[...m.values(),...n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])].find(u=>u.operation==="submit"&&u.input.type===p&&"operationId"in u.input&&u.input.operationId===o.quote.operationId),I=a?.operation==="submit"&&a.input.type===p&&"operationId"in a.input&&a.input.operationId===o.quote.operationId?a.requestId:crypto.randomUUID();if(await se(L(I,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.quote.operationId}),G),!o.operation)throw new h("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(o.operation)}let S={get view(){return structuredClone(r())},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]:[]),p=n.pendingPurchase;if(p&&(p.receiptId!==v||p.operationId!==o.quote?.operationId))return{type:"recover",operationId:p.operationId,requestId:i[0]?.requestId??null};let a=_e({quote:o.quote,operation:o.operation,requestId:i[0]?.requestId??j??O,pending:q.size>0||i.length>0||j!==null,destroyed:d,canReselect:o.canReselect});return a.type==="recover"&&a.requestId===null&&!d&&n.hasDurableJournal===!0&&!o.quote&&!o.operation&&(o.selectionGeneration??0)===0&&!p&&!i.length&&!q.size&&!O?{type:"native",operationId:null}:a},get pendingCancellation(){return!d&&(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===f&&i.input.type==="paywall_cancel"&&i.input.operationId===o.quote?.operationId)},subscribe(i){return d?()=>{}:(R.add(i),()=>R.delete(i))},async refresh(){U();let i=G,p=await n.get();if(X(p,i),p.run.paywall?.receiptId!==v)throw new h("PRECONDITION_FAILED","Paywall presentation has changed");return E()},preview(i){let p=r();if(!p)return Promise.reject(new h("PRECONDITION_FAILED","Load the Paywall presentation first"));if(O&&O!==i.requestId&&(M||o.canReselect!==!0))return Promise.reject(new h("COMMAND_PENDING","Retry the original purchase before starting another"));let a=p.document.buttons[i.actionId],I=a?.type==="checkout"?Ke(a.product,i.selection,p.capabilities):null;if(!I)return Promise.reject(new h("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let u=Xe(p.document.screen,I,i.selection,p.capabilities),g=O!==i.requestId&&(o.selectionGeneration??0)>0?{operationId:o.quote?.operationId??null,generation:o.selectionGeneration??0}:void 0;if(g&&o.canReselect!==!0)return Promise.reject(new h("COMMAND_PENDING","Original purchase requires authoritative termination"));let Q;try{Q=L(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:I,...Object.keys(u).length?{featureQuantities:u}:{},...g?{predecessor:g}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}})}catch(W){return Promise.reject(W)}if(O===i.requestId&&M)return M;O!==i.requestId&&G++;let J=G;O=i.requestId;let K=(async()=>{if(await se(Q,J),!o.quote)throw new h("INVALID_RESPONSE","The accepted quote is missing");return tn(o.quote,{productVersionId:I,featureQuantities:u},"The selected purchase changed"),structuredClone(o.quote)})();return M=K,K.then(()=>{M===K&&(M=null)},W=>{M===K&&(M=null),O===i.requestId&&n.pendingCommand?.requestId!==i.requestId&&W instanceof h&&W.status!==void 0&&W.status<500&&![401,425].includes(W.status)&&(O=null)}),K},confirm:()=>b("confirm"),cancel:()=>b("cancel"),async read(){if(U(),!o.quote)throw new h("INVALID_REQUEST","A quoted purchase is required");let i=o.quote.operationId,p=G,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 I=await n.get(void 0,{receiptId:v,operationId:i});U();let u=A(I);if(u?.quote&&u.quote.operationId!==i||u?.operation&&u.operation.operationId!==i)throw new h("INVALID_RESPONSE","Purchase operation changed");let g=X(I,p,i),Q=g?o.operation:u?.operation;if(!Q)throw new h("INVALID_RESPONSE","The current purchase result is missing");return g&&q.size===0&&!(n.pendingCommands?.length??(n.pendingCommand?1:0))&&(j=null),structuredClone(Q)},destroy(){d=!0,ne(),R.clear(),c.abort(),m.clear()}},ne=n.subscribe(i=>{d||i.nodeId!==e||i.visit!==f||i.paywall?.receiptId!==v||(i.paywall.selectionGeneration??0)<(o.selectionGeneration??0)||(w(i.paywall.resolution),o={...o,resolution:i.paywall.resolution},T())});return{session:S,load:E}}function fn(n){let P=new Set,v=new Set,e=null;async function f(r,w){let d=!1;for(;!n.stopped&&n.key===r&&n.client.pendingCommand?.requestId===w;){if(!n.client.settle)throw new h("COMMAND_PENDING","The original display acknowledgement is still pending");await n.client.settle(w),d=!0,n.client.pendingCommand?.requestId===w&&await new Promise(R=>setTimeout(R,1500))}n.stopped||n.key!==r||(d&&await n.client.get(),!(n.stopped||n.key!==r)&&P.add(r))}function D(r,w){e=w;let d=()=>{e===w&&(e=null),v.delete(r)};return w.then(d,R=>{d(),n.busy||n.fail(R)}),w}function o(r){if(n.reviewing||P.has(r)||v.has(r)||n.stopped)return;v.add(r);let w=async()=>{if(n.reviewing||n.stopped||n.key!==r||P.has(r)){v.delete(r);return}if(n.busy||n.client.pendingCommand){setTimeout(()=>{w()},250);return}let d=(async()=>{if(n.staleRead){if(await n.staleRead,n.stopped||n.key!==r)return;if(n.client.pendingCommand){setTimeout(()=>{w()},250);return}}let R=n.client.view,_=n.expected(),T=_.requestId;try{await n.client.submit({operation:"shown",..._})}catch(E){if(!(E instanceof h)||E.code!=="CONFLICT"||E.status!==409||n.client.pendingCommand)throw E;await n.client.get();let c=n.client.view;if(n.stopped||n.reviewing||n.key!==r||!c||!R||c.id!==R.id||c.source.versionId!==R.source.versionId||c.nodeId!==_.nodeId||c.visit!==_.visit||c.revision<=_.revision||c.stopped||!c.screen&&(!c.paywall||c.paywall.receiptId!==R.paywall?.receiptId)||!["running","waiting"].includes(c.status)||n.client.pendingCommand)throw E;let N=n.expected();T=N.requestId,await n.client.submit({operation:"shown",...N})}await f(r,T)})();D(r,d)};w()}function F(){if(e)return e;let r=n.client.pendingCommand;if(r?.operation!=="shown")return null;let w=n.key;return v.add(w),D(w,(async()=>{await n.client.retry(),await f(w,r.requestId)})())}return{report:o,settled:F,get inFlight(){return e}}}function mn(n){let P={},v=new Map;async function e(f){let D=n.client.view,o=D?.screen,F=o?.customerData.nodes[f.nodeId];if(n.stopped||n.busy||!D||!o||!F)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(f.action)){let E=n.document,c=E?Ye(E,f.nodeId):null,N=c?.type==="customer_data"?c.data.outputs?.[f.action]:void 0;N&&o.outputs.includes(N)?await n.perform(()=>n.client.submit({operation:"submit",...n.expected(),input:{type:"screen",output:N,answers:n.answers,selection:f.value?{[f.nodeId]:f.value}:{}}})):await n.onIntent?.(f,D);return}let w=f.action.startsWith("sources_")?F.resources.find(E=>E.key===f.value):null;if(f.action.startsWith("sources_")&&!w)throw new h("INVALID_REQUEST","Choose a current resource");let d=`${D.visit}:${f.nodeId}:${w?.key??""}`,R=v.get(d)??[null],T=P[f.nodeId]??{page:1,after:null,filter:"all",...w?{resourceKey:w.key}:{}};if(f.action==="filter"){let E=f.value;if(!E||!(F.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(E))throw new h("INVALID_REQUEST","Unknown data filter");T={page:1,after:null,filter:E},R.splice(0,R.length,null)}else if(f.action==="next"||f.action==="sources_next"){let E=w?.sources.at(-1),c=w?E?{kind:"ledger",cursor:{at:E.detail[0],id:E.id,type:"source"}}:null:o.dataCursors[f.nodeId];if(!c||!w&&!F.hasNext)return;R[T.page]=c,T={...T,page:T.page+1,after:c}}else if(f.action==="previous"||f.action==="sources_previous"){if(T.page<=1)return;T={...T,page:T.page-1,after:R[T.page-2]??null}}v.set(d,R),P={...P,[f.nodeId]:T},await n.perform(()=>n.client.get({nodeId:D.nodeId,visit:D.visit,revision:D.revision,components:P}))}return{get queries(){return P},intent:e,reset(){P={},v.clear()}}}function wn(n){let{doc:P,holder:v,reviewHolder:e,mountScreenPreview:f}=n,D=!1,o,F=0,r=null,w="",d,R=new Map,_=c=>c?`${c.id}:${c.nodeId}:${c.visit}:${c.revision}:${c.paywall?.quote?.operationId??""}`:"";async function T(c){if(n.stopped||!n.client.review||D&&c===o&&d?.active)return;let N=!D||c!==o;D||(w=_(n.client.view),R.set(w,structuredClone(n.answers))),D=!0,o=c,v.hidden=!0,n.suspend(!0),e.hidden=!1;let O=++F;N&&(d?.finish("dismissed"),r?.destroy(),r=null,e.replaceChildren(),d=Le(e,n.loadingOptions,"funnel",()=>{E()}));let G=N?d:void 0;try{if(G?.start(!1,n.client.view?.locale),O!==F||n.stopped)return;let M=n.client.review(c),q=await(G?.wait(M,qe)??M);if(n.stopped||O!==F||!D)return;if(!q.review)throw new h("INVALID_RESPONSE","Historical projection is missing");r?.destroy(),r=null,G||e.replaceChildren();let j=P.createElement("div"),m=G?Ve(j,e):()=>{};e.append(j);let A=q.run.locale.startsWith("zh"),U=P.createElement("p");U.textContent=A?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",j.append(U);for(let[k,B]of q.review.pages.entries()){let L=P.createElement("button");L.type="button",L.textContent=A?`\u7B2C ${k+1} \u9875`:`Page ${k+1}`,L.onclick=()=>{T(B.receiptId)},j.append(L)}if(q.review.page){let k=q.review.page,B=P.createElement("div");B.inert=!0,j.append(B),r=f(B,{mode:"live",rendererUrl:n.client.webViewUrl,title:k.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{O===F&&!n.stopped&&G?.present(m)},onError:se=>{if(O!==F||n.stopped)return;let b=new Error(se);G?.finish("error",b),r?.destroy(),r=null,j.remove(),n.fail(b)},onEscape:()=>{E()}});let L=r;if(L.update(k.document,q.run.locale,{serverInput:{bindings:k.inputs,answers:k.answers,values:k.values}}),await L.ready,n.stopped||O!==F||!D)return}let X=A?{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 k of[...q.review.coupons.map((B,L)=>`${A?"\u4F18\u60E0\u5238":"Coupon"} ${L+1}: ${X[B.status]}`),...q.review.purchases.map((B,L)=>`${A?"\u8D2D\u4E70":"Purchase"} ${L+1}: ${ln(B.status,A)}`)]){let B=P.createElement("p");B.textContent=k,j.append(B)}q.review.page||G?.present(m),n.client.view&&await n.enqueue(n.client.view)}catch(M){if(O!==F||n.stopped)return;G?.finish("error",M),r?.destroy(),r=null,e.replaceChildren(),n.fail(M)}}async function E(){if(!D||n.stopped||!n.client.review)return;let c=++F;d?.finish("dismissed");try{if(await n.client.review(),n.stopped||c!==F)return;D=!1,F++,d?.finish("dismissed"),r?.destroy(),r=null,e.replaceChildren(),e.hidden=!0,v.hidden=!1;let N=n.client.view;_(N)!==w?(R.set(w,structuredClone(n.answers)),n.resetScreen()):(R.delete(w),n.suspend(!1)),N&&await n.enqueue(N)}catch(N){if(c!==F||n.stopped)return;r?.destroy(),r=null,e.replaceChildren(),n.fail(N)}}return{get active(){return D},get receipt(){return o},open:T,exit:E,get drafts(){return new Map([...R].map(([c,N])=>[c,structuredClone(N)]))},stop(){D=!1,F++,d?.finish("dismissed"),r?.destroy(),r=null,e.replaceChildren(),e.hidden=!0,v.hidden=!1}}}function yn(n){if(!n.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let P=n.client.pageExperiments.bind(n.client),v=!1,e=!1,f=0,D=!1,o=!1,F="",r=()=>{let m=n.client.view;return JSON.stringify([m?.id,m?.source.versionId,m?.visit,m?.revision,m?.status,m?.stopped])},w=new Map,d=new Set,R={},_=new Map,T=un(n.appManifestRelease),E=()=>{for(let m of w.values())m.effect.revert();w.clear()},c=()=>{E();for(let m of _.values())m();_.clear()};function N(m){if(v||d.has(m))return;d.add(m);let A=f;P(n.appManifestRelease,[m]).catch(U=>{d.delete(m),!v&&A===f&&oe(n.onError,U)})}async function O(){if(v)return;F=r();let m=n.client.view;if(!m||m.stopped||!["running","waiting"].includes(m.status)){f++,c();return}if(document.visibilityState==="hidden")return;if(D){o=!0;return}D=!0;let A=++f,U=`${m.id}:${m.visit}:${m.revision}`,X=location.href;try{let[k,{applyVisualVariation:B}]=await Promise.all([P(n.appManifestRelease),import("./visual-dom-7IF7ITAK.js")]),L=n.client.view;if(v||A!==f||!L||L.stopped||!["running","waiting"].includes(L.status)||`${L.id}:${L.visit}:${L.revision}`!==U||location.href!==X)return;let se=new Set,b=new Set;for(let S of k.assignments){let ne=`${k.payload.environmentId}:${S.experimentKey}`;if(b.add(ne),_.has(ne)||_.set(ne,cn(ne,R)),!!S.inExperiment)for(let i of k.payload.experiments){if(i.key!==S.experimentKey||!xe(location.href,i.urlPatterns??[]))continue;let p=i.meta?.findIndex(J=>J.key===S.variationKey)??-1,a=i.variations[p];if(!a?.renderGuard)continue;let I=S.receiptId+":"+i.changeId,u=JSON.stringify([S.variationKey,a]);se.add(I);let g=w.get(I);if(g?.signature===u){g.effect.applied&&N(S.receiptId);continue}w.get(I)?.effect.revert(),w.delete(I);let Q=B(a,{requireUniqueTargets:!0,boundVariations:i.variations,allowJs:!1,onApplied:()=>N(S.receiptId),onError:J=>oe(n.onError,J)});w.set(I,{signature:u,effect:Q}),Q.applied&&N(S.receiptId)}}for(let[S,ne]of w)se.has(S)||(ne.effect.revert(),w.delete(S));for(let[S,ne]of _)b.has(S)||(ne(),_.delete(S))}catch(k){A===f&&c(),!v&&A===f&&oe(n.onError,k)}finally{D=!1,o&&!v&&(o=!1,O())}}let G=n.client.subscribe(()=>{if(r()===F)return;F=r(),f++;let m=n.client.view;(!m||m.stopped||!["running","waiting"].includes(m.status))&&c(),e&&O()}),M=dn(()=>{f++,c(),e&&O()}),q=()=>{f++,E()};document.addEventListener("visibilitychange",q);let j=Me({document,run:async()=>{e&&await O()},delay:()=>e&&!v?15e3:void 0});return{async start(){e||v||(e=!0,await j.refresh())},refresh:O,destroy(){v=!0,f++,j.destroy(),document.removeEventListener("visibilitychange",q),G(),M(),c(),T.destroy()}}}var Je=5e3;async function Rn(n,P,v){let e=P,[{mountScreenPreview:f},{showPaywall:D}]=await Promise.all([import("./screen-renderer-WOMWOEYL.js"),import("./paywall-CGBFHFRU.js")]),o=e.client.identitySignal;e.signal?.throwIfAborted(),o?.throwIfAborted();let F=e.appManifestRelease?yn({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;F?.start();let r=n.ownerDocument,w=an(r),d=r.createElement("section"),R=r.createElement("div"),_=r.createElement("div"),T=r.createElement("div"),E=r.createElement("button");T.hidden=!0,E.type="button";let c=r.createElement("p"),N=r.createElement("p"),O=r.createElement("button"),G=r.createElement("button"),M=r.createElement("button"),q=r.createElement("dialog"),j;d.dataset.indianaFunnel="",d.setAttribute("aria-busy","false"),d.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",_.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",c.setAttribute("role","status"),N.setAttribute("role","alert"),N.hidden=!0,O.type=G.type=M.type="button",_.append(O,c,N,M,E,G),d.append(R,T,_),n.append(d);let m=null,A=null,U=null,X="",k="",B="",L="",se="",b=!1,S=0,ne=!1,i="",p=null,a=Promise.resolve(),I=!e.client.view,u=v,g,Q,J="",K,W=!1,ye=null,ae=!1,De=()=>e.client.pendingCommand?.operation==="close",re=null,x=null,ze=Me({document:r,run:async()=>{(!A?.observing||e.client.pendingCommand)&&await $e()},delay:()=>{if(!(b||!U||!["running","waiting"].includes(U.status)&&!e.client.pendingCommand)&&!(A?.observing&&!e.client.pendingCommand))return U.pendingRequest||e.client.pendingCommand?1500:Je},hiddenDelay:()=>!b&&e.client.pendingCommand?15e3:void 0}),Y=null;function Ue(){return x&&e.client.hasDurableJournal===!0&&Y?.acknowledged===!0&&Y.operationId===x.operationId&&e.client.view?.id===Y.runId&&e.client.view?.status==="closed"&&e.client.view.revision===Y.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?x:null}function je(t){let s=t.run.paywall;if(Y&&t.settlement?.requestId===Y.requestId&&t.settlement.state==="settled"&&t.settlement.operationId===null&&t.run.id===Y.runId&&t.run.status==="closed"&&!t.run.pendingRequest&&t.run.revision===Y.revision+1&&t.run.nodeId===Y.nodeId&&t.run.visit===Y.visit&&s?.receiptId===Y.receiptId&&s.selectionGeneration===Y.selectionGeneration&&(s.quote?.operationId??null)===Y.operationId&&(s.operation?.operationId??s.quote?.operationId??null)===Y.operationId){let l=Y.operationId===null&&s.selectionGeneration===0&&!s.quote&&!s.operation&&!s.purchaseRequestId,te=_e({quote:s.quote,operation:s.operation,requestId:s.purchaseRequestId,pending:!1,destroyed:!1,canReselect:s.canReselect});(l||s.canReselect===!0&&te.type==="native")&&(Y.acknowledged=!0)}}let Ce=null,ke=new Set,pe={},le=(t,s=null)=>{b||(Ce=s,N.textContent=t instanceof Error?t.message:"Request failed",N.hidden=!1,M.hidden=e.client.pendingCommand===null,oe(e.onError,t))};function he(){let t=e.client.view;if(!t)throw new h("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let V=wn({client:e.client,doc:r,holder:R,reviewHolder:T,mountScreenPreview:f,loadingOptions:e,get stopped(){return b},get answers(){return pe},suspend(t){A?.setSuspended(t)},resetScreen(){X="",k="",B=""},enqueue:fe,fail:le}),Fe=fn({client:e.client,expected:he,fail:le,get stopped(){return b},get reviewing(){return V.active},get key(){return X},get busy(){return S},get staleRead(){return p}}),Se=mn({client:e.client,expected:he,perform:Re,onIntent:e.onCustomerDataIntent,get stopped(){return b},get busy(){return S},get document(){return m?.document},get answers(){return pe}}),Ne=t=>`${t.id}:${t.nodeId}:${t.visit}`,Pe=t=>t&&(t.screen||t.paywall)?Ne(t):"";function Ie(){let t=e.client.view;O.disabled=!V.active&&(S>0||!!e.client.pendingCommand||!t?.canBack||t.stopped||!["running","waiting"].includes(t.status)||!Pe(t)||k!==Pe(t))}async function Be(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 h("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Re(t,s=!1){if(!((S||ae||re||x)&&!s||b||V.active&&!s)){S++,d.setAttribute("aria-busy","true"),Ie(),N.hidden=!0,Ce=null;try{if(s||await Be(Fe.inFlight),b)return;let l=await t();b||await fe(e.client.view??l.run)}catch(l){le(l,e.client.pendingCommand?.requestId??null)}finally{S=Math.max(0,S-1),d.setAttribute("aria-busy",String(S>0)),b||(M.hidden=e.client.pendingCommand===null,Ie())}}}function Ee(){ze.schedule()}async function $e(){if(!(b||ne||S)){if(V.active){await V.open(V.receipt);return}ne=!0;try{let t=e.client.pendingCommand;t&&e.client.settle&&await e.client.settle(t.requestId);let s=e.client.view,l=Se.queries,te=await e.client.get(s?.screen&&Object.keys(l).length?{nodeId:s.nodeId,visit:s.visit,revision:s.revision,components:l}:void 0);!b&&l===Se.queries&&await fe(e.client.view??te.run)}catch(t){le(t)}finally{ne=!1}}}function Oe(t,s){if(u?.active){let te=u;return te.setDismissHandler(()=>We(te)),te}let l=Le(n,e,"funnel",()=>We(l));return u=l,l.start(t,s),l}function We(t){b||W||(W=!0,t.finish("dismissed"),ge(),d.hidden=!0,e.client.view?be().finally(ue):ue())}function He(){clearTimeout(K?.timeout),K=void 0}function ge(){He(),g?.abort(),g=void 0,m?.destroy(),m=null,A?.destroy(),A=null,Q?.(),Q=void 0,q.open&&q.close(),R.replaceChildren(),X="",k="",B="",se=""}function Ge(t){let s=t.screen?.presentation;if(!s||s.type==="inline"){q.open&&q.close(),d.parentElement!==n&&n.append(d);return}d.parentElement!==q&&(q.append(d),n.append(q));let l={sm:420,md:640,lg:900};q.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"}`,q.setAttribute("aria-label",(j?.screen===t.screen?.content.document.name?j?.label:void 0)??m?.document?.name??t.screen?.content.document.name??"Funnel")}async function gn(t){if(b||W||ae&&(De()||["running","waiting"].includes(t.status)))return;U=t,Ce&&e.client.pendingCommand?.requestId!==Ce&&(N.hidden=!0,Ce=null);let s=t.locale.startsWith("zh");if(E.textContent=s?"\u56DE\u770B":"History",E.hidden=!e.client.review,O.textContent=V.active?s?"\u8FD4\u56DE\u5F53\u524D":"Return to current":s?"\u8FD4\u56DE":"Back",G.textContent=s?"\u5173\u95ED":"Close",M.textContent=s?"\u91CD\u8BD5":"Retry",Ie(),M.hidden=e.client.pendingCommand===null,c.textContent=t.pendingRequest?s?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?s?"\u7B49\u5F85\u4E2D":"Waiting":"",i!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(i=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,oe(e.onState,structuredClone(t))),b||W)return;if((!t.pendingRequest||ae&&t.status==="closed")&&["closed","ineligible","failed"].includes(t.status)){ue();return}if(t.stopped||e.client.configurationReady===!1){V.stop(),ge(),u?.finish("skipped"),d.hidden=!0,Ee();return}if(d.hidden=!1,V.active){Ee();return}let l=Pe(t),te=e.client.view;if(te&&te.revision>t.revision&&Pe(te)!==l)return;let Qe=!t.instruction&&!t.pendingRequest&&t.nodeType==="screen"&&["running","waiting"].includes(t.status);l!==X&&(X&&u?.finish("dismissed"),ge(),X=l,pe={...t.answers},Se.reset());let me=Ne(t);if(J===me){d.hidden=!0;return}if(Qe&&!l){d.hidden=!0;let C=Oe(!0,t.locale);!b&&!W&&K?.key!==me&&(He(),K={key:me,timeout:setTimeout(()=>{let y=e.client.view;if(!C.active||!y||Ne(y)!==me)return;J=me;let ee=new Error("Funnel screen preparation timed out");C.finish("error",ee),ge(),le(ee)},qe)}),Ee();return}He();let ie=C=>{let y=e.client.view;return!b&&!W&&!ye&&!C.aborted&&e.client.configurationReady!==!1&&!!y&&!y.stopped&&!["closed","ineligible","failed"].includes(y.status)&&Pe(y)===l},Z=(C,y)=>{ie(y)&&(J=l,u?.finish("error",C),ge(),d.hidden=!0,le(C))};if(l||(Ge(t),t.instruction?.type!=="event"&&t.instruction?.type!=="open_url"&&u?.finish("skipped")),t.screen){let C=t.screen.content;if(!m){let z=t.screen.presentation.type!=="inline",we=Oe(z,t.locale);if(b||W)return;let de=(g=new AbortController).signal;Ge(t),Q=z?sn(q):Ve(d,n),m=f(R,{mode:"live",rendererUrl:e.client.webViewUrl,title:C.document.name,onAction(ce,ve={},bn={}){if(V.active||!ie(de)||k!==l)return;pe={...pe,...bn};let Cn=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:Ae})=>Object.hasOwn(pe,Ae)).map(({variable:Ae})=>[Ae,pe[Ae]]));Re(()=>e.client.submit({operation:"submit",...he(),input:{type:"screen",output:ce,answers:Cn,selection:ve}}))},onAnswers:ce=>{V.active||!ie(de)||k!==l||(pe={...pe,...ce})},onCustomerDataIntent:ce=>{V.active||!ie(de)||k!==l||Se.intent(ce).catch(le)},onEscape:()=>{!ie(de)||k!==l||V.active||re||x||be()},onError:ce=>{let ve=new Error(ce);k===l?le(ve):Z(ve,de)},onRendered:ce=>{if(!(!ie(de)||k===l))try{we.present(ve=>{Q?.(),Q=void 0,ce&&(j={screen:C.document.name,label:ce},q.setAttribute("aria-label",ce)),z&&(q.showModal(),!ve&&e.loading!=="host"&&on(q,t.screen.presentation.type)),k=l,Ie()}),ie(de)&&Fe.report(l)}catch(ve){Z(ve,de)}}})}let y={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:pe,values:t.screen.values}},ee=JSON.stringify([C,t.locale,y.parameters,t.screen.inputs,t.screen.values]);if(ee!==B)m.update(C.document,t.locale,y),B=ee,L=JSON.stringify(y.capabilities),se=JSON.stringify(y.customerData);else{let z=JSON.stringify(y.capabilities);z!==L&&(m.updateCapabilities(y.capabilities),L=z),JSON.stringify(y.customerData)!==se&&(m.updateCustomerData(y.customerData),se=JSON.stringify(y.customerData))}let H=m;if(H)try{await(u?.wait(H.ready)??H.ready)}catch(z){g&&Z(z,g.signal)}}else if(t.paywall&&!A){let C=Oe(!0,t.locale);if(b||W)return;let y=(g=new AbortController).signal;Ge(t);let ee=await D(R,{loading:"host",signal:y,canInteract:()=>ie(y)&&!V.active&&!re&&!x,beforeAction:async()=>{S++;try{await Be(Fe.settled()),N.hidden=!0,Ce=null}finally{S=Math.max(0,S-1)}},start:()=>pn(e.client),onObservationChange:Ee,onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,checkoutNavigation:e.checkoutNavigation,resolveOfferId:e.resolveOfferId,onEvent:e.onEvent,onOpenUrl:H=>e.onOpenUrl?e.onOpenUrl({receiptId:t.paywall.receiptId,url:H,openIn:"same_window"}):r.defaultView?.location.assign(H),onAction:async H=>{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:H,answers:{}}});await fe(e.client.view??z.run)},onError:H=>{k===l?le(H):Z(H,y)}},{quoteError:H=>oe(e.onError,H),present(H){ie(y)&&(C.present(()=>{H(),k=l,Ie()}),ie(y)&&Fe.report(l))},async dismiss(){b||y.aborted||V.active||re||x||!ae&&!ie(y)||(ae=!0,await be())}}).catch(H=>(Z(H,y),null));!ie(y)&&!(ae&&!b&&!y.aborted)?ee?.host?.destroy():ee&&(A=ee.host,A?.setSuspended(V.active))}if(b||W)return;Ie();let $=t.instruction;if($&&($.type==="open_url"||$.type==="event")&&!ke.has($.receiptId)){let C=r.createElement("button");C.type="button",C.textContent=$.type==="open_url"?`${s?"\u524D\u5F80":"Continue to"} ${new URL($.url).host}`:s?"\u7EE7\u7EED":"Continue",C.onclick=()=>{let y=he(),ee=$.type==="open_url"&&!e.onOpenUrl&&$.openIn==="new_window"?vn($.url):null;Re(async()=>{let H="success";if($.type==="open_url")if(e.onOpenUrl)try{H=await e.onOpenUrl({receiptId:$.receiptId,url:$.url,openIn:$.openIn})===!1?"failed":"opened"}catch(we){oe(e.onError,we),H="failed"}else H=$.openIn==="new_window"&&!ee?"failed":"opened";if($.type==="event"){if(!e.onEvent)throw new h("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent($.event)}if(b||e.client.view?.nodeId!==y.nodeId||e.client.view.visit!==y.visit)throw new h("PRECONDITION_FAILED","The client action visit changed");let z=await e.client.submit({operation:"submit",...y,input:{type:"client_action",receiptId:$.receiptId,outcome:H}});return ke.add($.receiptId),$.type==="open_url"&&!e.onOpenUrl&&$.openIn==="same_window"&&r.defaultView?.location.assign($.url),z})},u?.active?u.present(()=>R.replaceChildren(C)):R.replaceChildren(C)}!t.pendingRequest&&t.status==="completed"&&!ke.has(`complete:${t.id}`)&&(ke.add(`complete:${t.id}`),oe(e.onComplete,structuredClone(t))),Ee()}function vn(t){let s=r.defaultView?.open(t,"_blank")??null;return s&&(s.opener=null),s}function fe(t){return Ie(),a=a.catch(()=>{}).then(async()=>{try{await gn(t)}catch(s){throw u?.active&&(J=Ne(t),u.finish("error",s),ge(),d.hidden=!0),s}}),a}let hn=e.client.subscribe(t=>{I||(!ae&&(t.stopped||e.client.configurationReady===!1||X&&k!==X&&(Pe(t)!==X||["closed","ineligible","failed"].includes(t.status)))&&(ge(),u?.finish("dismissed"),d.hidden=!0),fe(t).catch(le))}),In=e.client.subscribeError?.(le);function be(t){if(ye)return ye;if(b||!t&&(re||x))return Promise.resolve();let s=!t&&De();return!s&&e.client.view&&!["running","waiting"].includes(e.client.view.status)?(U=e.client.view,ue(),Promise.resolve()):(ye=Re(async()=>{let l=s?await e.client.retry():await e.client.submit({operation:"close",...t??he()});return t&&je(l),l},!0).then(()=>{let l=e.client.view;l?.status==="closed"&&!De()&&(U=l,ue())}).finally(()=>{ye=null}),ye)}function ue(){F?.destroy(),!b&&(b=!0,e.signal?.removeEventListener("abort",ue),o?.removeEventListener("abort",ue),u?.finish("dismissed"),ze.destroy(),hn(),In?.(),ge(),V.stop(),q.remove(),d.remove(),w(),oe(e.onDismiss,U?structuredClone(U):null))}O.onclick=()=>{if(!O.disabled){if(V.active){V.exit();return}Re(()=>e.client.submit({operation:"back",...he()}))}},E.onclick=()=>{V.open()},G.onclick=()=>{u?.active?u.dismiss():re||be()},M.onclick=()=>{De()?be():Re(()=>e.client.retry())},q.addEventListener("cancel",t=>{t.preventDefault(),u?.active?u.dismiss():re||be()}),e.signal?.addEventListener("abort",ue,{once:!0}),o?.addEventListener("abort",ue,{once:!0});try{let t=e.client.view;if(t)((e.client.viewAgeMs??Je)>=Je||t.instruction?.type==="evaluate_segment")&&(p=$e().finally(()=>{p=null})),await fe(t);else{d.hidden=!0;let s=Oe(e.client.view?.screen?.presentation.type!=="inline",e.client.view?.locale);if(b||W)throw new DOMException("Presentation cancelled","AbortError");let l=await s.wait(e.client.get(),qe);I=!1,await fe(e.client.view??l.run)}}catch(t){throw u?.finish("error",t),ue(),t}return{destroy:ue,refresh:$e,get recovery(){let t=Ue();if(t)return t;if(!b&&!S&&!ae&&!re&&A){let s=A.recovery;if(s.type!=="native")return s}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??x?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(re)return re;let t=Ue();if(t)return Promise.resolve(t);let s=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??x?.operationId??null,l=()=>({type:"recover",operationId:s,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let Z=A?.recovery;return Promise.resolve(Z&&Z.type!=="native"&&Z.type!=="cancel"?Z:l())}let te=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(Z=>Z.operation==="close");if(b&&!(te||x&&e.client.view?.status==="closed")||S||ne||ye||V.active||!A&&!x&&!te)return Promise.resolve(l());let Qe=A,me=(async()=>{try{if(!x&&te){let C=await e.client.retry();return await fe(e.client.view??C.run),l()}if(!x){let C=await Qe.prepareFallback();if(C.type!=="native")return C;if(e.client.hasDurableJournal!==!0)return l();x=C}let Z=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(Z.length){let C=Z.find(ee=>ee.operation==="close");if(!C||!Y||C.requestId!==Y.requestId)return l();let y=await e.client.retry();je(y),await fe(e.client.view??y.run)}else{let C=e.client.view,y=C?.paywall;if(!C||!y||y.selectionGeneration===void 0||(y.quote?.operationId??null)!==x.operationId||x.operationId!==null&&y.canReselect!==!0)return l();let ee=y.selectionGeneration,H=await e.client.get();await fe(e.client.view??H.run);let z=e.client.view,we=z?.paywall;if(!z||!we||!["running","waiting"].includes(z.status)||z.stopped||z.id!==C.id||z.nodeId!==C.nodeId||z.visit!==C.visit||we.receiptId!==y.receiptId||we.selectionGeneration!==ee||(we.quote?.operationId??null)!==x.operationId||x.operationId!==null&&we.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return l();let de=he();Y={runId:z.id,operationId:x.operationId,revision:de.revision,requestId:de.requestId,nodeId:z.nodeId,visit:z.visit,receiptId:we.receiptId,selectionGeneration:ee,acknowledged:!1},await be(de)}let $=Ue();return $?(ue(),$):l()}catch(Z){return le(Z),l()}})();re=me;let ie=()=>{re===me&&(re=null)};return me.then(ie,ie),me},review:V.open,exitReview:V.exit,get unappliedDrafts(){return V.drafts}}}function at(n,P,v){return Rn(n,P,v)}export{yn as a,Rn as b,at as c};
|
package/dist/chunk-LFFBNGXP.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as de}from"./chunk-RKREEPCT.js";import{a as H,b as B}from"./chunk-5HJMAZ7A.js";import{a as s}from"./chunk-SJNF6JDJ.js";import{a as le,c as ce}from"./chunk-2ZJ5CS5Q.js";import{$ as X,Ea as re,Ia as te,Ja as oe,Oa as J,Pa as ie,bb as se,jb as ue,ma as k,mb as ae,oa as Z,pb as U,q as W,wa as ee,xa as ne}from"./chunk-O4535GJR.js";import{a as $}from"./chunk-MHEYMXGZ.js";function me(e){return Ee({...e,namespace:"commands",identity:[e.runToken]})}function Ee(e){let n,a,o=()=>new s("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),t=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,a=e.locks??globalThis.navigator?.locks,!n||!a||!globalThis.crypto?.subtle)throw o();let f=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??U).href,...e.identity])),u=new Uint8Array(await crypto.subtle.digest("SHA-256",f));return`indiana.funnel.${e.namespace}.v1.`+Array.from(u,r=>r.toString(16).padStart(2,"0")).join("")});t.catch(()=>{});async function d(f){try{let u=await t;return await a.request(u,{mode:"exclusive"},()=>f(u))}catch(u){throw u instanceof s?u:o()}}function c(f){let u=n.getItem(f);if(u===null)return{revision:0,entry:null};if(u.length>1048576)throw o();let r=JSON.parse(u);if(!r||typeof r!="object"||!("revision"in r)||!("entry"in r)||!Number.isSafeInteger(r.revision)||Number(r.revision)<0)throw o();return{revision:Number(r.revision),entry:r.entry}}return{read:()=>d(c),write:(f,u)=>d(r=>{if(c(r).revision!==f)return null;if(!Number.isSafeInteger(f+1))throw o();let m=JSON.stringify({revision:f+1,entry:u});if(m.length>1048576)throw o();return n.setItem(r,m),f+1})}}function pe(e,n){let a=te.safeParse(n);if(!a.success)throw new s("INVALID_RESPONSE","Funnel response contract changed");let o=a.data;if(e.scope&&(o.scope.projectId!==e.scope.projectId||o.scope.environment!==e.scope.environment))throw new s("SCOPE_MISMATCH","Funnel scope changed");return o}async function fe(e,n){let a=ee.parse(n),{artifact:o,environmentId:t}=a.content,d=new H(e.baseUrl??U).origin,c=new H(o.url,d);if(c.origin!==d||c.username||c.password||c.search||c.hash||c.pathname!==`/api/v1/configuration/${t}/artifacts/${o.sha256}`)throw new s("INVALID_RESPONSE","Public Paywall locator is not trusted");let f=new AbortController,u,r=new Promise((m,y)=>{u=setTimeout(()=>{let w=new s("TIMEOUT","Public Paywall read timed out");f.abort(w),y(w)},Z.initializationMs)}),g=(async()=>{let m=await(e.fetch??globalThis.fetch)(c,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:f.signal});if(f.signal.aborted&&(m.body?.cancel().catch(()=>{}),f.signal.throwIfAborted()),!m.ok||!m.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(m.headers.get("content-length"))>o.byteLength)throw m.body?.cancel().catch(()=>{}),new s("INVALID_RESPONSE","Public Paywall is unavailable");let y=await le(m,o.byteLength,{signal:f.signal,error:w=>new s("INVALID_RESPONSE",w==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!ce(y,o))throw new s("INVALID_RESPONSE","Public Paywall digest or size changed");return ne(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(y)))})();try{return await Promise.race([g,r])}finally{clearTimeout(u)}}var K=(e,n)=>new s(e,n);function ze(e){return ue(e,K)}var Fe=3,Se=2e3;function be(e){return e instanceof TypeError||e instanceof s&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Te(e){for(let n=1;;n++)try{return await e.refresh()}catch(a){if(n===Fe||!be(a))throw a;await new Promise(o=>setTimeout(o,n*Se))}}async function Y(e,n,{predict:a=!0}={}){let o=n.instruction;if(o?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new s("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==o.environmentId)throw new s("SCOPE_MISMATCH","Evaluation environment changed");let t=null,d;if(a)try{let c=await e.funnel(n.source.id,n.source.versionId);d=c.manifest.generation,t=Ne(e,n,c)}catch{t=null}return d??=e.snapshot?.generation??(await Te(e)).generation,{advance:{policyRevision:o.policyRevision,generation:d},prediction:t}}function Ne(e,n,a){let o=n.instruction;if(o?.type!=="evaluate_segment"||!a.growth||a.control.evaluationMode!=="local"||a.control.evaluationRevision!==o.policyRevision)return null;let{analyticsConfig:t,remoteFeatures:d,...c}=a.growth,f=se({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:o.policyRevision,document:a.document,payload:X.parse(c)}),u=Ae(f,a.document,{...n,...o}),r=u.steps.at(-1),g=u.boundary??(r?.result.port==="value"?{nodeId:r.nodeId,visit:n.visit+u.steps.length-1}:null);return g?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:g.nodeId,visit:g.visit,terminal:!u.boundary}:null}function Ae(e,n,a){return ae(e,n,a,K)}import{z as A}from"zod";var ge=k.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new s("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),Ie=A.strictObject({schemaVersion:A.literal(1),scope:$,runId:A.uuid(),funnelId:A.uuid(),versionId:A.uuid(),processBindingIds:A.record(A.uuid(),A.uuid().nullable()).optional(),command:ge.optional(),closeCommand:ge.refine(e=>e.operation==="close").optional(),purchase:A.strictObject({receiptId:A.uuid(),operationId:A.uuid(),generation:A.number().int().nonnegative()}).optional(),closed:A.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),T=()=>new s("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),j=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function V(e,n){if(!e||!n)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,n)){let a={...e.processBindingIds};delete a[n],e={...e,processBindingIds:a}}return e.command?.requestId===n?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===n?{...e,closeCommand:void 0}:e}function ye(e){let n=0,a=null,o=u=>JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]),t=Promise.resolve();async function d(){let u=await e.read();if(!Number.isSafeInteger(u.revision)||u.revision<0)throw new s("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:u.revision,entry:u.entry===null?null:Ie.parse(u.entry)}}function c(u){let r=t.then(u);return t=r.catch(()=>{}),r}async function f(u){for(let r=0;r<4;r++){let g=await d();if(g.entry&&a!==null&&o(g.entry)!==a)throw T();let m=u(g.entry,g.revision);if(j(g.entry,m)){n=g.revision;return}let y=await e.write(g.revision,m);if(y!==null){if(!Number.isSafeInteger(y)||y<=g.revision)throw T();n=y;return}}throw T()}return{bind(u){let r=JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]);if(a!==null&&a!==r)throw T();a=r},async load(){let u=await d();return n=u.revision,a=u.entry?o(u.entry):null,u.entry},retain(u){let r=Ie.parse(u),g=r.command;return!g||a!==null&&o(r)!==a?Promise.reject(T()):(a??=o(r),c(()=>f((m,y)=>{if(m&&!j(o(m),o(r)))throw T();if(m&&r.processBindingIds){for(let[w,v]of Object.entries(r.processBindingIds))if(m.processBindingIds&&Object.hasOwn(m.processBindingIds,w)&&m.processBindingIds[w]!==v)throw T();m={...m,processBindingIds:{...m.processBindingIds,...r.processBindingIds}}}if(!m){if(y!==n&&g.operation!=="close")throw T();return r}if(!m.command)return{...m,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&m.command.operation!=="close"){if(m.command.requestId===g.requestId||m.closeCommand&&!j(m.closeCommand,g))throw T();return{...m,closeCommand:g,closed:!0}}if(!j(m.command,g))throw T();return m})))},observePurchase(u,r,g,m){return c(()=>f((y,w)=>{if(!y&&w!==n||y&&o(y)!==o({...u,schemaVersion:1}))throw T();if(y?.purchase&&y.purchase.generation>r.generation)return V(y,m);if(y?.purchase&&y.purchase.generation===r.generation&&y.purchase.operationId!==r.operationId)throw T();return g?!y?.purchase||y.purchase.operationId!==r.operationId?V(y,m):V(y.command?{...y,purchase:void 0}:null,m):V({schemaVersion:1,...u,...y,purchase:r},m)}))},settle(u){return c(()=>f(r=>V(r,u)))}}}function sn(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function G(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((t,d)=>G(t,n[d]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let a=Object.entries(e),o=Object.entries(n);return a.length===o.length&&a.every(([t,d])=>Object.hasOwn(n,t)&&G(d,Reflect.get(n,t)))}function we(e,n){let a=n&&{...n},o=null,t=0,d=-1,c=0,f=new AbortController;function u(){c++,f.abort(new s("IDENTITY_CHANGED","Run identity changed")),f=new AbortController}let r=!1,g,m=0,y=new Set;return{get scope(){return a},bindScope(w){if(a&&(a.projectId!==w.projectId||a.environment!==w.environment))throw new s("SCOPE_MISMATCH","Run scope changed");a??={...w}},get view(){return o},get currentView(){return d===c?o:null},get viewAgeMs(){return o&&d===c?performance.now()-t:void 0},get generation(){return c},get signal(){return f.signal},get disposed(){return r},get customerToken(){return g},get readSequence(){return m},nextRead(){return++m},assertCurrent(w,v="Run identity changed during the request"){if(w!==c||r)throw new s("IDENTITY_CHANGED",v)},assertRun(w){if(o&&(w.id!==o.id||w.source.type!==o.source.type||w.source.id!==o.source.id||w.source.versionId!==o.source.versionId||w.locale!==o.locale||!G(w.parameters,o.parameters)))throw new s("INVALID_RESPONSE","Run version changed");if(e&&w.source.id!==e)throw new s("INVALID_RESPONSE","Run belongs to another Funnel")},publish(w,v,O,_,l){if(!(w.operation==="review"&&o&&o!==O&&v.run.revision<=o.revision)&&!(o&&v.run.revision===o.revision&&_!==void 0&&_<m)&&(w.operation==="review"&&!v.run.stopped&&["running","waiting"].includes(v.run.status)&&o&&d===c&&v.run.nodeId===o.nodeId&&v.run.visit===o.visit&&v.run.revision===o.revision&&(v.run.screen=o.screen,(o.paywall?.quote?.operationId===v.review?.activeOperationId||!o.paywall?.quote&&v.review?.activeOperationId===null)&&(v.run.paywall=o.paywall)),!(o?.paywall&&v.run.paywall&&o.paywall.receiptId===v.run.paywall.receiptId&&(v.run.paywall.selectionGeneration??0)<(o.paywall.selectionGeneration??0)))){if(!o||v.run.revision>=o.revision)o=v.run,t=performance.now(),d=c;else if(!l)return;if(o&&d===c)for(let p of y)try{p(structuredClone(o))}catch{}}},identify(w){if(r)throw new s("IDENTITY_CHANGED","Controller was reset");if(!W.test(w))throw new s("INVALID_TOKEN","Customer credential required");u(),g=w},subscribe(w){return y.add(w),()=>y.delete(w)},reset(){r||(r=!0,u(),g=void 0,o=null,y.clear())}}}var Q=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function pn(e,n,a="A server API key is required"){if(typeof window<"u")throw new s("SERVER_ONLY",n);if(!Q.test(e))throw new s("INVALID_TOKEN",a)}function fn(e){let n=B(e);return n.identify(e.apiKey),n}function he(e,n){if(!e)return;let a=n?.execution,o=a?.provider==="merchant"?"merchant":a?.provider==="stripe"?a.executor==="merchant"?"record_only":"indiana":n&&["apple","google"].includes(n.provider)?"native":n?.provider==="stripe"?"indiana":void 0;if(!o||!e.allowed.includes(o))throw new s("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function x(e){let{customerToken:n,...a}=e;return a}var Oe=e=>!(e instanceof s&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof s)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function ve({journal:e,state:n,call:a,processIdentity:o}){let t=null,d=null,c=!1,f={command:null,close:null},u=new Set,r,g=null,m=e?e.load().then(l=>{if(n.disposed)throw new s("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=l,!l)return;if(o){if([l.command,l.closeCommand].some(S=>S&&!Object.hasOwn(l.processBindingIds??{},S.requestId)))throw new s("COMMAND_STORAGE_INVALID","The original process identity is missing");o.restore(l.processBindingIds??{})}if(n.scope&&(l.scope.projectId!==n.scope.projectId||l.scope.environment!==n.scope.environment))throw new s("SCOPE_MISMATCH","Pending command belongs to another scope");if(r=l.purchase,c=l.closed===!0,!l.command)return;let p=l.command;t=p.operation==="close"?null:p,d=p.operation==="close"?p:l.closeCommand?.operation==="close"?l.closeCommand:null,d&&(c=!0);for(let S of[t,d])S&&u.add(S.requestId)}):Promise.resolve();m.catch(()=>{});async function y(l){e&&await m;let p=n.generation;if(e){if(!n.view||!n.scope)throw new s("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:x(l),...o?{processBindingIds:{[l.requestId]:o.binding(l.requestId)}}:{}})}if(p!==n.generation||t!==l&&d!==l)throw new s("IDENTITY_CHANGED","Run changed before command dispatch");let S=u.has(l.requestId);u.add(l.requestId);try{return await a(l)}catch(b){throw p===n.generation&&(t===l||d===l)&&!S&&!Oe(b)&&(e&&await e.settle(l.requestId),p===n.generation&&_(l)),b}}function w(l){let p=k.parse(l);if(p.operation==="start"||p.operation==="get"||p.operation==="review")throw new s("INVALID_REQUEST","Mutation required");if(c&&p.operation!=="close"){if(t?.requestId===p.requestId)return O(p.requestId);throw new s("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(p.operation==="close"){if(t?.requestId===p.requestId)throw new s("INVALID_REQUEST","Close requires its own request identity");if(c=!0,d&&JSON.stringify(x(d))!==JSON.stringify(x(p)))throw new s("COMMAND_PENDING","Retry the original Close");return d??=p,f.close?f.close:v(d,"close")}if(t){if(JSON.stringify(x(t))!==JSON.stringify(x(p)))throw new s("COMMAND_PENDING","Retry the original command before sending another");if(f.command)return f.command}else t=p;return v(t,"command")}function v(l,p){let S=y(l);f[p]=S;let b=()=>{f[p]===S&&(f[p]=null)};return S.then(b,b),S}function O(l){return a({operation:"get",settlementRequestId:l})}function _(l){return!l||t!==l&&d!==l?!1:(t===l&&(t=null),d===l&&(d=null),u.delete(l.requestId),!t&&!d&&(g=null),!0)}return{ready:m,get pending(){return t},get closing(){return d},get closeRequested(){return c},get inFlight(){return f.command},get closeFlight(){return f.close},get purchase(){return r},assertBinding(l){if(g&&(l.run.id!==g.runId||l.run.source.id!==g.funnelId||l.run.source.versionId!==g.versionId))throw new s("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(l,p,S,b){let D=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0,q=D&&p.settlement?.state==="settled"&&p.run.pendingRequest?.requestId!==D&&(l.operation==="get"||!c||l.operation==="close"||!["running","waiting"].includes(p.run.status))?D:void 0,L=t?.requestId===q?t:d?.requestId===q?d:void 0;e?.bind({scope:p.scope,runId:p.run.id,funnelId:p.run.source.id,versionId:p.run.source.versionId});let i=p.run.paywall,I=i??p.purchase,E=I?.operation,P=p.settlement&&(!i||i.purchaseRequestId===p.settlement.requestId)&&(!r||r.operationId===p.settlement.operationId)?p.settlement:void 0,R=E?.operationId??I?.quote?.operationId??P?.operationId,C=I?.receiptId??P?.receiptId,h=i?.selectionGeneration??r?.generation??0;if(e&&R&&C&&l.operation!=="review"&&(!n.view||p.run.revision>=n.view.revision)&&(b===void 0||b>=n.readSequence)&&(!r||h>=r.generation)){let F={receiptId:C,operationId:R,generation:h},N=de(E,I?.canReselect===!0);await e.observePurchase({scope:p.scope,runId:p.run.id,funnelId:p.run.source.id,versionId:p.run.source.versionId},F,N,q),n.assertCurrent(S),(!r||F.generation>=r.generation)&&(b===void 0||b>=n.readSequence)&&(N?r?.operationId===F.operationId&&(r=void 0):r=F)}else e&&q&&await e.settle(q);return n.assertCurrent(S),q?_(L):!1},stop(){c=!0},submit:w,settle:O,reset(){c=!0,t=null,d=null,r=void 0,g=null,f.close=null,u.clear(),f.command=null}}}function _e(e){e={...e};let n=e.initialResponse;delete e.initialResponse;let a=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new s("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new s("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Q.test(e.serverKey)))throw new s("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new s("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let o=B({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),t=we(e.funnelId,e.scope??e.configuration?.scope),d=e.session?.subscribeIdentity(v),c=null,f=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?me(e):void 0),u=f&&ye(f),r=ve({journal:u,state:t,call:O,processIdentity:e.process}),g=0,m=new Map;function y(){g++,m.clear(),n=void 0}async function w(i){let I=i.operation==="resume"?r.pending?.operation==="resume"?null:r.pending:i;if(a&&i.operation==="resume"&&!I&&i.requestId!==e.customerRun?.startRequestId)throw new s("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(I?.operation==="submit"&&I.input.type==="paywall_confirm"){let F=t.view?.paywall;he(a,F?.quote?.operationId===I.input.operationId?F.quote:void 0)}if(e.process)return e.process.request(i);let E=t.generation;t.assertCurrent(E);let P=performance.now()+(e.timeoutMs??35e3),R=t.customerToken??("customerToken"in i?i.customerToken:void 0);if(e.session){let F=t.signal,N,M=()=>{},Pe=new Promise((xe,z)=>{M=()=>z(F.reason),F.addEventListener("abort",M,{once:!0}),N=setTimeout(()=>z(new s("TIMEOUT","Longplay request timed out")),Math.max(1,P-performance.now()))});try{R=await Promise.race([Promise.resolve().then(()=>(t.assertCurrent(E),e.session.access())),Pe])}finally{clearTimeout(N),F.removeEventListener("abort",M)}}t.assertCurrent(E);let C={...i,...R?{customerToken:R}:{}},h=i.operation==="page_experiments"?J.parse(C):k.parse(C);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!R)throw new s("IDENTITY_CHANGED","Original recovery Customer changed");let F={...h};return"customerToken"in F&&delete F.customerToken,o.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:F},R,{timeoutMs:Math.max(1,P-performance.now())})}return o.requestWithCredential("funnels",h,e.runToken,{headers:e.serverKey&&!R?{[oe]:e.serverKey}:void 0,timeoutMs:Math.max(1,P-performance.now())})}function v(){y(),d?.(),t.reset(),r.reset(),c=null,o.dispose()}async function O(i,I){let E=n;n=void 0;let P=t.generation,R=()=>t.assertCurrent(P);u&&await r.ready,R();let C=t.view,h=pe(e,E!==void 0&&i.operation==="get"&&!i.data&&!i.purchase&&!i.settlementRequestId?E:await w(i));if(i.operation==="review"&&!h.review)throw new s("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&h.run.id!==e.customerRun.runId)throw new s("INVALID_RESPONSE","Original recovery Run changed");if(i.operation==="get"&&i.purchase&&h.purchase&&(h.purchase.receiptId!==i.purchase.receiptId||(h.purchase.operation?.operationId??h.purchase.quote?.operationId)!==i.purchase.operationId))throw new s("INVALID_RESPONSE","The requested original purchase changed");if(R(),h.runToken&&h.runToken!==e.runToken)throw new s("INVALID_RESPONSE","Run credential changed");let F=i.operation==="get"?i.settlementRequestId:"requestId"in i&&i.operation!=="start"?i.requestId:void 0;if(F&&h.settlement?.requestId!==F)throw new s("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");r.assertBinding(h),t.assertRun(h.run),t.bindScope(h.scope);let N=await r.observe(i,h,P,I);return(!t.view||h.run.revision>=t.view.revision)&&(I===void 0||I>=t.readSequence)&&(await e.onAcceptedResponse?.(h),R()),!h.run.stopped&&["running","waiting"].includes(h.run.status)&&i.operation==="get"&&i.settlementRequestId||(R(),["running","waiting"].includes(h.run.status)||r.stop(),t.publish(i,h,C,I,N)),h}function _(i){let I=t.generation;y();let E=i(),P=()=>{t.generation===I&&y()};return E.then(P,P),E}let l=i=>_(()=>r.submit(i)),p=null,S=new WeakMap;function b(i){let I=S.get(i);if(I)return I;let E=q(i);return S.set(i,E),E}let D=!1;async function q(i){let I=await i;if(I.run.instruction?.type!=="evaluate_segment")return I;if(p)return p;D=!0;let E=t.generation,P=(async()=>{for(let R=0;R<32&&I.run.instruction?.type==="evaluate_segment";R++){if(r.pending||r.closeRequested)return I;let C=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:F}=await Y(e.configuration,C,{predict:!1});if(E!==t.generation)throw new s("IDENTITY_CHANGED","Run identity changed during segment calculation");if(r.pending||r.closeRequested)return I;if(t.view&&(t.view.revision!==C.revision||t.view.visit!==C.visit||t.view.nodeId!==C.nodeId))return O({operation:"get"});let N=!0;Y(e.configuration,C).then(({prediction:M})=>{N&&E===t.generation&&!r.closeRequested&&t.view?.id===C.id&&!t.view.stopped&&t.view.nodeId===C.nodeId&&t.view.visit===C.visit&&t.view.revision===C.revision&&(c=M)}).catch(()=>{});try{I=await l({operation:"commit_segment",requestId:re(C.id,C.visit,`segment:${C.revision}`),nodeId:C.nodeId,visit:C.visit,revision:C.revision,...F})}finally{N=!1,c=null}}}return I})();p=P;try{return await P}finally{p===P&&(p=null)}}let L={get configuration(){return D?e.configuration:void 0},get configurationReady(){return!0},get view(){let i=t.currentView;return i?structuredClone(i):null},get viewAgeMs(){return t.viewAgeMs},get pendingCommand(){let i=r.closing??r.pending;return i?structuredClone(x(i)):null},get pendingCommands(){return[r.pending,r.closing].filter(i=>i!==null).map(i=>structuredClone(x(i)))},get pendingPurchase(){return r.purchase?structuredClone(r.purchase):null},get hasDurableJournal(){return u!==void 0},get prediction(){let i=t.view;return c&&i&&!i.stopped&&["running","waiting"].includes(i.status)&&i.id===c.runId&&i.nodeId===c.from.nodeId&&i.visit===c.from.visit&&i.revision===c.from.revision&&!r.closeRequested?structuredClone(c):null},settle:(...i)=>_(()=>r.settle(...i)),get webViewUrl(){return"bundled"},resolvePaywall(i){return fe(e,i)},async pageExperiments(i,I=[]){let E=t.generation;t.assertCurrent(E);let P=t.view?.id;if(!P)throw new s("INVALID_REQUEST","Read the Run before its page experiments");let R=ie.parse(await w(J.parse({operation:"page_experiments",release:i,usedReceiptIds:I})));if(t.assertCurrent(E),R.runId!==P||R.scope.projectId!==t.scope?.projectId||R.scope.environment!==t.scope?.environment)throw new s("SCOPE_MISMATCH","Page experiment Run changed");return R},review(i){return O({operation:"review",...i?{receiptId:i}:{}},t.nextRead())},async get(i,I){let E=t.generation;i=i&&structuredClone(i),I=I&&{...I},u&&await r.ready,t.assertCurrent(E),I??=r.purchase&&{receiptId:r.purchase.receiptId,operationId:r.purchase.operationId};let P=JSON.stringify([t.generation,g,i??null,I??null]),R=m.get(P);if(R)return R.then(N=>structuredClone(N));let C=t.nextRead(),h=b(O({operation:"get",...i?{data:i}:{},...I?{purchase:I}:{}},C));m.set(P,h);let F=()=>{m.get(P)===h&&m.delete(P)};return h.then(F,F),h.then(N=>structuredClone(N))},resume(i=t.view?.pendingRequest?.requestId){return i?r.closeRequested?L.settle(i):r.pending?.requestId===i?b(l(r.pending)):b(l({operation:"resume",requestId:i})):Promise.reject(new s("INVALID_REQUEST","No interrupted command is available"))},submit(i){return b(l(i))},retry(){return r.closeFlight?r.closeFlight:r.closing?l(r.closing):r.closeRequested&&r.pending?L.settle(r.pending.requestId):r.inFlight?b(r.inFlight):r.pending?b(l(r.pending)):Promise.reject(new s("INVALID_REQUEST","No command is pending"))},identify(i){let I=t.customerToken?void 0:n;y(),t.identify(i),n=I,c=null,o.reset()},get identitySignal(){return t.signal},subscribe:t.subscribe,reset:v};return L}function Dn(e,n){return _e({...e,runToken:"",initialResponse:n})}import{ZodError as qe}from"zod";function Re(e,n,a){if(!["subscriptions/operations/read","subscriptions/updates/read","subscriptions/refunds/read"].includes(e))return;let o=n,t=a,d=t.operation;if(d.operationId!==o.operationId||[d.authority,d.merchantExecution].some(c=>c&&(c.operationId!==o.operationId||o.customerId!==void 0&&c.customerId!==o.customerId))||d.authority&&(d.authority.scope.projectId!==t.scope.projectId||d.authority.scope.environment!==t.scope.environment))throw new s("INVALID_RESPONSE","Original commerce operation changed")}function Ce(e,n,a,o){try{return e.parse(n)}catch(t){throw o&&t instanceof qe?new s(a,o):t}}async function jn(e,n,a,o={},t){let d=typeof o=="function"?{}:o,c=Ce(n.request,a,"INVALID_REQUEST",d.request);try{let f=await e(n.path,c,n.method,t),u=typeof o=="function"?o:o.parseResponse,r=u?u(n.response,f):Ce(n.response,f,"INVALID_RESPONSE",d.response);return Re(n.path,c,r),r}catch(f){throw f instanceof s&&c!==null&&typeof c=="object"&&"requestId"in c&&typeof c.requestId=="string"&&(f.commandRequestId??=c.requestId),f}}export{jn as a,pe as b,fe as c,K as d,ze as e,Ae as f,Ie as g,V as h,me as i,Ee as j,sn as k,G as l,Q as m,pn as n,fn as o,he as p,_e as q,Dn as r};
|
package/dist/chunk-MHEYMXGZ.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import{z as lr}from"zod";var pr=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],z=lr.enum(pr);function dr(e){let t=z.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function We(e,t,n="en",r={}){let i=z.parse(t.toUpperCase());return new Intl.NumberFormat(n,{style:"currency",currency:i,...r}).format(e/10**dr(i))}import{z as E}from"zod";import{z as R}from"zod";var Ce=R.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),N=R.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),fr=R.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),Je=N.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Dt=R.string().min(1).max(64),ie=R.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Lt=R.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),B=R.record(Dt,R.union([R.string().max(120),R.number().finite(),R.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,String(n)]))),Ut=R.record(Dt,R.union([R.string().max(120),R.number().finite(),R.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),le=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");let i=BigInt(n)*BigInt("1000000")+BigInt(r.padEnd(6,"0"));return t?-i:i},zt=R.array(R.object({upTo:Je.nullable(),cost:N}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&le(t.upTo)>le(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),mr=R.object({key:Lt,match:Ut,priority:R.number().int().default(0),cost:N.optional(),tiers:zt.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),gr=R.object({key:Lt,match:Ut,factor:Je.optional(),add:fr.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),br=R.object({units:Je.default("1"),cost:N,tiers:zt.optional(),dimensions:R.array(mr).max(12).optional(),multipliers:R.array(gr).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],r=e.multipliers??[];(new Set(n.map(a=>a.key)).size!==n.length||new Set(r.map(a=>a.key)).size!==r.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[a,s]of n.entries())for(let u of n.slice(a+1))Object.keys(s.match).length===Object.keys(u.match).length&&s.priority===u.priority&&!Object.keys(s.match).some(f=>u.match[f]!==void 0&&u.match[f]!==s.match[f])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let i=[e.cost,...(e.tiers??[]).map(a=>a.cost),...n.flatMap(a=>[...a.cost===void 0?[]:[a.cost],...(a.tiers??[]).map(s=>s.cost)])],o=le(e.units);for(let a of i)for(let s=0;s<1<<r.length;s++){let u=r.filter((b,k)=>s&1<<k);if(u.some((b,k)=>u.slice(k+1).some(O=>Object.keys(b.match).some(U=>O.match[U]!==void 0&&O.match[U]!==b.match[U]))))continue;let f=le(a),d=BigInt("1"),g=BigInt("0");for(let[b,k]of r.entries())s&1<<b&&(f*=le(k.factor??"1"),d*=BigInt("1000000"),g+=le(k.add??"0"));let I=(f+g*d)*BigInt("1000000"),y=d*o;(I<BigInt("0")||I%y!==BigInt("0")||I/y>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),ko=br.safeExtend({featureKey:ie});import{z as hr}from"zod";import{z as pe}from"zod";var $t=pe.enum(["stripe","apple","google","merchant"]),Eo=pe.enum(["membership","credit_pack","lifetime"]),_o=pe.enum(["active","grace","suspended","inactive","revoked"]),wo=pe.strictObject({currency:pe.string().regex(/^[A-Z]{3}$/),micros:pe.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var Ft=hr.object({provider:$t,currency:z}).strict();import{z as de}from"zod";var yr=e=>e/2**32|0,xr=e=>e>>>0;function Vt(e,t,n,r){let i=yr(n),o=xr(n);e.setUint32(t,r?o:i,r),e.setUint32(t+4,r?i:o,r)}function Bt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Ye=e=>e?`"${e}" `:"";function Sr(e,t=""){if(typeof e!="number")throw new TypeError(Ye(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Ye(t)+"expected integer >= 0, got "+e);return e}function je(e,t,n=""){if(Bt(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Sr(t,"length");let r=Bt(e),i=t!==void 0?` of length ${t}`:"",o=r?`length=${e.length}`:`type=${typeof e}`,a=Ye(n)+"expected Uint8Array"+i+", got "+o;throw r?new RangeError(a):new TypeError(a)}var kr=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Mt=(e,t)=>{kr(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function Xe(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function qt(e,t){je(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function et(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Te(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function M(e,t){return e<<32-t|e>>>t}var Ir=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ar=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Pe(e){if(je(e),Ir)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Ar[e[n]];return t}function Er(e,t,n="opts"){return Mt(e,"defaults"),t!==void 0&&Mt(t,n),Object.assign(Object.create(null),e,t)}function Ht(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=Er({},t,"info");let n=(i,o)=>e(o).update(i).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=i=>e(i),Object.assign(n,t),Object.freeze(n)}var Gt=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Qt(e,t,n){return e&t^~e&n}function Kt(e,t,n){return e&t^e&n^t&n}var De=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,r,i){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Te(this.buffer)}update(t){Xe(this),je(t);let{view:n,buffer:r,blockLen:i}=this,o=t.length,a=!1;for(let s=0;s<o;){let u=Math.min(i-this.pos,o-s);if(u===i){let f=Te(t);for(;i<=o-s;s+=i)this.process(f,s);a=!0;continue}r.set(s===0&&u===o?t:t.subarray(s,s+u),this.pos),this.pos+=u,s+=u,this.pos===i&&(this.process(n,0),this.pos=0,a=!0)}return this.length+=t.length,a&&this.roundClean(),this}digestInto(t){Xe(this),qt(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:o}=this,{pos:a}=this;n[a++]=128,n.fill(0,a),this.padOffset>i-a&&(this.process(r,0),n.fill(0)),Vt(r,i-8,this.length*8,o),this.process(r,0),this.roundClean();let s=t===n?r:Te(t),u=this.outputLen,f=u/4,d=this.get();if(u%4||f>d.length)throw new Error("invalid outputLen");for(let g=0;g<f;g++)s.setUint32(4*g,d[g],o)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:i,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=i,t.length=r,t.pos=a,a&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Zt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var _r=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),X=new Uint32Array(64),tt=class extends De{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,n){super(64,t,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){let{A:t,B:n,C:r,D:i,E:o,F:a,G:s,H:u}=this;return[t,n,r,i,o,a,s,u]}set(t,n,r,i,o,a,s,u){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=o|0,this.F=a|0,this.G=s|0,this.H=u|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let g=0;g<16;g++,n+=4)X[g]=t.getUint32(n,!1);for(let g=16;g<64;g++){let I=X[g-15],y=X[g-2],b=M(I,7)^M(I,18)^I>>>3,k=M(y,17)^M(y,19)^y>>>10;X[g]=k+X[g-7]+b+X[g-16]|0}let{A:r,B:i,C:o,D:a,E:s,F:u,G:f,H:d}=this;for(let g=0;g<64;g++){let I=M(s,6)^M(s,11)^M(s,25),y=d+I+Qt(s,u,f)+_r[g]+X[g]|0,k=(M(r,2)^M(r,13)^M(r,22))+Kt(r,i,o)|0;d=f,f=u,u=s,s=a+y|0,a=o,o=i,i=r,r=y+k|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,a=a+this.D|0,s=s+this.E|0,u=u+this.F|0,f=f+this.G|0,d=d+this.H|0,this.set(r,i,o,a,s,u,f,d)}roundClean(){et(X)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),et(this.buffer)}},nt=class extends tt{constructor(){super(32,Zt)}};var Le=Ht(()=>new nt,Gt(1));import{z as rt}from"zod";var it=rt.enum(["sandbox","live"]),qo=rt.object({projectId:rt.string().min(1),environment:it}).strict();var Wt=de.string().regex(/^[a-f0-9]{64}$/),Ue=de.strictObject({scope:de.strictObject({projectId:de.uuid(),environmentId:de.uuid(),environment:it}),customerId:de.uuid()});function Jt(e){let t=n=>{if(Array.isArray(n))return`[${n.map(t).join(",")}]`;if(n!==null&&typeof n=="object"){let r=Object.getPrototypeOf(n);if(r!==Object.prototype&&r!==null)throw new TypeError("Commerce protocol digests require JSON objects");return`{${Object.entries(n).filter(([,i])=>i!==void 0).sort(([i],[o])=>i<o?-1:i>o?1:0).map(([i,o])=>`${JSON.stringify(i)}:${t(o)}`).join(",")}}`}if(n===null||typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))return JSON.stringify(n);throw new TypeError("Commerce protocol digests require JSON values")};return Pe(Le(new TextEncoder().encode(t(e))))}var Se=E.strictObject({internal_feature_id:E.uuid(),quantity:N.refine(e=>/[1-9]/.test(e)),properties:B,entityId:E.uuid().optional()}),na=E.strictObject({requirement:Se,commerce:Ft.optional(),paywallId:E.uuid().optional()}),wr=E.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Or=E.strictObject({productId:E.string().min(1),productVersionId:E.string().min(1),name:E.string().min(1).max(120),action:E.enum(["purchase","upgrade","addon","topup"]),membershipId:E.string().min(1).nullable(),currency:z,amountMinor:E.string().regex(/^(0|[1-9]\d{0,8})$/),interval:E.enum(["free","week","month","year","one_time"]),intervalCount:E.number().int().min(1).max(156)}),Yt=E.strictObject({subject:Ue,authority:E.enum(["longplay","merchant"]),observedAt:E.iso.datetime({offset:!0}),sourceRevision:E.string().min(1).max(128),requirementDigest:Wt});function vr(e,t){return Jt({subject:Ue.parse(e),requirement:Se.parse(t)})}var ot=E.strictObject({internal_feature_id:E.string().min(1),name:E.string().min(1).max(120),kind:E.enum(["access","metered","credit"]),quantity:N,allowed:E.boolean(),observation:Yt.optional(),reason:wr.nullable(),preview:E.strictObject({scenario:E.enum(["feature_flag","usage_limit"]),candidates:E.array(Or).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(n=>n.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),ra=E.strictObject({paywallId:E.uuid(),requirement:Se}),ia=E.strictObject({subject:Ue,requirement:Se}),oa=ot.safeExtend({observation:Yt.extend({authority:E.literal("merchant")})});function aa(e,t){let n=Se.parse(e);return t.internal_feature_id===n.internal_feature_id&&t.quantity===n.quantity&&(!t.observation||t.observation.requirementDigest===vr(t.observation.subject,n))}import{z as l}from"zod";function at(e){let t=2166136261,n=e.length;for(let r=0;r<n;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return t>>>0}function ke(e,t,n){return n===2?at(at(e+t)+"")%1e4/1e4:null}function Xt(e){return e<=0?[]:new Array(e).fill(1/e)}function Ie(e,t){return e>=t[0]&&e<t[1]}function st(e,t){for(let[n,r]of t.entries())if(Ie(e,r))return n;return-1}function ct(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=Xt(e);n=n||r,n.length!==e&&(n=r);let i=n.reduce((s,u)=>u+s,0);(i<.99||i>1.01)&&(n=r);let o=0,a=t;return n.map(s=>{let u=o;return o+=s,[u,u+a*s]})}function ut(e,t,n){if(!t)return null;let r=t.split("?")[1];if(!r)return null;let o=r.replace(/#.*/,"").split("&").map(a=>a.split("=",2)).filter(([a])=>a===e).map(([,a])=>a===void 0?NaN:parseInt(a))[0];return o!==void 0&&o>=0&&o<n?o:null}function lt(e){try{return e()}catch{return!1}}function fe(e){return typeof e=="string"?e:JSON.stringify(e)}function $(e){typeof e=="number"&&(e=e+""),(!e||typeof e!="string")&&(e="0");let t=e.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return t.length===3&&t.push("~"),t.map(n=>n.match(/^[0-9]+$/)?n.padStart(5," "):n).join("-")}function en(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function pt(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let o=Cr(e,i.type,i.pattern);if(i.include===!1){if(o)return!1}else n=!0,o&&(r=!0)}return r||!n}function Rr(e,t,n){try{let r=t.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return n&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(e)}catch{return!1}}function Nr(e,t){try{let n=new URL(t.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[e.host,n.host,!1],[e.pathname,n.pathname,!0]];return n.hash&&r.push([e.hash,n.hash,!1]),n.searchParams.forEach((i,o)=>{r.push([e.searchParams.get(o)||"",i,!1])}),!r.some(i=>!Rr(i[0],i[1],i[2]))}catch{return!1}}function Cr(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=en(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return Nr(r,n);return!1}catch{return!1}}function dt(e){for(let n of["namespace","status","url","groups"])if(Object.hasOwn(e,n))throw new TypeError(`Retired experiment field: ${n}`);let t=e;if(t.hashVersion!==void 0&&t.hashVersion!==2)throw new TypeError("Only hash version 2 is supported");if(t.filters?.some(n=>n.hashVersion!==2))throw new TypeError("Only hash version 2 is supported")}function ze(e){for(let t of Object.values(e)){if(Array.isArray(t))throw new TypeError("Saved groups require typed list or condition entries");if(t&&Object.hasOwn(t,"useEmptyListGroup"))throw new TypeError("Retired saved group field: useEmptyListGroup")}}function tn(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);ze(e.savedGroups??{})}var nn=new Map,ft=32,rn=new WeakMap,on=new WeakMap;function jr(e){return Pe(Le(new TextEncoder().encode(String(e))))}var Fe=e=>Array.isArray(e)?e.map(Fe):typeof e=="string"||typeof e=="number"?jr(e):null,$e=e=>typeof e=="string"?e.toLowerCase():e;function ln(e){let t=rn.get(e);return t||(t=new Set(e),rn.set(e,t)),t}function Tr(e){let t=on.get(e);return t||(t=new Set(e.map($e)),on.set(e,t)),t}function pn(e){ze(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=ft&&ln(n)}return e}function q(e,t,n,r){n=n||{},r||ze(n),r=r||new Set;for(let[i,o]of Object.entries(t))switch(i){case"$or":if(!un(e,o,n,r))return!1;break;case"$nor":if(un(e,o,n,r))return!1;break;case"$and":if(!zr(e,o,n,r))return!1;break;case"$not":if(q(e,o,n,r))return!1;break;case"$savedGroup":if(!Pr(e,o,n,r))return!1;break;default:if(!Ae(o,dn(e,i),n,!1,r))return!1}return!0}function Pr(e,t,n,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let{id:i,attributeKey:o}=t;if(typeof i!="string"||r.has(i)||o!==void 0&&typeof o!="string")return!1;let a=n[i];if(!a||Array.isArray(a)||typeof a!="object")return!1;let s=new Set(r).add(i);if(a.type==="list"||a.type==="hashed"){let u=o??a.attributeKey;if(typeof u!="string"||!Array.isArray(a.values))return!1;let f=dn(e,u);return oe(a.type==="hashed"?Fe(f):f,a.values)}return a.type==="condition"?!a.condition||typeof a.condition!="object"?!1:q(e,a.condition,n,s):!1}function dn(e,t){let n=t.split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return null;return r}function an(e,t=!1){let n=`${e}${t?"/i":""}`,r=nn.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),nn.set(n,r)),r}function Ae(e,t,n,r=!1,i=new Set){if(typeof e=="string")return r?String(t).toLowerCase()===e.toLowerCase():t+""===e;if(typeof e=="number")return t*1===e;if(typeof e=="boolean")return t!==null&&!!t===e;if(e===null)return t===null;if(Array.isArray(e)||!fn(e))return JSON.stringify(t)===JSON.stringify(e);let o=e;for(let a in o)if(!Ur(a,t,o[a],n,i))return!1;return!0}function fn(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function Dr(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return["string","number","boolean","object","undefined"].includes(t)?t:"unknown"}function Lr(e,t,n,r){if(!Array.isArray(e))return!1;let i=fn(t)?o=>Ae(t,o,n,!1,r):o=>q(o,t,n,r);for(let o=0;o<e.length;o++)if((e[o]??null)!==null&&i(e[o]))return!0;return!1}function oe(e,t,n=!1){if(n){let i;if(t.length>=ft){let o=Tr(t);i=a=>{let s=$e(a);return!(typeof s=="number"&&Number.isNaN(s))&&o.has(s)}}else i=o=>t.some(a=>$e(o)===$e(a));return Array.isArray(e)?e.some(o=>i(o)):i(e)}let r=t.length>=ft?(i=>o=>i.has(o))(ln(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function sn(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function cn(e,t,n,r=!1,i=new Set){if(!Array.isArray(e))return!1;for(let o=0;o<t.length;o++){let a=!1;for(let s=0;s<e.length;s++)if(Ae(t[o],e[s],n,r,i)){a=!0;break}if(!a)return!1}return!0}function Ur(e,t,n,r,i=new Set){let o=t,a=n;switch(e){case"$veq":return $(t)===$(n);case"$vne":return $(t)!==$(n);case"$vgt":return $(t)>$(n);case"$vgte":return $(t)>=$(n);case"$vlt":return $(t)<$(n);case"$vlte":return $(t)<=$(n);case"$eq":return t===n;case"$ne":return t!==n;case"$lt":return o<a;case"$lte":return o<=a;case"$gt":return o>a;case"$gte":return o>=a;case"$exists":return n?t!=null:t==null;case"$in":return Array.isArray(n)?oe(t,n):!1;case"$ini":return Array.isArray(n)?oe(t,n,!0):!1;case"$inGroup":{let s=r[n],u=sn(s);return u===null?!1:oe(s?.type==="hashed"?Fe(t):t,u)}case"$notInGroup":{let s=r[n],u=sn(s);return u===null?!1:!oe(s?.type==="hashed"?Fe(t):t,u)}case"$nin":return Array.isArray(n)?!oe(t,n):!1;case"$nini":return Array.isArray(n)?!oe(t,n,!0):!1;case"$not":return!Ae(n,t,r,!1,i);case"$size":return Array.isArray(t)?Ae(n,t.length,r,!1,i):!1;case"$elemMatch":return Lr(t,n,r,i);case"$all":return Array.isArray(n)?cn(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?cn(t,n,r,!0,i):!1;case"$regex":try{return an(n).test(t)}catch{return!1}case"$regexi":try{return an(n,!0).test(t)}catch{return!1}case"$type":return Dr(t)===n;default:return!1}}function un(e,t,n,r){if(!t.length)return!0;for(let i of t)if(q(e,i,n,r))return!0;return!1}function zr(e,t,n,r){for(let i of t)if(!q(e,i,n,r))return!1;return!0}function mt(e){return tn(e),{context:e,stack:{evaluatedFeatures:new Set}}}function gt(e){return{...e.attributes,...e.attributeOverrides}}function ee(e,t,n){let r=t||"id",i="",o=gt(e);return o[r]&&(i=o[r]),!i&&n&&(o[n]&&(i=o[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function _(e,t,n){e.context.log?.(t,n)}function Ve(e,t){return t=t||0,`${e}__${t}`}function bt(e,t){return`${e}||${t}`}function $r(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:o}=ee(e,t),a=bt(i,fe(o)),{hashAttribute:s,hashValue:u}=ee(e,n),f=u?bt(s,fe(u)):null,d={};return f&&r[f]&&Object.assign(d,r[f].assignments||{}),r[a]&&Object.assign(d,r[a].assignments||{}),d}function mn({context:e,expKey:t,expBucketVersion:n,expHashAttribute:r,expFallbackAttribute:i,expMinBucketVersion:o,expMeta:a}){n=n||0,o=o||0,r=r||"id",a=a||[];let s=Ve(t,n),u=$r(e,r,i);if(o>0)for(let g=0;g<o;g++){let I=Ve(t,g);if(u[I]!==void 0)return{variation:-1,versionIsBlocked:!0}}let f=u[s];if(f===void 0)return{variation:-1};let d=a.findIndex(g=>g.key===f);return d<0?{variation:-1}:{variation:d}}function gn(e,t,n,r){let i=bt(t,n),o=e.stickyBucketAssignmentDocs,a=o&&o[i]?o[i].assignments||{}:{},s={...a,...r},u=JSON.stringify(a)!==JSON.stringify(s);return{key:i,doc:{attributeName:t,attributeValue:n,assignments:s},changed:u}}function bn(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function hn(e,t){let n=mt(t),r=Sn(e,null,n);return t.onExperimentEval?.(e,r),r}function yn(e,t){return yt(e,mt(t))}function Fr(e){return e.forcedVariations||{}}function xn(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=An(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}ht(()=>r.onExperimentViewed?.(t,n))}function Vr(e,t,n){let{context:r}=e;if(r.trackedFeatureUsage){let i=JSON.stringify(n.value);if(r.trackedFeatureUsage[t]===i)return;r.trackedFeatureUsage[t]=i}ht(()=>r.onFeatureUsage?.(t,n))}function ht(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function yt(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return _(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),te(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let o of r?.rules??[])dt(o);let i=n.forcedFeatureValues;if(i&&i.has(e))return _(t,"Global override",{id:e,value:i.get(e)}),te(t,e,i.get(e),"override");if(!r)return _(t,"Unknown feature",{id:e}),te(t,e,null,"unknownFeature");if(r.rules){let o=new Set(t.stack.evaluatedFeatures);e:for(let a of r.rules){if(a.parentConditions)for(let f of a.parentConditions){t.stack.evaluatedFeatures=new Set(o);let d=yt(f.id,t);if(d.source==="cyclicPrerequisite")return te(t,e,null,"cyclicPrerequisite");let g={value:d.value};if(!q(g,f.condition||{},n.savedGroups||{})){if(f.gate)return _(t,"Feature blocked by prerequisite",{id:e,rule:a}),te(t,e,null,"prerequisite");_(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:a});continue e}}if(a.filters&&In(a.filters,t)){_(t,"Skip rule because of filters",{id:e,rule:a});continue}if("force"in a){if(a.condition&&!kn(a.condition,t)){_(t,"Skip rule because of condition ff",{id:e,rule:a});continue}if(!Br(t,a.seed||e,a.hashAttribute,n.saveStickyBucketAssignmentDoc&&!a.disableStickyBucketing?a.fallbackAttribute:void 0,a.range,a.coverage,a.hashVersion)){_(t,"Skip rule because user not included in rollout",{id:e,rule:a});continue}return _(t,"Force value from rule",{id:e,rule:a}),a.tracks&&a.tracks.forEach(f=>{xn(t,f.experiment,f.result)}),te(t,e,a.force,"force",a.id)}if(!a.variations){_(t,"Skip invalid rule",{id:e,rule:a});continue}let s={variations:a.variations,key:a.key||e};"coverage"in a&&(s.coverage=a.coverage),a.weights&&(s.weights=a.weights),a.hashAttribute&&(s.hashAttribute=a.hashAttribute),a.fallbackAttribute&&(s.fallbackAttribute=a.fallbackAttribute),a.disableStickyBucketing&&(s.disableStickyBucketing=a.disableStickyBucketing),a.bucketVersion!==void 0&&(s.bucketVersion=a.bucketVersion),a.minBucketVersion!==void 0&&(s.minBucketVersion=a.minBucketVersion),a.meta&&(s.meta=a.meta),a.ranges&&(s.ranges=a.ranges),a.name&&(s.name=a.name),a.phase&&(s.phase=a.phase),a.seed&&(s.seed=a.seed),a.hashVersion&&(s.hashVersion=a.hashVersion),a.filters&&(s.filters=a.filters),a.condition&&(s.condition=a.condition);let u=Sn(s,e,t);if(n.onExperimentEval?.(s,u),u.inExperiment&&!u.passthrough)return te(t,e,u.value,"experiment",a.id,s,u)}}return _(t,"Use default value",{id:e,value:r.defaultValue}),te(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Sn(e,t,n){let{context:r}=n;dt(e);let i=e.key,o=e.variations.length;if(o<2)return _(n,"Invalid experiment",{id:i}),D(n,e,-1,!1,t);if(r.enabled===!1)return _(n,"Context disabled",{id:i}),D(n,e,-1,!1,t);if(e.urlPatterns&&!pt(r.url||"",e.urlPatterns))return _(n,"Skip because of url targeting",{id:i}),D(n,e,-1,!1,t);let a=ut(i,r.url||"",o);if(a!==null)return _(n,"Force via querystring",{id:i,variation:a}),D(n,e,a,!1,t);let u=Fr(r)[i];if(u!==void 0)return _(n,"Force via dev tools",{id:i,variation:u}),D(n,e,u,!1,t);if(e.active===!1)return _(n,"Skip because inactive",{id:i}),D(n,e,-1,!1,t);let{hashAttribute:f,hashValue:d}=ee(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!d)return _(n,"Skip because missing hashAttribute",{id:i}),D(n,e,-1,!1,t);let g=-1,I=!1,y=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:O,versionIsBlocked:U}=mn(bn({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));I=O>=0,g=O,y=!!U}if(!I){if(e.filters&&In(e.filters,n))return _(n,"Skip because of filters",{id:i}),D(n,e,-1,!1,t);if(e.include&&!lt(e.include))return _(n,"Skip because of include function",{id:i}),D(n,e,-1,!1,t);if(e.condition&&!kn(e.condition,n))return _(n,"Skip because of condition exp",{id:i}),D(n,e,-1,!1,t);if(e.parentConditions){let O=new Set(n.stack.evaluatedFeatures);for(let U of e.parentConditions){n.stack.evaluatedFeatures=new Set(O);let re=yt(U.id,n);if(re.source==="cyclicPrerequisite")return D(n,e,-1,!1,t);let Ze={value:re.value};if(!q(Ze,U.condition||{},r.savedGroups||{}))return _(n,"Skip because prerequisite evaluation fails",{id:i}),D(n,e,-1,!1,t)}}}let b=ke(e.seed||i,d,e.hashVersion??2);if(b===null)return _(n,"Skip because of invalid hash version",{id:i}),D(n,e,-1,!1,t);if(!I){let O=e.ranges||ct(o,e.coverage===void 0?1:e.coverage,e.weights);g=st(b,O)}if(y)return _(n,"Skip because sticky bucket version is blocked",{id:i}),D(n,e,-1,!1,t,void 0,!0);if(g<0)return _(n,"Skip because of coverage",{id:i}),D(n,e,-1,!1,t);if("force"in e)return _(n,"Force variation",{id:i,variation:e.force}),D(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return _(n,"Skip because QA mode",{id:i}),D(n,e,-1,!1,t);let k=D(n,e,g,!0,t,b,I);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:O,key:U,doc:re}=gn(r,f,fe(d),{[Ve(e.key,e.bucketVersion)]:k.key});if(O){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[U]=re;let Ze=r.saveStickyBucketAssignmentDoc;ht(()=>Ze(re))}}return xn(n,e,k),_(n,"In experiment",{id:i,variation:k.variationId}),k}function te(e,t,n,r,i,o,a){let s={value:n,on:!!n,off:!n,source:r,ruleId:i||""};return o&&(s.experiment=o),a&&(s.experimentResult=a),r!=="override"&&Vr(e,t,s),s}function kn(e,t){return q(gt(t.context),e,t.context.savedGroups||{})}function In(e,t){return e.some(n=>{let{hashValue:r}=ee(t.context,n.attribute);if(!r)return!0;let i=ke(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(o=>Ie(i,o))})}function Br(e,t,n,r,i,o,a){if(!i&&o===void 0)return!0;if(!i&&o===0)return!1;let{hashValue:s}=ee(e.context,n,r);if(!s)return!1;let u=ke(t,s,a??2);return u===null?!1:i?Ie(u,i):o!==void 0?u<=o:!0}function D(e,t,n,r,i,o,a){let s=!0;(n<0||n>=t.variations.length)&&(n=0,s=!1);let{hashAttribute:u,hashValue:f}=ee(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),d=t.meta?.[n]??{},g=t.variations[0];for(let[y,b]of t.variations.entries())if(y===n){g=b;break}let I={key:d.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:g,hashAttribute:u,hashValue:f,stickyBucketUsed:!!a};return d.name&&(I.name=d.name),o!==void 0&&(I.bucket=o),d.passthrough&&(I.passthrough=d.passthrough),I}function An(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
|
|
2
|
-
Copyright (c) 2025 GrowthBook, Inc.
|
|
3
|
-
|
|
4
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
|
|
5
|
-
furnished to do so, subject to the following conditions:
|
|
6
|
-
|
|
7
|
-
The above copyright notice and this permission notice shall be included in all
|
|
8
|
-
copies or substantial portions of the Software.
|
|
9
|
-
|
|
10
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
11
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
12
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
13
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
14
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
15
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
16
|
-
SOFTWARE.
|
|
17
|
-
*/var ne=l.json().superRefine((e,t)=>{let n=0;function r(i,o){if(++n>1e4||o>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(a=>r(a,o+1));else if(i&&typeof i=="object")for(let[a,s]of Object.entries(i))(a.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(a)||["__proto__","prototype","constructor"].includes(a))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,o+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),St=l.record(l.string().min(1).max(128),ne).superRefine((e,t)=>{(!ne.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),Mr=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),Be=St.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,o]of Object.entries(r)){if(i==="$savedGroup"&&!l.strictObject({id:l.uuid(),attributeKey:l.string().min(1).max(128).optional()}).safeParse(o).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(a=>["__proto__","prototype","constructor"].includes(a))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!Mr.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof o=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(o)||[...o.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(a=>Number(a[1])>255||Number(a[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(o.replace(/\\u([0-9a-f]{4})/gi,(a,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(o)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(o)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),qr=l.discriminatedUnion("type",[l.strictObject({type:l.literal("condition"),condition:Be}),l.strictObject({type:l.literal("list"),attributeKey:l.string().min(1).max(128),values:l.array(l.union([l.string(),l.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Hr(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,o]of Object.entries(r))i==="$savedGroup"&&o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.id=="string"?t.add(o.id):["$inGroup","$notInGroup"].includes(i)&&typeof o=="string"?t.add(o):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(o)}return n(e),[...t]}var Gr=l.record(l.uuid(),qr).superRefine((e,t)=>{let n=new Set,r=new Set;function i(o){if(n.has(o)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(o),a.type==="condition"&&Hr(a.condition).forEach(i),n.delete(o),r.add(o)}Object.keys(e).forEach(i)}),kt=l.tuple([l.number().min(0).max(1),l.number().min(0).max(1)]).refine(([e,t])=>e<=t),En=l.strictObject({attribute:l.string().optional(),seed:l.string().min(1),hashVersion:l.literal(2),ranges:l.array(kt).min(1).max(100)}),Qr=l.strictObject({id:l.string().min(1).max(128),condition:Be,gate:l.boolean().optional()}),xt={id:l.string().max(128).optional(),condition:Be.optional(),parentConditions:l.array(Qr).max(50).optional(),filters:l.array(En).max(20).optional()},Kr=l.union([l.strictObject({...xt}),l.strictObject({...xt,force:ne,coverage:l.number().min(0).max(1).optional(),range:kt.optional(),seed:l.string().min(1).optional(),hashAttribute:l.string().optional(),hashVersion:l.literal(2).optional()}),l.strictObject({...xt,type:l.literal("experiment-ref"),experimentId:l.uuid(),values:l.record(l.string().min(1),ne),meta:l.record(l.string().min(1),l.strictObject({passthrough:l.boolean()})).optional()})]),Zr=l.strictObject({defaultValue:ne,rules:l.array(Kr).max(100)}),za=l.record(l.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Zr).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function i(o){if(n.has(o)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${o}`});return}if(r.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${o}`});return}n.add(o);for(let s of a.rules)for(let u of s.parentConditions??[])i(u.id);n.delete(o),r.add(o)}Object.keys(e).forEach(i)}),Wr=l.strictObject({name:l.string().max(80),reason:l.string().max(500),dateStarted:l.iso.datetime({offset:!0}),dateEnded:l.iso.datetime({offset:!0}).nullable(),coverage:l.number().min(0).max(1),variationWeights:l.array(l.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Be,savedGroups:l.array(l.strictObject({match:l.enum(["any","all","none"]),ids:l.array(l.uuid()).min(1)})).max(50),namespace:l.strictObject({id:l.uuid(),ranges:l.array(kt).min(1)}).nullable(),seed:l.string().min(1).max(128)}),Jr=l.strictObject({key:l.string().min(1).max(128),name:l.string().min(1).max(80),hypothesis:l.string().max(2e3),status:l.enum(["draft","running","stopped"]),hashAttribute:l.string().min(1).max(128),fallbackAttribute:l.string().max(128).nullable(),hashVersion:l.literal(2),disableStickyBucketing:l.boolean(),bucketVersion:l.number().int().min(0).max(1e3),minBucketVersion:l.number().int().min(0).max(1e3),variations:l.array(l.strictObject({id:l.string().min(1),key:l.string().min(1),name:l.string().max(80),description:l.string().max(500)})).min(2).max(20),phases:l.array(Wr).min(1).max(100),releasedVariationId:l.string().nullable(),excludeFromPayload:l.boolean(),statusSchedule:l.strictObject({startAt:l.iso.datetime({offset:!0}).nullable(),stopAt:l.iso.datetime({offset:!0}).nullable(),stopAfter:l.strictObject({value:l.number().int().positive().max(36500),unit:l.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let i=e.phases[r-1];return!i?.dateEnded||Date.parse(n.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],o,a)=>r>=i||a.some(([s,u],f)=>f!==o&&r<u&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var Yr=Jr.safeExtend({filters:l.array(En).optional()}),Xr=l.strictObject({experiments:l.record(l.uuid(),Yr),savedGroups:Gr}),ei=l.strictObject({attributeName:l.string(),attributeValue:l.string(),assignments:l.record(l.string(),l.string())}),$a=l.strictObject({snapshot:Xr,attributes:St,results:St,stickyBucketAssignmentDocs:l.record(l.string(),ei)}),Fa=l.strictObject({variantKey:l.string().nullable(),bucketVersion:l.number().int().min(0),source:l.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:l.number().min(0).max(1).optional(),stickyBucketUsed:l.boolean().optional(),hashUsed:l.boolean().optional()});import{z as x}from"zod";import{z as be}from"zod";import{z as ge}from"zod";import{z as me}from"zod";var _n=me.number().int().min(0).max(1e8),It=me.strictObject({kind:me.enum(["graduated","volume"]),tiers:me.array(me.strictObject({upTo:me.number().int().min(1).max(1e4).nullable(),unitAmountMinor:_n,flatAmountMinor:_n.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,n)=>{let r=e.tiers[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&t.upTo>r)}),"Tier ceilings must increase and end unbounded").refine(e=>!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function At(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?It.parse(e.pricing):void 0;if(t===0)return 0;let r=0n,i=0;if(!n)r=BigInt(e.amountMinor)*BigInt(t);else for(let o of n.tiers){let a=o.upTo??1e4;if(n.kind==="volume"){if(t<=a){r=BigInt(t)*BigInt(o.unitAmountMinor)+BigInt(o.flatAmountMinor??0);break}}else t>i&&(r+=BigInt(Math.min(t,a)-i)*BigInt(o.unitAmountMinor));i=a}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function wn(e){return At({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var ti=N.refine(e=>/[1-9]/.test(e)),vn=ge.strictObject({units:ti,prices:ge.array(ge.strictObject({currency:z,amountMinor:ge.number().int().min(0).max(1e8),pricing:It.optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique").refine(e=>e.every(t=>!t.pricing||t.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:ge.number().int().min(0).max(1e4),maximumQuantity:ge.number().int().min(0).max(1e4)}).refine(e=>e.maximumQuantity>=e.minimumQuantity,"Purchased quantity must fit its published bounds").refine(e=>{try{for(let t of e.prices)for(let n of[e.maximumQuantity,...t.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])n<=e.maximumQuantity&&At({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},n);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit");function On(e){if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(e))throw new Error("Invalid quantity");let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))}function Rn(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=On(e)+On(t)*BigInt(n);if(r>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let i=(r%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(r/1000000n).toString()+(i?"."+i:"")}var Et=be.strictObject({internalFeatureId:be.uuid(),name:be.string().min(1).max(120),includedAmount:be.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:be.enum(["hour","day","week","month","year","lifetime"]),resetCount:be.number().int().min(1).max(100),terms:vn});var ni=["plan.name","plan.price","plan.period","plan.price_per_month","trial.headline","trial.terms","offer.headline","offer.name","offer.description","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.price","offer.original_price","offer.months","offer.code","offer.ends_at","offer.expires_at","paywall.feature","paywall.message","paywall.action"],Me=x.object({plan:x.string().min(1).max(200).optional(),coupon:x.uuid().optional(),promotionCode:x.uuid().optional(),picker:x.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Nn=x.object({text:x.string().optional(),label:x.string().optional(),alt:x.string().optional(),html:x.string().max(32768).optional(),price:x.object({current:x.string(),original:x.string().nullable(),period:x.string()}).optional(),code:x.string().optional(),countdownAt:x.iso.datetime().optional(),planId:x.string().min(1).max(200).optional(),planVersionId:x.string().min(1).max(200).optional(),currency:z.optional(),couponId:x.uuid().optional(),offerId:x.uuid().optional(),unavailable:x.boolean().optional(),unavailableReason:x.string().optional(),missing:x.array(x.string()).optional()}).strict(),ns=x.object({paywall:ot.optional(),nodes:x.record(x.string(),x.object({base:Nn,picker:x.string().optional(),byPlan:x.record(x.string(),Nn).optional()}).strict()),plans:x.record(x.string(),x.object({id:x.string().min(1).max(200),versionId:x.string().min(1).max(200),available:x.boolean(),name:x.string(),price:x.string(),period:x.string(),currency:z.optional(),amountMinor:x.number().int().nonnegative().optional(),interval:x.enum(["free","week","month","year","one_time"]).optional(),intervalCount:x.number().int().positive().optional(),prepaid:x.array(Et).max(100).optional()}).strict()),pickers:x.record(x.string(),x.object({options:x.array(x.string().min(1).max(200)).max(20),selected:x.string().min(1).max(200).nullable()}).strict()),quantities:x.record(x.string(),x.strictObject({minimum:x.number().int().nonnegative(),maximum:x.number().int().nonnegative(),step:x.number().int().positive(),value:x.number().int().nonnegative(),label:x.string(),available:x.boolean()})).optional(),diagnostics:x.array(x.object({nodeId:x.string(),message:x.string()}).strict())}).strict();function Cn(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}function _t(e){let t=Cn(e).filter(r=>!ni.includes(r)&&!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(r)),n=e.replace(/\{\{\s*[^{}]+?\s*\}\}/g,"");return(n.includes("{{")||n.includes("}}"))&&t.push("\u65E0\u6548\u53D8\u91CF\u8BED\u6CD5"),[...new Set(t)]}function rs(e,t,n={}){let r=e?.nodes[t];if(!r)return;let i=r.picker?n[r.picker]??e?.pickers[r.picker]?.selected:void 0;return typeof i=="string"?r.byPlan?.[i]??r.base:r.base}import{z as S}from"zod";var ri=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],jn=S.enum(ri),Tn=S.object({source:jn,layout:S.enum(["full","compact"]),resourceKey:ie.optional(),pageSize:S.number().int().min(1).max(50),showSources:S.boolean(),allowPurchase:S.boolean(),outputs:S.object({billing_adjustment:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),T=S.string().max(2e3),Pn=S.object({id:S.string().max(100),label:T,detail:S.array(T).max(12),value:T.optional(),status:T.optional(),facts:S.array(S.object({label:T,value:T}).strict()).max(1e3),purchaseId:S.uuid().optional(),invoiceUrl:S.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:S.array(S.strictObject({action:S.literal("invoice_open"),label:T})).max(1).optional(),membershipActions:S.array(S.object({value:S.string().max(100),label:T}).strict()).max(3).optional()}).strict(),ii=S.object({key:ie,name:T,spendable:T,reserved:T,available:T,expiry:T.nullable(),sources:S.array(Pn).max(50),sourceCount:S.number().int().nonnegative(),sourcePage:S.number().int().positive(),hasNextSources:S.boolean(),hasPreviousSources:S.boolean()}).strict(),oi=S.object({source:jn,status:S.enum(["idle","loading","ready","error"]),stale:S.boolean(),preview:S.boolean(),errorCode:S.string().max(80).optional(),errorMessage:T.optional(),resources:S.array(ii).max(500),rows:S.array(Pn).max(50),hasNext:S.boolean(),hasPrevious:S.boolean(),page:S.number().int().positive(),filter:S.string().max(40),updatedAt:S.iso.datetime().optional(),buyingId:S.uuid().optional(),membershipBusy:S.boolean().optional(),billingBusy:S.boolean().optional(),membershipReview:S.object({title:T,note:T,facts:S.array(S.object({label:T,value:T}).strict()).max(100)}).strict().optional(),membershipResult:T.optional()}).strict(),ss=S.object({nodes:S.record(S.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),oi)}).strict(),cs=S.object({nodeId:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:S.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:S.string().max(100).optional()}).strict();import{z as v}from"zod";var ai=v.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ps=v.discriminatedUnion("type",[v.object({type:v.literal("fixed"),productVersionId:v.string().min(1).max(200)}).strict(),v.object({type:v.literal("picker"),pickerId:ai,allowedProductVersionIds:v.array(v.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),si=v.strictObject({min:v.number().finite().min(1).max(1800),max:v.number().finite().min(1).max(1800),viewport:v.number().finite().min(1).max(100)}).refine(e=>e.min<=e.max,"Desktop width range is reversed"),Dn={desktopWidth:si.optional(),mobile:v.enum(["sheet","fullscreen"]).optional(),backdrop:v.enum(["none","scrim","dim","strong-dim","blur"]).optional()},Ln=v.discriminatedUnion("type",[v.strictObject({type:v.literal("modal"),size:v.enum(["sm","md","lg"]),...Dn}),v.strictObject({type:v.literal("sheet"),size:v.enum(["sm","md","lg"]),...Dn}),v.strictObject({type:v.literal("fullscreen")}),v.strictObject({type:v.literal("inline")})]),ci={sm:360,md:420,lg:560};import{z as c}from"zod";function Un(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function zn(e){let t={};function n(r){if(Un(r)){let i=t[r.interaction.pickerId]??={ids:[],defaultId:null};for(let a of r.children){let s=a.type==="stack"?a.bind?.plan:void 0;s&&!i.ids.includes(s)&&i.ids.push(s)}let o=r.children[r.interaction.defaultIndex];!i.defaultId&&o?.type==="stack"&&(i.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}function $n(e,t,n){let r={};function i(u){if(u.hidden)return;if(u.type==="plan_picker"){let g=n.pickers[u.id];r[u.id]={ids:g?.options??[],defaults:g?.selected?[g.selected]:[],remembered:[]};return}if(u.type!=="stack")return;let f=u.children.filter(g=>!g.hidden),d=u.interaction;if(Un(u)){let g=r[u.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},I=n.pickers[u.interaction.pickerId]?.options??[];for(let b of f){let k=b.type==="stack"?b.bind?.plan:void 0;k&&I.includes(k)&&!g.ids.includes(k)&&g.ids.push(k),k&&b.id===t[u.id]&&g.remembered.push(k)}let y=u.children[u.interaction.defaultIndex];y?.type==="stack"&&!y.hidden&&y.bind?.plan&&g.defaults.push(y.bind.plan)}if(d?.type==="tabs"){let g=f.find(I=>I.id===t[u.id])??u.children[d.defaultIndex];g&&i(g)}else if(d?.type==="toggle"){let g=typeof t[u.id]=="boolean"?t[u.id]:d.defaultEnabled,I=u.children[g?0:1];I&&i(I)}else f.forEach(i)}let o=typeof t.__page=="string"?t.__page:e.initialPageId??e.pages[0]?.id,a=e.pages.find(u=>u.id===o);a&&i(a.root);let s={};for(let[u,f]of Object.entries(r)){let d=t[u],g=f.remembered[0]??(f.ids.includes(n.pickers[u]?.selected??"")?n.pickers[u]?.selected:f.defaults[0]);s[u]=typeof d=="string"?f.ids.includes(d)?d:"":g&&f.ids.includes(g)?g:""}for(let u of Object.keys(zn(e)))s[u]??="";return s}import{z as Y}from"zod";var Fn=Y.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Vn=Y.strictObject({tiers:Y.array(Y.strictObject({id:Fn,name:Y.string().trim().min(1).max(80)})).min(1).max(8),assignments:Y.array(Y.strictObject({productVersionId:Y.string().min(1).max(200),tierId:Fn,period:Y.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function Bn(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}function hs(e){let t=_t(e).map(n=>`\u672A\u77E5\u53D8\u91CF\uFF1A${n}`);for(let n=0;n<e.length;n++){if(e[n]!=="<"||!/[A-Za-z!/?{]/.test(e[n+1]??""))continue;let r=n;if(e.startsWith("<!--",n)){let i=e.indexOf("-->",n+4);n=i<0?e.length:i+2}else{let i="";for(n++;n<e.length;n++){let o=e[n];if(i)o===i&&(i="");else if(o==='"'||o==="'")i=o;else if(o===">")break}}/\{\{|\}\}/.test(e.slice(r,n+1))&&t.push("\u53D8\u91CF\u53EA\u80FD\u653E\u5728 HTML \u6587\u5B57\u4E2D\uFF0C\u4E0D\u80FD\u653E\u5165\u6807\u7B7E\u3001\u5C5E\u6027\u6216\u6CE8\u91CA")}return[...new Set(t)]}import{z as m}from"zod";var j={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},qn=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),L=m.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(e=>!qn.has(e),"Reserved UI identifier"),wt=m.union([m.string().max(2e3),m.number().finite(),m.boolean(),m.null()]),ui=m.discriminatedUnion("type",[m.strictObject({type:m.literal("enum"),values:m.array(wt).min(1).max(j.enumValues),default:wt}),m.strictObject({type:m.literal("number"),min:m.number().finite(),max:m.number().finite(),step:m.number().finite().positive(),default:m.number().finite()}),m.strictObject({type:m.literal("text"),maxLength:m.number().int().min(0).max(2e3),default:m.string().max(2e3).nullable()}),m.strictObject({type:m.literal("boolean"),default:m.boolean()})]);function qe(e,t){if(e.type==="enum")return e.values.some(r=>r===t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="text")return t===null||typeof t=="string"&&t.length<=e.maxLength;if(typeof t!="number"||!Number.isFinite(t)||t<e.min||t>e.max)return!1;let n=(t-e.min)/e.step;return Number.isFinite(n)&&Math.abs(n-Math.round(n))<=Math.min(1e-7,Math.max(1,Math.abs(n))*Number.EPSILON*8)}var li=ui.superRefine((e,t)=>{e.type==="enum"&&new Set(e.values).size!==e.values.length&&t.addIssue({code:"custom",path:["values"],message:"UI enum values must be unique"}),e.type==="number"&&e.min>e.max&&t.addIssue({code:"custom",path:["max"],message:"UI number range is reversed"}),qe(e,e.default)||t.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),pi=["add","sub","mul","div","min","max","round","floor","eq","ne","gt","gte","lt","lte","and","or","not","if","concat","number","parse_number","money","lookup","now","duration"];function di(e,t){return e==="now"?t===0:e==="concat"?!0:e==="lookup"?t>=4&&t%2===0:e==="if"?t===3:["sub","div","eq","ne","gt","gte","lt","lte"].includes(e)?t===2:["round","floor","not","number","parse_number","money","duration"].includes(e)?t===1:t>=1}var se=m.lazy(()=>m.union([wt,m.strictObject({ref:L}),m.strictObject({op:m.enum(pi),args:m.array(se).max(j.expressionNodes)}).superRefine((e,t)=>{di(e.op,e.args.length)||t.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function H(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function ae(e,t,n){if(!e||typeof e!="object")return!0;if(!H(e))return t.addIssue({code:"custom",path:n,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(e)){if(qn.has(r))return t.addIssue({code:"custom",path:[...n,r],message:"Reserved UI object key"}),!1;let i=Object.getOwnPropertyDescriptor(e,r);if(i&&!Object.hasOwn(i,"value"))return t.addIssue({code:"custom",path:[...n,r],message:"UI objects cannot contain accessors"}),!1}return!0}function he(e,t,n,r){let i=[{value:e,depth:1,path:n}];for(;i.length;){let o=i.pop();if(++r.nodes>j.expressionNodes||o.depth>j.depth){t.addIssue({code:"custom",path:o.path,message:"UI expression budget exceeded"});return}if(!ae(o.value,t,o.path))return;if(H(o.value)&&Array.isArray(o.value.args)){if(o.value.args.length>j.expressionNodes){t.addIssue({code:"custom",path:[...o.path,"args"],message:"UI expression budget exceeded"});return}for(let a=o.value.args.length-1;a>=0;a--)i.push({value:o.value.args[a],depth:o.depth+1,path:[...o.path,"args",a]})}}}var Ss=m.unknown().superRefine((e,t)=>{he(e,t,[],{nodes:0})}).pipe(se),Ot=m.record(L,se).refine(e=>Object.keys(e).length>0&&Object.keys(e).length<=j.state,"UI assignments need 1\u201332 state keys"),fi=m.strictObject({target:L,property:m.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:se,className:L.optional()}).superRefine((e,t)=>{e.property==="class"!=(e.className!==void 0)&&t.addIssue({code:"custom",path:["className"],message:"Only class bindings require a safe className"})}),mi=m.discriminatedUnion("type",[m.strictObject({type:m.literal("scroll_latch"),target:L,state:L}),m.strictObject({type:m.literal("input"),target:L,state:L,set:Ot.optional()}),m.strictObject({type:m.literal("action"),target:L,set:Ot}),m.strictObject({type:m.literal("carousel"),target:L,state:L,initialIndex:m.number().int().nonnegative().optional(),maxWidth:m.number().int().min(1).max(1e4).optional(),previousTarget:L.optional(),nextTarget:L.optional(),inactiveTargets:m.array(L).max(20).optional(),inactiveMaxWidth:m.number().int().min(1).max(1e4).optional()})]),gi=m.strictObject({afterMs:m.number().int().min(0).max(6e4),set:Ot}),bi=m.strictObject({type:m.literal("mosaic_waves"),target:L,color:m.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:m.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:se.optional(),speed:m.number().min(0).max(4).optional(),pitch:m.number().min(.05).max(4).optional(),fill:m.number().min(.05).max(1).optional(),feather:m.number().min(0).max(1).optional(),warp:m.number().min(0).max(4).optional(),warpScale:m.number().min(0).max(32).optional(),detailScale:m.number().min(0).max(32).optional(),waveScale:m.number().min(0).max(32).optional(),falloff:m.number().min(.1).max(32).optional(),brightness:m.number().min(0).max(32).optional(),ambient:m.number().min(0).max(1).optional(),gamma:m.number().min(.05).max(8).optional(),vignette:m.number().min(0).max(1).optional(),opacity:m.number().min(0).max(1).optional()}),hi=m.strictObject({type:m.literal("number_counter"),target:L,value:se,prefix:m.string().max(20).optional(),format:m.enum(["number","short"]).optional()}),yi=m.strictObject({state:m.record(L,li).refine(e=>Object.keys(e).length<=j.state,"Too many UI state keys").optional(),derived:m.record(L,se).refine(e=>Object.keys(e).length<=j.derived,"Too many UI derived keys").optional(),bindings:m.array(fi).max(j.bindings).optional(),controls:m.array(mi).max(j.controls).optional(),timers:m.array(gi).max(j.timers).optional(),effects:m.array(m.discriminatedUnion("type",[bi,hi])).max(j.effects).optional(),clock:m.boolean().optional()});function xi(e,t){if(!ae(e,t,[])||!H(e))return;for(let[r,i]of[["state",j.state],["derived",j.derived]]){let o=e[r];if(!ae(o,t,[r]))return;if(H(o)&&Object.keys(o).length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}}for(let[r,i]of[["bindings",j.bindings],["controls",j.controls],["timers",j.timers],["effects",j.effects]])if(Array.isArray(e[r])&&e[r].length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}if(Array.isArray(e.effects)){for(let[r,i]of e.effects.entries())if(!ae(i,t,["effects",r]))return}if(H(e.state))for(let[r,i]of Object.entries(e.state)){if(!ae(i,t,["state",r]))return;if(H(i)&&Array.isArray(i.values)&&i.values.length>j.enumValues){t.addIssue({code:"custom",path:["state",r,"values"],message:"Too many UI enum values"});return}}let n={nodes:0};if(H(e.derived))for(let[r,i]of Object.entries(e.derived))he(i,t,["derived",r],n);for(let r of["bindings","controls","timers"]){let i=e[r];if(Array.isArray(i)){for(let[o,a]of i.entries())if(!(!ae(a,t,[r,o])||!H(a))){if(r==="bindings")he(a.expression,t,[r,o,"expression"],n);else if(ae(a.set,t,[r,o,"set"])&&H(a.set)){if(Object.keys(a.set).length>j.state){t.addIssue({code:"custom",path:[r,o,"set"],message:"Too many UI assignments"});return}for(let[s,u]of Object.entries(a.set))he(u,t,[r,o,"set",s],n)}if(n.nodes>j.expressionNodes)return}}}if(Array.isArray(e.effects))for(let[r,i]of e.effects.entries())H(i)&&i.type==="number_counter"?he(i.value,t,["effects",r,"value"],n):H(i)&&i.enabled!==void 0&&he(i.enabled,t,["effects",r,"enabled"],n)}function Mn(e){let t=[],n=[e];for(;n.length;){let r=n.pop();!r||typeof r!="object"||("ref"in r?t.push(r.ref):n.push(...r.args))}return t}var Hn=m.unknown().superRefine(xi).pipe(yi).superRefine((e,t)=>{let n=e.state??{},r=e.derived??{},i=new Set([...Object.keys(n),...Object.keys(r)]),o=(y,b)=>{for(let k of Mn(y))i.has(k)||t.addIssue({code:"custom",path:b,message:`Unknown UI reference: ${k}`})};for(let[y,b]of Object.entries(e.derived??{}))Object.hasOwn(n,y)&&t.addIssue({code:"custom",path:["derived",y],message:"UI state and derived identifiers must be distinct"}),o(b,["derived",y]);let a=new Set,s=new Set,u=y=>{if(a.has(y))return!1;if(s.has(y))return!0;a.add(y);for(let b of Mn(r[y]))if(Object.hasOwn(r,b)&&!u(b))return!1;return a.delete(y),s.add(y),!0};for(let y of Object.keys(r))if(!u(y)){t.addIssue({code:"custom",path:["derived",y],message:"Cyclic UI derived references"});break}for(let[y,b]of(e.bindings??[]).entries())o(b.expression,["bindings",y,"expression"]);let f=new Set;for(let[y,b]of(e.effects??[]).entries())f.has(b.target)&&t.addIssue({code:"custom",path:["effects",y,"target"],message:"Effect targets must be unique"}),f.add(b.target),b.type==="number_counter"?(o(b.value,["effects",y,"value"]),typeof b.value=="number"&&Math.abs(b.value)>1e12&&t.addIssue({code:"custom",path:["effects",y,"value"],message:"Counter values must be within the display bound"})):b.enabled!==void 0&&o(b.enabled,["effects",y,"enabled"]);let d=(y,b)=>{for(let[k,O]of Object.entries(y))Object.hasOwn(n,k)||t.addIssue({code:"custom",path:[...b,k],message:"UI assignments can only update declared state"}),o(O,[...b,k])},g=new Set,I=new Set;for(let[y,b]of(e.controls??[]).entries()){if(b.type==="carousel"&&b.inactiveMaxWidth!==void 0&&b.inactiveTargets===void 0&&t.addIssue({code:"custom",path:["controls",y,"inactiveMaxWidth"],message:"Inactive width requires inactive article targets"}),b.type==="carousel")for(let k of b.inactiveTargets??[])(k===b.target||I.has(k))&&t.addIssue({code:"custom",path:["controls",y,"inactiveTargets"],message:"Inactive article targets must have one carousel owner"}),I.add(k);if(b.type==="carousel")for(let k of["previousTarget","nextTarget"]){let O=b[k];O!==void 0&&((O===b.target||g.has(O)||(e.controls??[]).some(U=>U.target===O))&&t.addIssue({code:"custom",path:["controls",y,k],message:"Carousel navigation needs a distinct, exclusive button target"}),g.add(O))}if(b.type!=="action"){let k=Object.hasOwn(n,b.state)?n[b.state]:void 0;(!k||b.type==="input"&&k.type==="enum"&&k.values.some(O=>typeof O!="string"))&&t.addIssue({code:"custom",path:["controls",y,"state"],message:"Control needs a supported declared UI state"}),b.type==="carousel"&&(k?.type!=="number"||!Number.isInteger(k.min)||k.min<0||!Number.isInteger(k.max)||k.step!==1||b.initialIndex!==void 0&&!qe(k,b.initialIndex))&&t.addIssue({code:"custom",path:["controls",y],message:"Carousel needs bounded nonnegative integer index state"}),b.type==="scroll_latch"&&k?.type!=="boolean"&&t.addIssue({code:"custom",path:["controls",y,"state"],message:"Scroll latches require boolean UI state"})}(b.type==="input"||b.type==="action")&&b.set&&d(b.set,["controls",y,"set"])}for(let[y,b]of(e.timers??[]).entries())d(b.set,["timers",y,"set"])});import{z as Si}from"zod";var Qn=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,ye=Si.string().max(16).regex(Qn,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");function vt(e){if(typeof e!="string")return null;try{let t=Intl.getCanonicalLocales(e.trim().replaceAll("_","-"))[0];if(!t)return null;let{language:n,script:r,region:i}=new Intl.Locale(t),o=[n,r,i].filter(Boolean).join("-");return Qn.test(o)?o:null}catch{return null}}var ki=new Set(["TW","HK","MO"]);function Gn(e){let[t,n,r]=e.split("-");if(t!=="zh")return`${t}-${new Intl.Locale(e).maximize().script??""}`;let i=n?.length===4?n:void 0,o=n?.length===4?r:n;return i?`zh-${i}`:o&&ki.has(o)?"zh-Hant":"zh-Hans"}function Kn(e,t,n){let r=t.map(i=>({code:ye.parse(i),normalized:i}));for(let i of e){let o=vt(i);if(!o)continue;let a=r.find(d=>d.normalized===o);if(a)return a.code;let s=Gn(o),u=r.filter(d=>Gn(d.normalized)===s),f=u.find(d=>!d.normalized.includes("-")||d.normalized===s)??u[0];if(f)return f.code}return n}var Ii=4,Q={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},_e=c.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),w=c.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ai=c.enum(["none","xs","sm","md","lg","xl"]),Ei=c.enum(["none","sm","md","lg","full"]),Rt=c.string().regex(/^#[0-9a-fA-F]{6}$/),Ct=c.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),Nt=c.union([Ct,c.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),c.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),c.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Zn=c.object({primary:Rt,background:Rt,text:Rt,radius:Ei,font:c.enum(["system","serif","rounded","mono"]),fontAssets:c.object({family:c.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:c.array(c.object({url:Ct,weight:c.number().int().min(100).max(900).multipleOf(100),family:c.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),we=c.union([c.enum(["primary","text","muted","background","surface"]),c.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),A=(e,t)=>c.number().int().min(e).max(t),Wn=c.union([c.enum(["fit","fill"]),A(1,1200)]),_i=c.object({top:A(0,200),right:A(0,200),bottom:A(0,200),left:A(0,200)}).strict(),wi=c.object({top:A(-100,200),right:A(-100,200),bottom:A(-100,200),left:A(-100,200)}).strict(),Jn=c.object({x:A(0,100),y:A(0,100)}).strict(),Oi=c.discriminatedUnion("type",[c.object({type:c.literal("color"),color:we}).strict(),c.object({type:c.literal("linear"),angle:A(0,360),stops:c.array(c.object({color:we,at:A(0,100)}).strict()).min(2).max(4)}).strict(),c.object({type:c.literal("image"),src:Nt,fit:c.enum(["cover","contain"]),position:Jn.optional()}).strict()]),vi=c.discriminatedUnion("type",[c.object({type:c.literal("rect"),radius:c.union([A(0,200),c.object({topLeft:A(0,200),topRight:A(0,200),bottomRight:A(0,200),bottomLeft:A(0,200)}).strict()])}).strict(),c.object({type:c.literal("pill")}).strict()]),Ri=c.object({width:A(0,12),color:we,style:c.enum(["solid","dashed"])}).strict(),Ni=c.object({x:A(-40,40),y:A(-40,40),blur:A(0,80),spread:A(-20,40),color:we}).strict(),Ci=c.object({font:c.enum(["system","serif","rounded","mono"]),size:A(8,96),weight:c.number().int().min(100).max(900).multipleOf(100),lineHeight:c.number().min(.8).max(3),letterSpacing:c.number().min(-5).max(20),color:we,align:c.enum(["start","center","end"]),italic:c.boolean(),decoration:c.enum(["none","underline","line-through"]),transform:c.enum(["none","uppercase"])}).strict().partial(),ce=c.object({width:Wn,height:Wn,padding:_i,margin:wi,gap:A(0,120),grow:c.union([c.boolean(),c.number().min(0).max(12)]),background:Oi,opacity:c.number().min(0).max(1),clipContent:c.boolean(),shape:vi,border:Ri,shadow:Ni,text:Ci}).strict().partial(),F={id:_e,name:c.string().trim().min(1).max(60).optional(),hidden:c.boolean().optional(),style:ce.optional(),fallback:w.optional()},ji=c.object({...F,type:c.literal("text"),productField:c.enum(["name","price","trial","period"]).optional(),feature:c.object({id:c.uuid(),field:c.enum(["name","allowance"])}).strict().optional(),text:w,variant:c.enum(["title","heading","body","caption"])}).strict(),Ti=c.object({...F,type:c.literal("image"),src:Nt,localizedSrc:c.record(ye,Nt).optional(),alt:w,aspect:c.enum(["auto","1:1","4:3","16:9","3:1"]),fit:c.enum(["cover","contain"]),position:Jn.optional()}).strict(),Pi=c.object({...F,type:c.literal("button"),label:w,variant:c.enum(["primary","secondary","link"]),action:w,purpose:c.enum(["purchase","navigation","close"]).optional(),bind:Me.optional()}).strict(),Di=c.object({...F,type:c.literal("divider")}).strict(),Li=c.object({...F,type:c.literal("customer_data"),title:w,data:Tn}).strict(),Ui=c.object({...F,type:c.literal("spacer"),size:Ai}).strict(),zi=c.object({...F,type:c.literal("custom_html"),html:c.record(ye,c.string().max(Q.customHtml)),css:c.string().max(Q.customCss),ui:Hn.optional()}).strict(),$i=c.object({...F,type:c.literal("price"),fallback:w,parts:c.object({current:ce.optional(),original:ce.optional(),period:ce.optional()}).strict().optional()}).strict(),Fi=c.object({...F,type:c.literal("coupon_code"),label:w,fallback:w}).strict(),Vi=c.object({...F,type:c.literal("countdown"),source:c.enum(["offer.ends_at","offer.expires_at","fixed"]),at:c.iso.datetime().optional(),granularity:c.enum(["day","hour","minute","second"]),expired:w,fallback:w}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Bi=c.object({...F,type:c.literal("plan_picker"),label:w,fallback:w,planIds:c.array(c.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:c.string().min(1).max(200).optional(),grouping:Vn.safeExtend({monthLabel:w,yearLabel:w,unavailableLabel:w}).optional(),states:c.object({selected:ce.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Bn(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Mi=c.object({...F,type:c.literal("quantity_picker"),bind:Me.optional(),label:w,fallback:w,internalFeatureId:c.uuid(),minimumQuantity:A(0,1e4),maximumQuantity:A(0,1e4),defaultQuantity:A(0,1e4),step:A(1,1e4)}).strict().refine(e=>e.minimumQuantity<=e.defaultQuantity&&e.defaultQuantity<=e.maximumQuantity&&(e.defaultQuantity-e.minimumQuantity)%e.step===0,"Quantity controls require a Product binding and valid bounds"),qi=c.discriminatedUnion("type",[c.object({type:c.literal("input"),label:w,keyboard:c.enum(["text","email","tel","url"]),maxLength:A(1,500)}).strict(),c.object({type:c.literal("multiselect"),label:w,min:A(0,50),max:A(1,50)}).strict(),c.object({type:c.literal("select"),label:w,defaultIndex:A(0,49),purpose:c.enum(["option","product","tier"]).optional(),pickerId:_e.optional(),selectedStyle:ce.optional()}).strict(),c.object({type:c.literal("tabs"),label:w,defaultIndex:A(0,49),purpose:c.literal("tier").optional()}).strict(),c.object({type:c.literal("toggle"),label:w,defaultEnabled:c.boolean()}).strict(),c.object({type:c.literal("carousel"),label:w}).strict()]),G={...F,type:c.literal("stack"),direction:c.enum(["vertical","horizontal","overlay"]),align:c.enum(["start","center","end","stretch"]),justify:c.enum(["start","center","end","between"]),productSlot:c.object({index:A(0,19),period:c.enum(["month","year"]).optional(),requireBinding:c.boolean().optional()}).strict().optional(),interaction:qi.optional(),states:c.object({selected:ce.optional()}).strict().optional(),purpose:c.literal("benefits").optional(),purchaseAction:w.optional(),buttonVariant:c.enum(["primary","secondary","link"]).optional(),bind:Me.optional()},Yn=c.lazy(()=>c.object({...F,type:G.type,direction:G.direction,align:G.align,justify:G.justify,children:c.array(Hi).max(Q.children),productSlot:G.productSlot,interaction:G.interaction,states:G.states,purpose:G.purpose,purchaseAction:G.purchaseAction,buttonVariant:G.buttonVariant,bind:G.bind}).strict()),Hi=c.lazy(()=>c.union([Yn,ji,Ti,Pi,Di,Ui,zi,$i,Fi,Vi,Bi,Mi,Li])),Gi=c.union([c.string().max(500),c.number().finite(),c.boolean(),c.null()]),Ee={id:w,event:w,properties:c.record(w,Gi).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},Qi=c.discriminatedUnion("type",[c.object({...Ee,type:c.literal("navigate"),close:c.literal(!1),pageId:_e}).strict(),c.object({...Ee,type:c.literal("event"),close:c.boolean()}).strict(),c.object({...Ee,type:c.literal("close"),close:c.literal(!0)}).strict(),c.object({...Ee,type:c.literal("open_url"),close:c.boolean(),url:Ct}).strict(),c.object({...Ee,type:c.literal("claim_offer"),close:c.boolean(),couponId:c.uuid()}).strict()]),Ki=c.object({defaultLocale:ye,locales:c.record(ye,c.record(w,c.string().max(Q.stringLength)))}).strict(),Zi=c.enum(["popup","paywall","onboarding","page","banner"]);var Wi=c.object({kind:c.literal("screen"),schemaVersion:c.literal(Ii),name:c.string().trim().min(1).max(80),surface:Zi,initialPageId:_e.optional(),presentation:Ln,theme:Zn,pages:c.array(c.object({id:_e,name:c.string().trim().min(1).max(60),root:Yn,theme:Zn.optional(),editorPosition:c.object({x:c.number().finite().min(-1e5).max(1e5),y:c.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(Q.pages),strings:Ki,actions:c.array(Qi).max(Q.actions)}).strict();function W(e,t){for(let n of e.pages)jt(n.root,t)}var js=Wi.superRefine((e,t)=>{let n=Q;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(d=>d.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let d of e.actions)d.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(g=>g.id===d.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=d=>t.addIssue({code:"custom",message:d}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>Q.locales&&r(`\u6700\u591A ${Q.locales} \u79CD\u8BED\u8A00`);let o=new Set;for(let d of e.actions)o.has(d.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${d.id}`),o.add(d.id);let a=new Set;for(let d of e.pages)["next","back"].includes(d.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${d.id}`),a.has(d.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${d.id}`),a.add(d.id);let s=new Set,u=0,f=!1;W(e,(d,g)=>{if(u++,g>Q.depth&&(f=!0),s.has(d.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${d.id}`),s.add(d.id),d.type==="button"&&!o.has(d.action)&&r(`\u6309\u94AE ${d.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${d.action}`),d.type==="custom_html")for(let I of Object.keys(d.html))i.includes(I)||r(`\u81EA\u5B9A\u4E49 HTML ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${I}`);if(d.type==="image")for(let I of Object.keys(d.localizedSrc??{}))i.includes(I)||r(`\u56FE\u7247 ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${I}`)}),u>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),f&&r(`\u5C42\u7EA7\u6700\u591A ${Q.depth} \u5C42`)});function jt(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)jt(i,t,n+1,e)}function Xn(e){let t=[],n=new Set;return W(e,r=>{let i=(o,a,s)=>{n.has(o)||(n.add(o),t.push({key:o,nodeId:r.id,nodeType:r.type,field:a,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function Ji(e,t,n){if(t.field==="html"){let r;return W(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=Tt(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function Yi(e){let t=Xn(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(o=>!Ji(e,o,r)?.trim()).map(o=>o.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function Xi(e){return Yi(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function Ts(e,t){return Kn(t,Xi(e),e.strings.defaultLocale)}function Ps(e,t){let n=e.strings.locales[t]??{},r=e.strings.locales[e.strings.defaultLocale]??{},i={};for(let a of Xn(e)){if(a.field==="html"||a.field==="src")continue;let s=n[a.key]?.trim()?n[a.key]:r[a.key];s!==void 0&&(i[a.key]=s)}let o=a=>{if(a.type==="stack")return{...a,children:a.children.map(o)};if(a.type==="custom_html"){let s=a.html[t]?.trim()?a.html[t]:a.html[e.strings.defaultLocale];return{...a,html:s===void 0?{}:{[t]:s}}}if(a.type==="image"){let{localizedSrc:s,...u}=a;return{...u,src:s?.[t]??s?.[e.strings.defaultLocale]??a.src}}return a};return{...e,pages:e.pages.map(a=>({...a,root:o(a.root)})),strings:{defaultLocale:t,locales:{[t]:i}}}}function eo(e,t){let n=null;return jt(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function Tt(e,t){for(let n of e.pages){let r=eo(n.root,t);if(r)return r}return null}function Ds(e){let t=vt(e)?.split("-")[0];return t!==void 0&&["ar","he","fa","ur"].includes(t)}function Ls(e,t,n){let r={};if(!t||typeof t!="object"||Array.isArray(t))return r;let i=t;if(W(e,o=>{if(o.type==="quantity_picker"){let s=i[o.id];typeof s=="number"&&Number.isSafeInteger(s)&&s>=o.minimumQuantity&&s<=o.maximumQuantity&&(s-o.minimumQuantity)%o.step===0&&(r[o.id]=s);return}if(o.type==="plan_picker"){let s=i[o.id];typeof s=="string"&&(r[o.id]=n?.pickers[o.id]?.options.includes(s)?s:"");return}if(o.type==="custom_html"&&o.ui)for(let[s,u]of Object.entries(o.ui.state??{})){let f=`${o.id}.${s}`,d=i[f];d!==null&&qe(u,d)&&(r[f]=d)}if(o.type!=="stack"||!o.interaction)return;let a=Object.hasOwn(i,o.id)?i[o.id]:void 0;["select","tabs"].includes(o.interaction.type)&&typeof a=="string"&&o.children.some(s=>s.id===a)&&(r[o.id]=a),o.interaction.type==="toggle"&&typeof a=="boolean"&&(r[o.id]=a)}),e.surface==="paywall"&&typeof i.__page=="string"&&e.pages.some(o=>o.id===i.__page)&&(r.__page=i.__page),n){let o={...r};for(let[a,s]of Object.entries(i))(typeof s=="string"||typeof s=="boolean")&&(o[a]=s);Object.assign(r,$n(e,o,n))}return r}import{z as C}from"zod";import{z as p}from"zod";import{z as h}from"zod";var ue=N.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Oe=h.string().min(1).max(120),He=h.enum(["cap","overflow"]),V=(e,t)=>{let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},ve=e=>{try{return e()}catch{return!1}},Vs=h.discriminatedUnion("operation",[h.object({operation:h.literal("quote"),overageBehavior:He.optional(),internal_feature_id:h.uuid(),entityId:h.uuid().optional(),quantity:ue,properties:B}).strict(),h.object({operation:h.literal("consume"),overageBehavior:He.optional(),occurredAt:h.iso.datetime({offset:!0}).optional(),internal_feature_id:h.uuid(),entityId:h.uuid().optional(),quantity:N,properties:B,idempotencyKey:Oe}).strict(),h.object({operation:h.literal("reserve"),occurredAt:h.iso.datetime({offset:!0}).optional(),internal_feature_id:h.uuid(),entityId:h.uuid().optional(),quantity:ue,properties:B,idempotencyKey:Oe,expiresInSeconds:h.number().int().min(1).max(86400)}).strict(),h.object({operation:h.literal("confirm"),operationId:h.uuid(),quantity:ue,properties:B.optional(),idempotencyKey:Oe}).strict(),h.object({operation:h.literal("refund"),operationId:h.uuid(),quantity:ue,idempotencyKey:Oe}).strict(),h.object({operation:h.literal("release"),operationId:h.uuid(),idempotencyKey:Oe}).strict()]),to=h.object({internal_credit_feature_id:h.uuid().nullable(),internal_metered_feature_id:h.uuid(),dimension:h.string().min(1).max(64),counterKey:h.string().min(1).max(240),cycleStart:h.iso.datetime({offset:!0}),unitCost:N,units:ue,amount:Ce,tier:h.number().int().min(1).max(12).nullable()}).strict(),Re=h.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function er(e,t){let n=e.reduce((r,i)=>r+V(i.units,12),0n)-V(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var tr=h.discriminatedUnion("funding",[h.strictObject({funding:h.literal("balance"),sourceId:h.uuid(),rolloverId:h.uuid().nullable(),units:Re.refine(e=>/[1-9]/.test(e)),amount:Ce}),h.strictObject({funding:h.literal("unbilled"),units:Re.refine(e=>/[1-9]/.test(e))}),h.object({funding:h.literal("prepaid"),sourceId:h.uuid(),units:ue,amount:Ce,pricing:h.array(to).min(1).max(12)}).strict().refine(e=>ve(()=>e.pricing.reduce((t,n)=>t+V(n.units,6),0n)===V(e.units,6)&&e.pricing.reduce((t,n)=>t+V(n.amount,12),0n)===V(e.amount,12)&&e.pricing.every(t=>V(t.unitCost,6)*V(t.units,6)===V(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),h.object({funding:h.literal("postpaid"),invoiceLineId:h.uuid().nullable(),units:ue,authorizationId:h.uuid()}).strict()]),Ge=h.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Bs=h.object({allowed:h.boolean(),internal_feature_id:h.uuid(),quantity:N,requestedQuantity:N.optional(),overageBehavior:He.optional(),reason:Ge.nullable(),allocations:h.array(tr).max(500)}).strict().refine(e=>ve(()=>e.allowed?e.reason===null&&er(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>ve(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&V(e.requestedQuantity,6)>=V(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Ms=h.object({id:h.uuid(),internal_feature_id:h.uuid(),kind:h.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:h.uuid().nullable(),quantity:N,requestedQuantity:N.optional(),overageBehavior:He.optional(),accepted:h.boolean(),reason:h.enum([...Ge.options,"expired"]).nullable(),createdAt:h.iso.datetime({offset:!0}),reservationStatus:h.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:h.iso.datetime({offset:!0}).nullable(),allocations:h.array(tr).max(500)}).strict().refine(e=>ve(()=>e.accepted?e.reason===null&&er(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>ve(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&V(e.requestedQuantity,6)>=V(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as K}from"zod";var no=K.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),ro=K.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),nr=K.strictObject({internal_feature_id:K.uuid(),entityId:K.uuid().nullable()}),Qs=nr.extend({quantity:N,expectedRevision:K.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:K.string().min(1).max(120),properties:B.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),rr=nr.extend({operationId:K.uuid().nullable(),usage:N,capacity:no.nullable(),remaining:ro.nullable(),withinLimit:K.boolean(),revision:K.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:K.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[o,a=""]=(i?r.slice(1):r).split(".");if(o===void 0||o==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(o)*10n**12n+BigInt(a.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var J=p.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),Z=p.iso.datetime({offset:!0}),io=p.enum(["access","metered","credit"]),Ne={internal_feature_id:p.uuid(),key:ie,name:p.string().min(1).max(120),kind:io},ec=p.object({customerId:p.uuid(),snapshotAt:Z,memberships:p.array(p.object({id:p.uuid(),productId:p.string().min(1).max(255),productVersionId:p.uuid(),billingProductVersionId:p.uuid(),version:p.number().int().positive(),key:p.string().min(1).max(64),name:p.string().min(1).max(120),groupId:p.string().max(255).nullable(),membershipType:p.enum(["main","addon"]),status:p.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:p.boolean(),accessEnabled:p.boolean(),renewalChange:p.object({productVersionId:p.uuid(),name:p.string().min(1).max(120),version:p.number().int().positive(),effectiveAt:Z,benefitsAppliedAt:Z.nullable(),timing:p.enum(["immediate","renewal"]),changeKind:p.enum(["plan","seats","quantity"]),feature:p.strictObject({internal_feature_id:p.uuid(),name:p.string().min(1).max(80),fromQuantity:p.number().int().min(0).max(1e4),toQuantity:p.number().int().min(0).max(1e4)}).optional(),seat:p.object({key:p.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:p.number().int().min(0).max(1e4),toQuantity:p.number().int().min(0).max(1e4)}).strict().nullable(),status:p.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:p.object({phase:p.enum(["paid","trial"]),startsAt:Z,endsAt:Z.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:p.boolean(),balances:p.array(p.object({...Ne,usageType:p.enum(["consumable","non_consumable"]).nullable(),accessible:p.boolean(),unlimited:p.boolean(),available:J,held:J,debt:J,nextExpiresAt:Z.nullable(),usage:rr.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:p.boolean()}).strict(),ir=p.enum(["source","usage","transaction","invoice","debt","settlement"]),Qe=p.object({at:Z,id:p.uuid(),type:ir}).strict(),tc=p.object({type:ir.nullable(),resourceKey:ie.optional(),kind:p.enum(["purchase","refund"]).optional(),topup:p.boolean().optional(),from:p.iso.date().nullable(),to:p.iso.date().nullable(),after:Qe.nullable(),limit:p.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),xe={id:p.uuid(),occurredAt:Z},oo=p.discriminatedUnion("type",[p.strictObject({...xe,type:p.literal("invoice"),status:p.string().min(1).max(80),paid:J,refunded:J,currency:z,externalId:p.string().nullable()}),p.object({...xe,...Ne,type:p.literal("source"),reason:p.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:J,unlimited:p.boolean(),status:p.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:Z,expiresAt:Z.nullable(),orderId:p.uuid().nullable(),parentSourceId:p.uuid().nullable()}).strict(),p.object({...xe,type:p.literal("usage"),internal_feature_id:p.uuid(),name:p.string().min(1).max(120),kind:p.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:p.uuid().nullable(),quantity:N,accepted:p.boolean(),reason:p.enum([...Ge.options,"expired"]).nullable(),properties:B,reservationStatus:p.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:Z.nullable(),charges:p.array(p.discriminatedUnion("funding",[p.strictObject({funding:p.literal("balance"),sourceId:p.uuid(),rolloverId:p.uuid().nullable(),units:Re,amount:J}),p.strictObject({funding:p.literal("unbilled"),units:Re}),p.object({...Ne,funding:p.literal("prepaid"),amount:J}).strict(),p.object({funding:p.literal("postpaid"),invoiceId:p.uuid(),invoiceLineId:p.uuid(),authorizationId:p.uuid(),units:N,currency:z}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),p.object({...xe,type:p.literal("transaction"),purpose:p.enum(["product","invoice"]),productVersionId:p.uuid().nullable(),productName:p.string().min(1).max(120).nullable(),productVersion:p.number().int().positive().nullable(),invoiceId:p.uuid().nullable(),orderId:p.uuid(),originalId:p.uuid().nullable(),kind:p.enum(["purchase","refund"]),amountMinor:p.number().int().nonnegative().max(2e8).nullable(),currency:z.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),p.object({...xe,...Ne,type:p.literal("debt"),sourceId:p.uuid(),transactionId:p.uuid(),amount:J}).strict(),p.object({...xe,...Ne,type:p.literal("settlement"),sourceId:p.uuid(),debtId:p.uuid(),kind:p.enum(["payment","usage_refund","payment_return"]),amount:J}).strict()]),nc=p.object({customerId:p.uuid(),rows:p.array(oo).max(50),nextCursor:Qe.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");var sc=C.discriminatedUnion("kind",[C.object({kind:C.literal("ledger"),cursor:Qe}).strict(),C.object({kind:C.literal("billing"),cursor:C.uuid()}).strict()]),ao=C.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),so=C.record(C.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),C.union([C.string().max(500),C.boolean(),C.array(C.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),co=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function Pt(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>Pt(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||co.test(n)||Pt(r,t+1)))}var uo=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,cc=C.record(ao,ne).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!Pt(e)&&!uo.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var or=C.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),lo=C.array(C.object({variable:or,componentId:or,required:C.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),uc=C.object({bindings:lo,answers:so,values:C.record(C.string(),ne).optional()}).strict();function ar(e,t,n=1){if(e==="free")return"";if(e==="one_time")return t.startsWith("zh")?" \xB7 \u4E00\u6B21\u4ED8\u6B3E":" \xB7 one-time";let r=t.split("-")[0]??"en",i={zh:["/\u6708","/\u5E74"],en:["/month","/year"],ja:["/\u6708","/\u5E74"],ko:["/\uC6D4","/\uB144"],es:["/mes","/a\xF1o"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/m\xEAs","/ano"],it:["/mese","/anno"],ar:["/\u0634\u0647\u0631","/\u0633\u0646\u0629"]},o={zh:"\u5468",en:"week",ja:"\u9031",ko:"\uC8FC",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"\u0623\u0633\u0628\u0648\u0639"},a=e==="week"?`/${o[r]??o.en}`:(i[r]??i.en)[e==="month"?0:1];return n===1?a:`/${n} ${a.slice(1)}${r==="en"?"s":""}`}function hc(e,t){let n=[],r={};W(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let o=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&W(e,a=>{if(a.type==="plan_picker"&&a.id===i.bind?.picker&&o.push(...a.planIds??[]),a.type==="stack"&&a.interaction?.type==="select"&&a.interaction.pickerId===i.bind?.picker)for(let s of a.children)s.type==="stack"&&s.bind?.plan&&o.push(s.bind.plan)}),o.length||n.push(`Quantity control ${i.id} needs a Product binding`);for(let a of new Set(o)){let s=t[a]?.prepaid?.find(f=>f.internalFeatureId===i.internalFeatureId)?.terms,u=r[a]??=new Set;(!s||u.has(i.internalFeatureId)||i.minimumQuantity<s.minimumQuantity||i.maximumQuantity>s.maximumQuantity)&&n.push(`Quantity control ${i.id} must match its Product's prepaid Feature and bounds`),u.add(i.internalFeatureId)}});for(let[i,o]of Object.entries(t))for(let a of o.prepaid??[])r[i]?.has(a.internalFeatureId)||n.push(`Product ${i} needs a quantity control for ${a.internalFeatureId}`);return n}function yc(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let o={};if(W(e,a=>{if(a.hidden)return!1;if(a.type!=="quantity_picker"||a.hidden||(a.bind?.plan??(a.bind?.picker?n[a.bind.picker]:void 0))!==t)return;let u=i.prepaid?.find(d=>d.internalFeatureId===a.internalFeatureId)?.terms,f=n[a.id];if(!u||typeof f!="number"||!Number.isSafeInteger(f)||f<Math.max(u.minimumQuantity,a.minimumQuantity)||f>Math.min(u.maximumQuantity,a.maximumQuantity)||(f-a.minimumQuantity)%a.step!==0||o[a.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");o[a.internalFeatureId]=f}),(i.prepaid??[]).some(a=>o[a.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return o}function po(e,t,n){let r=e.terms.prices.find(i=>i.currency===t);if(!r||n<e.terms.minimumQuantity||n>e.terms.maximumQuantity)throw new Error("Quantity or currency is unavailable");return{amountMinor:wn({quantity:n,unitAmountMinor:r.amountMinor,...r.pricing?{pricing:r.pricing}:{}}),allowance:Rn(e.includedAmount,e.terms.units,n)}}function xc(e,t,n,r){let i=!1;if(W(e,s=>{s.type==="quantity_picker"&&(i=!0)}),!i)return t;let o=structuredClone(t);o.quantities={};let a=new Map;W(e,s=>{if(s.hidden)return!1;if(s.type!=="quantity_picker")return;let u=s.bind?.plan??(s.bind?.picker?n[s.bind.picker]??o.pickers[s.bind.picker]?.selected:void 0),f=typeof u=="string"?o.plans[u]:void 0,d=f?.prepaid?.find(re=>re.internalFeatureId===s.internalFeatureId),g=Math.max(s.minimumQuantity,d?.terms.minimumQuantity??0),I=Math.min(s.maximumQuantity,d?.terms.maximumQuantity??0),y=n[s.id]??s.defaultQuantity,b=typeof y=="number"&&Number.isSafeInteger(y)?y:s.defaultQuantity,k=!!d&&!!f?.available&&b>=g&&b<=I&&(b-s.minimumQuantity)%s.step===0,O=o.quantities[s.id]={minimum:g,maximum:Math.max(g,I),step:s.step,value:b,label:"",available:k};if(!k||!d||!f?.currency||f.amountMinor===void 0)return;let U=po(d,f.currency,b);O.label=`${new Intl.NumberFormat(r).format(Number(U.allowance))} ${d.name}${["week","month","year"].includes(d.reset)?ar(d.reset,r,d.resetCount):d.reset==="lifetime"?"":` / ${d.resetCount} ${d.reset}`}`,a.set(String(u),(a.get(String(u))??f.amountMinor)+U.amountMinor)});for(let[s,u]of a){let f=o.plans[s];if(!f?.currency)continue;let d=We(u,f.currency,r);f.price=d;for(let[g,I]of Object.entries(o.nodes)){let y=Tt(e,g),b=k=>{if(k.price&&(k.price={...k.price,current:d,original:null}),y?.type==="text"){let O=e.strings.locales[r]?.[y.text]??e.strings.locales[e.strings.defaultLocale]?.[y.text];O?.includes("{{plan.price")&&(k.text=O.replace(/\{\{\s*plan.price\s*\}\}/g,d).replace(/\{\{\s*plan.price_per_month\s*\}\}/g,We(Math.round(u/((f.interval==="year"?12:1)*(f.intervalCount??1))),f.currency,r)))}};I.byPlan?.[s]&&b(I.byPlan[s]),(I.base.planVersionId===s||y&&"bind"in y&&y.bind?.plan===s)&&b(I.base)}}return o}import{z as P}from"zod";var Ke=P.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),Ac=P.enum([...Ke.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),Ec=P.enum([...Ke.options,"stale_revision"]),fo=P.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),mo=P.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","IDENTITY_CONTEXT_CHANGED","CUSTOMER_BINDING_CONFLICT","RUN_CONTRACT_MISMATCH","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),cr={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};var sr={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",CUSTOMER_SESSION_REQUIRED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",PURCHASE_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",PURCHASE_STORAGE_CONFLICT:"resolve_conflict",PURCHASE_STORAGE_INVALID:"recover_operation",EXECUTION_POLICY_REFUSED:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function go(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(sr,e)){let r=sr[e];return{retryable:r==="retry_same_request",recovery:r}}let n=Ke.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:cr[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function _c(e,t){let n=Ke.safeParse(e);if(n.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):cr[n.data].status===t;let r={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(r,e)&&(r[e]?.includes(t)??!1)}function bo(e,t=Date.now()){if(e===null)return;let n=e.trim();if(/^\d+$/.test(n)){let i=Number(n);return Number.isSafeInteger(i)?i:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(n))return;let r=Date.parse(n);return Number.isFinite(r)?Math.max(0,Math.ceil((r-t)/1e3)):void 0}var ur=P.object({retryable:P.boolean(),recovery:fo,reason:mo.optional(),retryAfterSeconds:P.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),ho=P.object({requestId:P.uuid().optional(),error:P.object({code:P.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:P.string(),...ur.partial().shape})}),wc=P.object({error:ho.shape.error.extend({requestId:P.uuid().optional()})}),Oc=P.object({error:P.string(),code:P.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:P.uuid(),...ur.shape});function vc(e,t,n={}){let r=go(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,o=r.retryable&&n.retryable!==!1&&i!=="recover_operation",a=o?bo(n.retryAfter??null):void 0;return{...r,retryable:o,recovery:i,...a===void 0?{}:{retryAfterSeconds:a},...n.reason?{reason:n.reason}:{}}}export{qo as a,Ke as b,fo as c,mo as d,_c as e,ho as f,vc as g,z as h,dr as i,We as j,Pe as k,Le as l,Wt as m,Ue as n,Jt as o,Ce as p,N as q,fr as r,B as s,Eo as t,Ft as u,Se as v,na as w,Or as x,vr as y,ot as z,ia as A,oa as B,aa as C,It as D,wn as E,vn as F,Rn as G,fe as H,pt as I,pn as J,q as K,hn as L,yn as M,An as N,ne as O,St as P,Be as Q,Hr as R,ei as S,ye as T,vt as U,Vs as V,to as W,Re as X,Bs as Y,Ms as Z,nr as _,Qs as $,rr as aa,J as ba,ec as ca,tc as da,nc as ea,Et as fa,Nn as ga,ns as ha,Cn as ia,rs as ja,zn as ka,Vn as la,Bn as ma,ss as na,cs as oa,hs as pa,ps as qa,Ln as ra,ci as sa,Q as ta,w as ua,Nt as va,W as wa,js as xa,jt as ya,Xn as za,Yi as Aa,Ts as Ba,Ps as Ca,Tt as Da,Ds as Ea,Ls as Fa,sc as Ga,so as Ha,cc as Ia,lo as Ja,uc as Ka,ar as La,hc as Ma,yc as Na,xc as Oa};
|
package/dist/chunk-ML3BIPM6.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as u}from"./chunk-SJNF6JDJ.js";import{Aa as j,Ba as O,Ca as T,ya as E,za as M}from"./chunk-O4535GJR.js";import{q as w}from"./chunk-MHEYMXGZ.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};
|