@tinkerlandai/longplay-sdk 0.10.66 → 0.10.69

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.
Files changed (93) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +2 -2
  3. package/dist/check-response-754GDUOJ.js +1 -0
  4. package/dist/{chunk-O5YYORDW.js → chunk-26QYDE7V.js} +1 -1
  5. package/dist/chunk-2BSDXKQS.js +1 -0
  6. package/dist/{chunk-SAPICYY3.js → chunk-2SSOV3OG.js} +1 -1
  7. package/dist/{chunk-N5HX3K5J.js → chunk-2ZMIM4MO.js} +1 -1
  8. package/dist/{chunk-AD35L6BX.js → chunk-3NV6NBQB.js} +1 -1
  9. package/dist/{chunk-MNICOIQ6.js → chunk-44ZJPQM6.js} +1 -1
  10. package/dist/{chunk-K675GO7R.js → chunk-57ZXT7AS.js} +1 -1
  11. package/dist/chunk-5MOJUGMA.js +1 -0
  12. package/dist/{chunk-RNCUAYLQ.js → chunk-5NCQOJR2.js} +1 -1
  13. package/dist/chunk-5U7LC2NL.js +1 -0
  14. package/dist/{chunk-IGE2UMXG.js → chunk-6C3ARFEL.js} +1 -1
  15. package/dist/{chunk-A22QPPNY.js → chunk-6GY2YT3U.js} +1 -1
  16. package/dist/{chunk-C5FSL4XH.js → chunk-BGCCW5QX.js} +2 -2
  17. package/dist/{chunk-JBN6ADWQ.js → chunk-CQ5EQNQA.js} +1 -1
  18. package/dist/{chunk-PQ4ISW55.js → chunk-CWBBW6QS.js} +1 -1
  19. package/dist/{chunk-PNX7Y2K3.js → chunk-DXNTXCSI.js} +1 -1
  20. package/dist/{chunk-OKPWZZZW.js → chunk-DZYMD4MJ.js} +1 -1
  21. package/dist/{chunk-FUP5JVDE.js → chunk-ECUGL7AO.js} +1 -1
  22. package/dist/{chunk-56YCOGQZ.js → chunk-EJSTRCBQ.js} +1 -1
  23. package/dist/{chunk-47FCHF3Y.js → chunk-EQ64JD4L.js} +1 -1
  24. package/dist/chunk-F5ABUGHD.js +1 -0
  25. package/dist/{chunk-EYTP23EK.js → chunk-G3YIPDT6.js} +1 -1
  26. package/dist/{chunk-M6MXJHJ5.js → chunk-GBUGEL6M.js} +1 -1
  27. package/dist/chunk-JAH62B6J.js +1 -0
  28. package/dist/{chunk-Q523TPZM.js → chunk-JW4MSBYN.js} +1 -1
  29. package/dist/{chunk-7EENIOSJ.js → chunk-KJTHMRSH.js} +1 -1
  30. package/dist/{chunk-KVLOMX2G.js → chunk-LBYMDTGD.js} +1 -1
  31. package/dist/{chunk-7OJIW75D.js → chunk-LUVTP4VU.js} +1 -1
  32. package/dist/{chunk-7D5462NE.js → chunk-MT4OQFDI.js} +1 -1
  33. package/dist/{chunk-74T76RE4.js → chunk-NEW77IDA.js} +1 -1
  34. package/dist/{chunk-G2OLUFYT.js → chunk-NNJ7W4KY.js} +1 -1
  35. package/dist/{chunk-ZWNWVMCH.js → chunk-Q4GG33R5.js} +1 -1
  36. package/dist/{chunk-5WFI36LF.js → chunk-QTXHF27F.js} +1 -1
  37. package/dist/{chunk-DCMA7W7N.js → chunk-RMR64P6V.js} +1 -1
  38. package/dist/{chunk-E3FUZSTM.js → chunk-SGOVJD5P.js} +1 -1
  39. package/dist/{chunk-HT5SLWWG.js → chunk-ST7XO45I.js} +1 -1
  40. package/dist/{chunk-YUL23NAW.js → chunk-T5SCW4IA.js} +1 -1
  41. package/dist/{chunk-XIBJF5E6.js → chunk-TFPLIX5E.js} +1 -1
  42. package/dist/{chunk-OFG3SGEX.js → chunk-TYJWRPJY.js} +1 -1
  43. package/dist/{chunk-YA5YKHDE.js → chunk-UFTKCFNI.js} +1 -1
  44. package/dist/{chunk-RHILCVPZ.js → chunk-UIR5CBCC.js} +1 -1
  45. package/dist/{chunk-TXVLJFZG.js → chunk-ULED3B5P.js} +1 -1
  46. package/dist/{chunk-QPVA644N.js → chunk-USH4WN6W.js} +1 -1
  47. package/dist/{chunk-45MWDZ42.js → chunk-VMYLTNDS.js} +1 -1
  48. package/dist/{chunk-3Q3DZEP3.js → chunk-WVTKVQLZ.js} +1 -1
  49. package/dist/{chunk-GE6RSO2C.js → chunk-YDPF2ZZW.js} +1 -1
  50. package/dist/{chunk-46USIMCJ.js → chunk-ZRU7WONE.js} +1 -1
  51. package/dist/{content-WWME7E27.js → content-66BI72XB.js} +1 -1
  52. package/dist/{funnel-host-purchase-XIGJ7P7M.js → funnel-host-purchase-YPAWZLXP.js} +1 -1
  53. package/dist/{funnel-host-recovery-paywall-POMEY6I2.js → funnel-host-recovery-paywall-KHBGMNS5.js} +1 -1
  54. package/dist/funnel-paywall-copies-A76T5V7B.js +1 -0
  55. package/dist/funnel-paywall-prerender-PNJXR4VC.js +1 -0
  56. package/dist/funnel-route-prediction-KFUCAJLL.js +1 -0
  57. package/dist/funnel-route-source-WEYKNM2C.js +1 -0
  58. package/dist/funnel-runtime-host-RWU52BJ7.js +1 -0
  59. package/dist/index.d.ts +10 -6
  60. package/dist/index.js +1 -1
  61. package/dist/merchant-bridge-contracts-RWNJHBTR.js +1 -0
  62. package/dist/native-shell.js +1 -1
  63. package/dist/openrouter.js +1 -1
  64. package/dist/operation-contracts-NNWS467N.js +1 -0
  65. package/dist/page.js +1 -1
  66. package/dist/paywall-BSY67NQL.js +1 -0
  67. package/dist/paywall-content-RAB5S6KB.js +1 -0
  68. package/dist/paywall-session-CRIGHMOQ.js +1 -0
  69. package/dist/popup.js +1 -1
  70. package/dist/react-native.js +1 -1
  71. package/dist/screen-renderer-H3FBGJZB.js +1 -0
  72. package/dist/server.js +1 -1
  73. package/dist/visual.js +1 -1
  74. package/package.json +1 -1
  75. package/dist/check-response-WOTPYNDN.js +0 -1
  76. package/dist/chunk-7NKBMAOB.js +0 -1
  77. package/dist/chunk-MUCDKWMP.js +0 -1
  78. package/dist/chunk-MUP7FNNY.js +0 -1
  79. package/dist/chunk-OT55LG4U.js +0 -1
  80. package/dist/chunk-ZLSZBGJG.js +0 -1
  81. package/dist/funnel-paywall-copies-DUZ3YX67.js +0 -1
  82. package/dist/funnel-paywall-prerender-5NU457SR.js +0 -1
  83. package/dist/funnel-route-prediction-EW3HVH46.js +0 -1
  84. package/dist/funnel-route-source-YVFAFCVG.js +0 -1
  85. package/dist/funnel-runtime-host-J2HWW5IN.js +0 -1
  86. package/dist/merchant-bridge-contracts-PNRVNTCN.js +0 -1
  87. package/dist/operation-contracts-6ORJSGYH.js +0 -1
  88. package/dist/paywall-YRB7LQUS.js +0 -1
  89. package/dist/paywall-content-QLJIOFR3.js +0 -1
  90. package/dist/paywall-session-Q6ZYXUOU.js +0 -1
  91. package/dist/screen-renderer-P6U5UBFX.js +0 -1
  92. /package/dist/{chunk-C5FSL4XH.js.LEGAL.txt → chunk-BGCCW5QX.js.LEGAL.txt} +0 -0
  93. /package/dist/{chunk-YLH3AYCK.js → chunk-S7NHVERO.js} +0 -0
@@ -1 +1 @@
1
- import{a as T,b as se}from"./chunk-74T76RE4.js";import{b as re,h as ae,j as ce}from"./chunk-M6MXJHJ5.js";import{E as M,a as J}from"./chunk-RHILCVPZ.js";import{a as b,b as f,c as m}from"./chunk-YUL23NAW.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-SAPICYY3.js";import{a as oe,b as j}from"./chunk-E3FUZSTM.js";import{b as W,j as X}from"./chunk-FUP5JVDE.js";import{n as $}from"./chunk-AD35L6BX.js";import{b as ie}from"./chunk-7D5462NE.js";import{a as B}from"./chunk-7EENIOSJ.js";import{a as s}from"./chunk-46USIMCJ.js";import{h as Q}from"./chunk-XIBJF5E6.js";import{b as K}from"./chunk-YLH3AYCK.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-6ORJSGYH.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-6ORJSGYH.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-6ORJSGYH.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-6ORJSGYH.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};
1
+ import{a as T,b as se}from"./chunk-NEW77IDA.js";import{b as re,h as ae,j as ce}from"./chunk-GBUGEL6M.js";import{E as M,a as J}from"./chunk-UIR5CBCC.js";import{a as b,b as f,c as m}from"./chunk-T5SCW4IA.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-2SSOV3OG.js";import{a as oe,b as j}from"./chunk-SGOVJD5P.js";import{b as W,j as X}from"./chunk-ECUGL7AO.js";import{n as $}from"./chunk-3NV6NBQB.js";import{b as ie}from"./chunk-MT4OQFDI.js";import{a as B}from"./chunk-KJTHMRSH.js";import{a as s}from"./chunk-ZRU7WONE.js";import{h as Q}from"./chunk-TFPLIX5E.js";import{b as K}from"./chunk-S7NHVERO.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-NNWS467N.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-NNWS467N.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-NNWS467N.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-NNWS467N.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};
@@ -1 +1 @@
1
- import{e as p}from"./chunk-QPVA644N.js";import{c as g}from"./chunk-YUL23NAW.js";import{a as $}from"./chunk-KVLOMX2G.js";import{e as Y,f as X,g as Z,h as ee,i as re}from"./chunk-JBN6ADWQ.js";import{b as B}from"./chunk-E3FUZSTM.js";import{b as F}from"./chunk-HT5SLWWG.js";import{b as j}from"./chunk-ZWNWVMCH.js";import{A as x,B as R,E as K,z as J}from"./chunk-3Q3DZEP3.js";import{x as G}from"./chunk-5WFI36LF.js";import{b as W}from"./chunk-7D5462NE.js";import{a as M}from"./chunk-7EENIOSJ.js";import{t as H}from"./chunk-Q523TPZM.js";import{a}from"./chunk-46USIMCJ.js";import{a as z}from"./chunk-DSPLGTQI.js";function ae(I){let t=[...new Set(I.map(({path:s})=>{let c=s.map(String).join(".");return c.startsWith("selector")?"paywallId or paywallVersionId":c||"input"}))],O=t.includes("locale")?` Pass locale, the Customer's language such as "en" or "zh-CN".`:"";return new a("INVALID_REQUEST",`createPaywallSession input is invalid: ${t.join(", ")}.${O}`)}async function Ie(I,t){if(!M.test(t.customerToken))throw new a("INVALID_TOKEN","A verified Customer credential is required");if(I.session&&I.session.peek()!==t.customerToken)throw new a("SCOPE_MISMATCH","Paywall credential does not match the shared session");let O=p.resolvePaywall.request.safeParse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}});if(!O.success)throw ae(O.error.issues);let s=O.data,c=W(I);I.session||c.identify(t.customerToken);let n=null,v=!1,U=new AbortController,u=null,d=null,b=null,P=null,T=null,y=null,m=null,A=0,q=null,k="",D=0,C=new Map,E=new Set;function S(){if(v)throw new a("IDENTITY_CHANGED","Paywall is closed")}function L(){let e=JSON.stringify([A,m!==null]);if(!q||e!==k){k=e;let r=te(++D);q=r;let i=()=>{q===r&&(q=null)};r.then(i,i)}return q.then(r=>structuredClone(r))}async function te(e){S();let r=p.resolvePaywall,i=await g(c.request,r,{...s,selector:n?{type:"version",versionId:n.id}:s.selector});B(s,i.paywall.check,i.scope);let l=await F(I,i.paywall);if(S(),t.paywallVersionId?l.id!==t.paywallVersionId:l.paywallId!==t.paywallId)throw new a("INVALID_RESPONSE","The requested Paywall changed");if(n&&(!Y(l,n)||l.paywallId!==n.paywallId))throw new a("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");if(e!==D)return structuredClone(n??l);n=l;for(let h of E)z(h,structuredClone(n));return structuredClone(n)}async function Q(e){if(S(),P&&e!=="read")throw new a("COMMAND_PENDING","Wait for the original quote");if(!u)throw new a("INVALID_REQUEST","A quoted purchase is required");let r=u;if(e!=="read"){if(m){if(y===e)return m;throw new a("COMMAND_PENDING","Wait for the original purchase command")}if(y&&y!==e)throw new a("COMMAND_PENDING","Read the original purchase before changing an uncertain command");y=e,A++,D++}let i=y,l=A,h=e==="read"&&m===null,f=JSON.stringify([r.operationId,l,m!==null]);if(e==="read"&&C.has(f))return C.get(f).then(o=>structuredClone(o));let w=(async()=>{let o={operationId:r.operationId,...e==="read"?{}:{intent:e},...e==="confirm"&&r.merchantTerms?{merchantConfirmation:G(r.merchantTerms)}:{}},V=R(r)?e==="read"?await g(c.request,p.readSubscriptionUpdate,o):await g(c.request,p.update,o):e==="read"?await g(c.request,p.readSubscriptionOperation,o):await g(c.request,p.attach,o),N=x.parse(V.operation);return N.quote&&ee(r,N.quote),X(N,{operationId:r.operationId,currency:s.commerce.currency,membershipId:R(r)?r.membershipId:null,...R(r)?{featureQuantities:r.featureQuantities??{}}:{}},"The purchase operation changed"),S(),u?.operationId!==r.operationId?structuredClone(N):(d=re(d,N),(e!=="read"||h&&m===null)&&A===l&&y===i&&(y=null),structuredClone(d))})();if(e!=="read"){m=w;let o=()=>{m===w&&(m=null)};w.then(o,o)}else{C.set(f,w);let o=()=>{C.get(f)===w&&C.delete(f)};w.then(o,o)}return w.then(o=>structuredClone(o))}let _={signal:U.signal,get view(){return n?structuredClone(n):null},get quote(){return u?structuredClone(u):null},get operation(){return d?structuredClone(d):null},get webViewUrl(){return"bundled"},get locale(){return s.locale},get recovery(){return $({quote:u,operation:d,requestId:T,pending:P!==null||y!==null,destroyed:v})},get pendingCancellation(){return!v&&y==="cancel"},refresh:L,subscribe(e){return v?()=>{}:(E.add(e),()=>E.delete(e))},async preview(e){if(S(),!n)throw new a("INVALID_REQUEST","Load the Paywall first");let r=n.document.buttons[e.actionId];if(r?.type!=="checkout")throw new a("INVALID_REQUEST","Choose an authored purchase action");let i=j(r.product,e.selection,n.capabilities);if(!i)throw new a("PRODUCT_UNAVAILABLE","Choose an available Product");let l=H(n.document.screen,i,e.selection,n.capabilities);if(s.commerce.intent==="subscription_change"&&!e.subscriptionChange)throw new a("INVALID_REQUEST","Choose the existing membership for this subscription change");if(e.subscriptionChange&&e.nativeOffer)throw new a("INVALID_REQUEST","A web membership change cannot include a store offer");let h=e.subscriptionChange?p.previewUpdate.request.parse({requestId:e.requestId,...e.subscriptionChange,change:{type:"plan",productVersionId:i,...Object.keys(l).length?{featureQuantities:l}:{}},...e.offerId?{offerId:e.offerId}:{}}):p.previewAttach.request.parse({funnelId:s.funnelId,funnelVersionId:s.funnelVersionId,requestId:e.requestId,plans:[{productVersionId:i,...Object.keys(l).length?{featureQuantities:l}:{}}],provider:s.commerce.provider,currency:s.commerce.currency,...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{}}),f=JSON.stringify(h);if(b&&b!==f&&(P||y||!d||K(d)))throw new a("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(b===f){if(P)return P;if(u)return structuredClone(u)}b!==f&&(u=null,d=null),b=f,T=h.requestId;let w=(async()=>{let o="membershipId"in h?await g(c.request,p.previewUpdate,h):await g(c.request,p.previewAttach,h),V=J.parse(o.quote);return S(),Z(V,{productVersionId:i,featureQuantities:l,currency:s.commerce.currency,provider:s.commerce.provider,subscriptionChange:e.subscriptionChange},"The purchase quote changed its selected Product or presentment"),u=V,d=null,structuredClone(u)})();P=w;try{return await w}finally{P===w&&(P=null)}},confirm:()=>Q("confirm"),cancel:()=>Q("cancel"),read:()=>Q("read"),destroy(){v||(v=!0,U.abort(),E.clear(),C.clear(),ne?.(),c.dispose(),n=null,u=null,d=null,b=null,T=null)}},ne=I.session?.subscribeIdentity(_.destroy);try{return await L(),_}catch(e){throw _.destroy(),e}}export{Ie as a};
1
+ import{e as p}from"./chunk-USH4WN6W.js";import{c as g}from"./chunk-T5SCW4IA.js";import{a as $}from"./chunk-LBYMDTGD.js";import{e as Y,f as X,g as Z,h as ee,i as re}from"./chunk-CQ5EQNQA.js";import{b as B}from"./chunk-SGOVJD5P.js";import{b as F}from"./chunk-ST7XO45I.js";import{b as j}from"./chunk-Q4GG33R5.js";import{A as x,B as R,E as K,z as J}from"./chunk-WVTKVQLZ.js";import{x as G}from"./chunk-QTXHF27F.js";import{b as W}from"./chunk-MT4OQFDI.js";import{a as M}from"./chunk-KJTHMRSH.js";import{t as H}from"./chunk-JW4MSBYN.js";import{a}from"./chunk-ZRU7WONE.js";import{a as z}from"./chunk-DSPLGTQI.js";function ae(I){let t=[...new Set(I.map(({path:s})=>{let c=s.map(String).join(".");return c.startsWith("selector")?"paywallId or paywallVersionId":c||"input"}))],O=t.includes("locale")?` Pass locale, the Customer's language such as "en" or "zh-CN".`:"";return new a("INVALID_REQUEST",`createPaywallSession input is invalid: ${t.join(", ")}.${O}`)}async function Ie(I,t){if(!M.test(t.customerToken))throw new a("INVALID_TOKEN","A verified Customer credential is required");if(I.session&&I.session.peek()!==t.customerToken)throw new a("SCOPE_MISMATCH","Paywall credential does not match the shared session");let O=p.resolvePaywall.request.safeParse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}});if(!O.success)throw ae(O.error.issues);let s=O.data,c=W(I);I.session||c.identify(t.customerToken);let n=null,v=!1,U=new AbortController,u=null,d=null,b=null,P=null,T=null,y=null,m=null,A=0,q=null,k="",D=0,C=new Map,E=new Set;function S(){if(v)throw new a("IDENTITY_CHANGED","Paywall is closed")}function L(){let e=JSON.stringify([A,m!==null]);if(!q||e!==k){k=e;let r=te(++D);q=r;let i=()=>{q===r&&(q=null)};r.then(i,i)}return q.then(r=>structuredClone(r))}async function te(e){S();let r=p.resolvePaywall,i=await g(c.request,r,{...s,selector:n?{type:"version",versionId:n.id}:s.selector});B(s,i.paywall.check,i.scope);let l=await F(I,i.paywall);if(S(),t.paywallVersionId?l.id!==t.paywallVersionId:l.paywallId!==t.paywallId)throw new a("INVALID_RESPONSE","The requested Paywall changed");if(n&&(!Y(l,n)||l.paywallId!==n.paywallId))throw new a("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");if(e!==D)return structuredClone(n??l);n=l;for(let h of E)z(h,structuredClone(n));return structuredClone(n)}async function Q(e){if(S(),P&&e!=="read")throw new a("COMMAND_PENDING","Wait for the original quote");if(!u)throw new a("INVALID_REQUEST","A quoted purchase is required");let r=u;if(e!=="read"){if(m){if(y===e)return m;throw new a("COMMAND_PENDING","Wait for the original purchase command")}if(y&&y!==e)throw new a("COMMAND_PENDING","Read the original purchase before changing an uncertain command");y=e,A++,D++}let i=y,l=A,h=e==="read"&&m===null,f=JSON.stringify([r.operationId,l,m!==null]);if(e==="read"&&C.has(f))return C.get(f).then(o=>structuredClone(o));let w=(async()=>{let o={operationId:r.operationId,...e==="read"?{}:{intent:e},...e==="confirm"&&r.merchantTerms?{merchantConfirmation:G(r.merchantTerms)}:{}},V=R(r)?e==="read"?await g(c.request,p.readSubscriptionUpdate,o):await g(c.request,p.update,o):e==="read"?await g(c.request,p.readSubscriptionOperation,o):await g(c.request,p.attach,o),N=x.parse(V.operation);return N.quote&&ee(r,N.quote),X(N,{operationId:r.operationId,currency:s.commerce.currency,membershipId:R(r)?r.membershipId:null,...R(r)?{featureQuantities:r.featureQuantities??{}}:{}},"The purchase operation changed"),S(),u?.operationId!==r.operationId?structuredClone(N):(d=re(d,N),(e!=="read"||h&&m===null)&&A===l&&y===i&&(y=null),structuredClone(d))})();if(e!=="read"){m=w;let o=()=>{m===w&&(m=null)};w.then(o,o)}else{C.set(f,w);let o=()=>{C.get(f)===w&&C.delete(f)};w.then(o,o)}return w.then(o=>structuredClone(o))}let _={signal:U.signal,get view(){return n?structuredClone(n):null},get quote(){return u?structuredClone(u):null},get operation(){return d?structuredClone(d):null},get webViewUrl(){return"bundled"},get locale(){return s.locale},get recovery(){return $({quote:u,operation:d,requestId:T,pending:P!==null||y!==null,destroyed:v})},get pendingCancellation(){return!v&&y==="cancel"},refresh:L,subscribe(e){return v?()=>{}:(E.add(e),()=>E.delete(e))},async preview(e){if(S(),!n)throw new a("INVALID_REQUEST","Load the Paywall first");let r=n.document.buttons[e.actionId];if(r?.type!=="checkout")throw new a("INVALID_REQUEST","Choose an authored purchase action");let i=j(r.product,e.selection,n.capabilities);if(!i)throw new a("PRODUCT_UNAVAILABLE","Choose an available Product");let l=H(n.document.screen,i,e.selection,n.capabilities);if(s.commerce.intent==="subscription_change"&&!e.subscriptionChange)throw new a("INVALID_REQUEST","Choose the existing membership for this subscription change");if(e.subscriptionChange&&e.nativeOffer)throw new a("INVALID_REQUEST","A web membership change cannot include a store offer");let h=e.subscriptionChange?p.previewUpdate.request.parse({requestId:e.requestId,...e.subscriptionChange,change:{type:"plan",productVersionId:i,...Object.keys(l).length?{featureQuantities:l}:{}},...e.offerId?{offerId:e.offerId}:{}}):p.previewAttach.request.parse({funnelId:s.funnelId,funnelVersionId:s.funnelVersionId,requestId:e.requestId,plans:[{productVersionId:i,...Object.keys(l).length?{featureQuantities:l}:{}}],provider:s.commerce.provider,currency:s.commerce.currency,...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{}}),f=JSON.stringify(h);if(b&&b!==f&&(P||y||!d||K(d)))throw new a("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(b===f){if(P)return P;if(u)return structuredClone(u)}b!==f&&(u=null,d=null),b=f,T=h.requestId;let w=(async()=>{let o="membershipId"in h?await g(c.request,p.previewUpdate,h):await g(c.request,p.previewAttach,h),V=J.parse(o.quote);return S(),Z(V,{productVersionId:i,featureQuantities:l,currency:s.commerce.currency,provider:s.commerce.provider,subscriptionChange:e.subscriptionChange},"The purchase quote changed its selected Product or presentment"),u=V,d=null,structuredClone(u)})();P=w;try{return await w}finally{P===w&&(P=null)}},confirm:()=>Q("confirm"),cancel:()=>Q("cancel"),read:()=>Q("read"),destroy(){v||(v=!0,U.abort(),E.clear(),C.clear(),ne?.(),c.dispose(),n=null,u=null,d=null,b=null,T=null)}},ne=I.session?.subscribeIdentity(_.destroy);try{return await L(),_}catch(e){throw _.destroy(),e}}export{Ie as a};
@@ -1 +1 @@
1
- import{a as tn}from"./chunk-47FCHF3Y.js";import{b as rn}from"./chunk-KVLOMX2G.js";import{b as nn}from"./chunk-HT5SLWWG.js";import{d as We,e as ce}from"./chunk-TXVLJFZG.js";import{c as qe,d as je,e as K,l as Ze}from"./chunk-FUP5JVDE.js";import{A as Je,F as He,G as Qe,H as z,I as Ye,J as le,K as G,a as Me,c as Y,g as Z,h as Ge,i as Ue,m as $e}from"./chunk-AD35L6BX.js";import{A as ie,B as ae,z as oe}from"./chunk-3Q3DZEP3.js";import{a as de,b as Xe}from"./chunk-PNX7Y2K3.js";import{a as j,b as _e,c as ke,e as De,h as Ve,i as Le,l as Be}from"./chunk-MNICOIQ6.js";import{b as W}from"./chunk-7D5462NE.js";import{a as Q}from"./chunk-7EENIOSJ.js";import{m as Ke,n as ue,o as ze,p as se}from"./chunk-Q523TPZM.js";import{g as Ee,m as Ce,w as re}from"./chunk-56YCOGQZ.js";import{b as Pe,d as L,e as Ae,f as Te}from"./chunk-7OJIW75D.js";import{a as m}from"./chunk-46USIMCJ.js";import{h as V}from"./chunk-XIBJF5E6.js";import{a as en}from"./chunk-5MRSFLQA.js";import{b as n}from"./chunk-YLH3AYCK.js";import{a as on}from"./chunk-DSPLGTQI.js";import{c as Ne,f as Oe}from"./chunk-VPT5MFDG.js";function an(e){return Fn({...e,namespace:"commands",identity:[e.runToken]})}function Fn(e){let t,u,r=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),o=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let c=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??en).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",c));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,i=>i.toString(16).padStart(2,"0")).join("")});o.catch(()=>{});async function p(c){try{let a=await o;return await u.request(a,{mode:"exclusive"},()=>c(a))}catch(a){throw a instanceof m?a:r()}}function d(c){let a=t.getItem(c);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let i=JSON.parse(a);if(!i||typeof i!="object"||!("revision"in i)||!("entry"in i)||!Number.isSafeInteger(i.revision)||Number(i.revision)<0)throw r();return{revision:Number(i.revision),entry:i.entry}}return{read:()=>p(d),write:(c,a)=>p(i=>{if(d(i).revision!==c)return null;if(!Number.isSafeInteger(c+1))throw r();let y=JSON.stringify({revision:c+1,entry:a});if(y.length>1048576)throw r();return t.setItem(i,y),c+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var M=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),En=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Cn=n.discriminatedUnion("type",[$e,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:M.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:He,openIn:Qe}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:M})]),Pn={id:M,presentation:Pe,outputs:n.array(M).max(250),inputs:se,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Ee,customerData:Ce,dataCursors:n.record(M,Ke.nullable())},Nn=n.strictObject({...Pn,content:n.strictObject({type:n.literal("document"),document:re})}),pe=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:M,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:En,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:ue,parameters:ze,variables:n.record(n.string(),L),output:L.nullable(),screen:Nn.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([We,ce]),quote:oe.nullable(),operation:ie.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Cn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),On=n.strictObject({scope:V,run:pe,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:oe.nullable(),operation:ie.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative(),document:re,answers:ue,inputs:se,values:n.record(n.string(),L).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),sn=On.extend({run:pe.extend({paywall:pe.shape.paywall.unwrap().extend({resolution:ce}).nullable()})});var ln="X-Indiana-Server-Key";var An=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),Tn=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(An).max(200).default([]),iam:Ge.optional(),renderGuard:Z.optional()}),me=Tn.omit({variation:!0,description:!0,iam:!0}),_n=qe.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([me,me]).rest(me).refine(e=>e.length<=20)}),cn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(_n).max(100),savedGroups:je});var $=n.string().regex(/^[a-f0-9]{64}$/),Tt=n.strictObject({iam:$,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),kn=n.strictObject({release:$,render:Z,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),_t=n.strictObject({scope:V.extend({environmentId:n.uuid()}),release:$,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),delivery:Ue.optional(),target:kn})).max(4e3)}),kt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:$,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Dt=n.strictObject({scope:V,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Vt=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Dn=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),fe=n.strictObject({operation:n.literal("page_experiments"),release:$,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(Q).optional()}),dn=n.strictObject({scope:V,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:cn});var U=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),mn=n.strictObject({entry:U,nodes:n.array(n.strictObject({id:U,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),U),writes:n.record(j,j),resources:n.strictObject({screenId:U.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),pn={scope:V,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:mn},X=n.discriminatedUnion("evaluationMode",[n.strictObject({...pn,evaluationMode:n.literal("local"),growth:K,conditions:n.record(U,n.array(n.strictObject({condition:Te,port:n.string()})))}),n.strictObject({...pn,evaluationMode:n.literal("remote")})]),Vn=X.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,ke),outputSchema:_e,terminals:n.record(U,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Je.nullable()}))})});function Ln(e){return mn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(d=>d.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,d)=>{u[`case:${d}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let o=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return o?.type==="feature"&&(r.featureKey=o.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ge(e){let t=le.parse(e.document),u=e.evaluationMode==="local"?K.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:Ln(t)};return X.parse(e.evaluationMode==="remote"?r:{...r,growth:Ze(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(o=>o.type==="condition").map(o=>[o.id,o.cases.map((p,d)=>({condition:p.condition,port:`case:${d}`}))]))})}function $t(e){let t=ge(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=le.parse(e.document);return Vn.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let o=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:o&&o.type!=="literal"&&o.type!=="feature"&&o.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:o??null}]]}))}})}var Ie=32,Mn=522240;function ve(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var qn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),ye=n.record(n.string(),L),jn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:z.shape.schemaVersion,kind:z.shape.kind,selector:z.shape.selector,contract:z.shape.contract}),context:ye,removed:n.array(n.string()).max(100),attributes:ye,removedAttributes:n.array(n.string()).max(100),result:Ye,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),Wt=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:qn,context:ye,steps:n.array(jn).min(1).max(Ie)}).refine(e=>Y(e)<=Mn,"Segment exceeds its byte budget");var Gn=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function J(e){return Array.isArray(e)?e.some(J):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&J(u):!Gn.test(t))}function fn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(c=>c.id===t.screenId&&c.type==="paywall")))return"customer_required";let o=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(o&&["bundle","selection","offering"].includes(o.type)||t.type==="condition"&&t.cases.some(c=>J(c.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(c=>c.id===t.screenId):null]);for(let[c,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${c}`)||p.includes(JSON.stringify(c))))return"customer_required";if(t.type==="split"){let c=u.experiments?.[t.experimentId];if((c?.hashAttribute??"id")!=="funnelParticipantId"||J(c?.condition)||c?.parentConditions?.length)return"customer_experiment_required"}let d=t.type==="feature"?t.featureKey:o?.type==="feature"?o.featureKey:void 0;return d&&u.features?.[d]?.rules?.some(c=>(c.hashAttribute??"id")!=="funnelParticipantId"||J(c.condition)||c.parentConditions?.length)?"customer_experiment_required":null}var he=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},ee=(e,t)=>new he(e,t),Un=e=>({experiments:e.experiments,features:e.features});function we(e,t=ee){let u=new Map(e.topology.nodes.map(d=>[d.id,d])),r=Ne(e.growth.savedGroups),o=Un(e.growth);function p(d,c){if(!Object.hasOwn(e.growth.features,d))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Oe(d,c).value}return{nodes:u,savedGroups:r,features:o.features,feature:p,evaluate(d,c){let a=u.get(d);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let i,g;if(a.type==="condition"){let v=e.conditions[a.id];if(!v)throw t("INVALID_RESPONSE","Local condition rules are unavailable");i=de({id:a.id,name:a.id,type:"condition",cases:v.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},c,o.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,c),i="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=de({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},c,o.experiments);g=h.value,i=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,c),i=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[i]??(i==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:d,port:i,target:y,...g===void 0?{}:{value:g}}}}}function dr(e,t,u,r=ee){return be(e,r)(t,u)}function be(e,t){let u=X.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,o=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};o();let p=we(u,t);return(d,c)=>(o(),Bn(p,d,c))}function Bn(e,t,u){let r=Ae.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:o,onFeatureUsage:p,onExperimentViewed:d}=u,c={attributes:r,...o?{saveStickyBucketAssignmentDoc:a=>o(structuredClone(a))}:{},...p?{onFeatureUsage:(a,i)=>p(a,structuredClone(i))}:{},...d?{onExperimentViewed:(a,i)=>d(structuredClone(a),structuredClone(i))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,c)}function pr(e,t,u,r=ee){return gn(be(e,r),t,u)}function gn(e,t,u){let r=[],o=[],p=[],d=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(c){let a=r.findIndex(y=>y.next.attributeName===c.attributeName&&y.next.attributeValue===c.attributeValue),i=c.attributeName+"||"+c.attributeValue,g={expected:u.sticky[i]??null,next:c};a<0?r.push(g):r[a]=g},onExperimentViewed(c,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&o.push(L.parse({key:c.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(c,a){p.push(L.parse({feature:c,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:d.port,...d.value===void 0?{}:{value:d.value},sticky:r,exposures:o,features:p}}function yn(e,t,u,r=ee){let o=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),d=structuredClone(u.variables),c=structuredClone(o.sticky),a=[],i=u.nodeId,g=u.visit,y=!1,v,h=O=>fn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},o.attributes.funnelCustomerBound===!0),R=O=>(v??=be(e,r),gn(v,O,{attributes:Be({declarations:t.variables,attributes:o.attributes,parameters:u.parameters,answers:u.answers,results:d,savedGroups:{}}),sticky:c}));for(let O=0;O<Ie;O++){let s=p.get(i);if(!s||!ve(s)||h(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let f,w;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")f=R(s.id),s.type==="offering"&&(f.value={type:"offering_version",id:String(f.value)}),s.type==="condition"?w=f.port==="default"?s.default:s.cases[Number(f.port.slice(5))]?.target:s.type==="split"?w=f.port==="notParticipating"?s.notParticipating:s.routes[f.port]:(s.type==="feature"||s.type==="offering")&&(w=s.next);else if(f={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(w=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(f.value={type:"offering_version",id:s.configuration.versionId},w=s.next),s.type==="end"||s.type==="output"){let x=s.type==="end"?s.output:s.value;if(f=x?.type==="feature"?R(s.id):{...f,port:"value",value:x?.type==="literal"?x.value:x?.type==="variable"?Me({source:"variable",key:x.key,...x.path?{path:x.path}:{}},{declarations:t.variables,answers:u.answers,results:d,parameters:u.parameters,attributes:o.attributes,savedGroups:{}}):null},x&&(f.value===void 0||!De(t.outputSchema,f.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let N=[...a,{nodeId:i,result:f}];if(Y({steps:N})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:i,result:f}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let x=s.type==="coupons"?s.couponIds.map(D=>({type:"reward",id:D})):s.type==="coupon"?{type:"reward",id:s.couponId}:f.value;if(x===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=Ve(s,{value:x});Le(t.variables,s,_),Object.assign(d,_)}for(let x of f.sticky)c[`${x.next.attributeName}||${x.next.attributeValue}`]=structuredClone(x.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!w)throw r("INVALID_RESPONSE","Local pure exit is unavailable");i=w,g++}let T=p.get(i);return{steps:a,...!y&&T&&(!ve(T)||h(T))?{boundary:{nodeId:i,visit:g}}:{}}}function In(e,t){let u=sn.safeParse(t);if(!u.success)throw new m("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Funnel scope changed");return r}var xe=(e,t)=>new m(e,t);function hr(e){return we(e,xe)}var Kn=3,zn=2e3;function $n(e){return e instanceof TypeError||e instanceof m&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Jn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Kn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*zn))}}async function Re(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let o=null,p;if(u)try{let d=await e.funnel(t.source.id,t.source.versionId);p=d.manifest.generation,o=Hn(e,t,d)}catch{o=null}return p??=e.snapshot?.generation??(await Jn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:o}}function Hn(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:o,remoteFeatures:p,...d}=u.growth,c=ge({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:K.parse(d)}),a=Qn(c,u.document,{...t,...r}),i=a.steps.at(-1),g=a.boundary??(i?.result.port==="value"?{nodeId:i.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Qn(e,t,u){return yn(e,t,u,xe)}var vn=G.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 m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),hn=n.strictObject({schemaVersion:n.literal(1),scope:V,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:vn.optional(),closeCommand:vn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.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"),A=()=>new m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),ne=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function H(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function wn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),o=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:hn.parse(a.entry)}}function d(a){let i=o.then(a);return o=i.catch(()=>{}),i}async function c(a){for(let i=0;i<4;i++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(ne(g.entry,y)){t=g.revision;return}let v=await e.write(g.revision,y);if(v!==null){if(!Number.isSafeInteger(v)||v<=g.revision)throw A();t=v;return}}throw A()}return{bind(a){let i=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==i)throw A();u=i},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let i=hn.parse(a),g=i.command;return!g||u!==null&&r(i)!==u?Promise.reject(A()):(u??=r(i),d(()=>c((y,v)=>{if(y&&!ne(r(y),r(i)))throw A();if(y&&i.processBindingIds){for(let[h,R]of Object.entries(i.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==R)throw A();y={...y,processBindingIds:{...y.processBindingIds,...i.processBindingIds}}}if(!y){if(v!==t&&g.operation!=="close")throw A();return i}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!ne(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!ne(y.command,g))throw A();return y})))},observePurchase(a,i,g,y){return d(()=>c((v,h)=>{if(!v&&h!==t||v&&r(v)!==r({...a,schemaVersion:1}))throw A();if(v?.purchase&&v.purchase.generation>i.generation)return H(v,y);if(v?.purchase&&v.purchase.generation===i.generation&&v.purchase.operationId!==i.operationId)throw A();return g?!v?.purchase||v.purchase.operationId!==i.operationId?H(v,y):H(v.command?{...v,purchase:void 0}:null,y):H({schemaVersion:1,...a,...v,purchase:i},y)}))},settle(a){return d(()=>c(i=>H(i,a)))}}}function Tr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function te(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((o,p)=>te(o,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([o,p])=>Object.hasOwn(t,o)&&te(p,Reflect.get(t,o)))}function bn(e,t){let u=t&&{...t},r=null,o=0,p=-1,d=0,c=new AbortController;function a(){d++,c.abort(new m("IDENTITY_CHANGED","Run identity changed")),c=new AbortController}let i=!1,g,y=0,v=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new m("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===d?r:null},get viewAgeMs(){return r&&p===d?performance.now()-o:void 0},get generation(){return d},get signal(){return c.signal},get disposed(){return i},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,R="Run identity changed during the request"){if(h!==d||i)throw new m("IDENTITY_CHANGED",R)},assertRun(h){if(r&&(h.id!==r.id||h.source.type!==r.source.type||h.source.id!==r.source.id||h.source.versionId!==r.source.versionId||h.locale!==r.locale||!te(h.parameters,r.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,R,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&R.run.revision<=r.revision)&&!(r&&R.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!R.run.stopped&&["running","waiting"].includes(R.run.status)&&r&&p===d&&R.run.nodeId===r.nodeId&&R.run.visit===r.visit&&R.run.revision===r.revision&&(R.run.screen=r.screen,(r.paywall?.quote?.operationId===R.review?.activeOperationId||!r.paywall?.quote&&R.review?.activeOperationId===null)&&(R.run.paywall=r.paywall)),!(r?.paywall&&R.run.paywall&&r.paywall.receiptId===R.run.paywall.receiptId&&(R.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||R.run.revision>=r.revision)r=R.run,o=performance.now(),p=d;else if(!s)return;if(r&&p===d)for(let f of v)try{f(structuredClone(r))}catch{}}},identify(h){if(i)throw new m("IDENTITY_CHANGED","Controller was reset");if(!Q.test(h))throw new m("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return v.add(h),()=>v.delete(h)},reset(){i||(i=!0,a(),g=void 0,r=null,v.clear())}}}var Se=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function qr(e,t,u="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",t);if(!Se.test(e))throw new m("INVALID_TOKEN",u)}function jr(e){let t=W(e);return t.identify(e.apiKey),t}function xn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&!ae(t)&&["apple","google"].includes(t.provider)?"native":t&&!ae(t)&&t.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new m("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function q(e){let{customerToken:t,...u}=e;return u}var Yn=e=>!(e instanceof m&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Rn({journal:e,state:t,call:u,processIdentity:r}){let o=null,p=null,d=!1,c={command:null,close:null},a=new Set,i,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(w=>w&&!Object.hasOwn(s.processBindingIds??{},w.requestId)))throw new m("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new m("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=s.purchase,d=s.closed===!0,!s.command)return;let f=s.command;o=f.operation==="close"?null:f,p=f.operation==="close"?f:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(d=!0);for(let w of[o,p])w&&a.add(w.requestId)}):Promise.resolve();y.catch(()=>{});async function v(s,f){e&&await y;let w=t.generation;if(e){if(!t.view||!t.scope)throw new m("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:q(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(w!==t.generation||o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");if(e&&on(f),t.assertCurrent(w),o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let N=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(x){let _=s.operation==="submit"&&s.input.type==="paywall_quote",D=!N&&!Yn(x),l=!1;if(_&&D&&w===t.generation&&o===s&&x instanceof m&&x.status!==void 0){let I=await T(s.requestId).catch(()=>{});l=I?.settlement?.state==="unknown"&&I.settlement.operationId===null}throw w===t.generation&&(o===s||p===s)&&D&&(!_||!(x instanceof m)||x.status===void 0||l)&&(e&&await e.settle(s.requestId),w===t.generation&&O(s)),x}}function h(s,f){let w=G.parse(s);if(w.operation==="start"||w.operation==="get"||w.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(d&&w.operation!=="close"){if(o?.requestId===w.requestId)return T(w.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(w.operation==="close"){if(o?.requestId===w.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(d=!0,p&&JSON.stringify(q(p))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original Close");return p??=w,c.close?c.close:R(p,"close",f)}if(o){if(JSON.stringify(q(o))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(c.command)return c.command}else o=w;return R(o,"command",f)}function R(s,f,w){let N=v(s,w);c[f]=N;let x=()=>{c[f]===N&&(c[f]=null)};return N.then(x,x),N}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||o!==s&&p!==s?!1:(o===s&&(o=null),p===s&&(p=null),a.delete(s.requestId),!o&&!p&&(g=null),!0)}return{ready:y,get pending(){return o},get closing(){return p},get closeRequested(){return d},get inFlight(){return c.command},get closeFlight(){return c.close},get purchase(){return i},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,f,w,N){let x=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=x&&f.settlement?.state==="settled"&&f.run.pendingRequest?.requestId!==x&&(s.operation==="get"||!d||s.operation==="close"||!["running","waiting"].includes(f.run.status))?x:void 0,D=o?.requestId===_?o:p?.requestId===_?p:void 0;e?.bind({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId});let l=f.run.paywall,I=l??f.purchase,C=I?.operation,E=f.settlement&&(!l||l.purchaseRequestId===f.settlement.requestId)&&(!i||i.operationId===f.settlement.operationId)?f.settlement:void 0,S=C?.operationId??I?.quote?.operationId??E?.operationId,F=I?.receiptId??E?.receiptId,b=l?.selectionGeneration??i?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||f.run.revision>=t.view.revision)&&(N===void 0||N>=t.readSequence)&&(!i||b>=i.generation)){let P={receiptId:F,operationId:S,generation:b},k=rn(C,I?.canReselect===!0);await e.observePurchase({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId},P,k,_),t.assertCurrent(w),(!i||P.generation>=i.generation)&&(N===void 0||N>=t.readSequence)&&(k?i?.operationId===P.operationId&&(i=void 0):i=P)}else e&&_&&await e.settle(_);return t.assertCurrent(w),_?O(D):!1},stop(){d=!0},submit:h,settle:T,reset(){d=!0,o=null,p=null,i=void 0,g=null,c.close=null,a.clear(),c.command=null}}}function Zn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new m("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new m("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Se.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=W({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),o=bn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(R),d=null,c=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=c&&wn(c),i=Rn({journal:a,state:o,call:T,processIdentity:e.process}),g=0,y=new Map;function v(){g++,y.clear(),t=void 0}async function h(l){let I=l.operation==="resume"?i.pending?.operation==="resume"?null:i.pending:l;if(u&&l.operation==="resume"&&!I&&l.requestId!==e.customerRun?.startRequestId)throw new m("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(I?.operation==="submit"&&I.input.type==="paywall_confirm"){let P=o.view?.paywall;xn(u,P?.quote?.operationId===I.input.operationId?P.quote:void 0)}if(e.process)return e.process.request(l);let C=o.generation;o.assertCurrent(C);let E=performance.now()+(e.timeoutMs??35e3),S=o.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let P=o.signal,k,B=()=>{},Sn=new Promise((Wn,Fe)=>{B=()=>Fe(P.reason),P.addEventListener("abort",B,{once:!0}),k=setTimeout(()=>Fe(new m("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(o.assertCurrent(C),e.session.access())),Sn])}finally{clearTimeout(k),P.removeEventListener("abort",B)}}o.assertCurrent(C);let F={...l,...S?{customerToken:S}:{}},b=l.operation==="page_experiments"?fe.parse(F):G.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new m("IDENTITY_CHANGED","Original recovery Customer changed");let P={...b};return"customerToken"in P&&delete P.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:P},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",b,e.runToken,{headers:e.serverKey&&!S?{[ln]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function R(){v(),p?.(),o.reset(),i.reset(),d=null,r.dispose()}async function T(l,I){let C=t;t=void 0;let E=o.generation,S=()=>o.assertCurrent(E);a&&await i.ready,S();let F=o.view,b=In(e,C!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?C:await h(l));if(l.operation==="review"&&!b.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&b.run.id!==e.customerRun.runId)throw new m("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&b.purchase&&(b.purchase.receiptId!==l.purchase.receiptId||(b.purchase.operation?.operationId??b.purchase.quote?.operationId)!==l.purchase.operationId))throw new m("INVALID_RESPONSE","The requested original purchase changed");if(S(),b.runToken&&b.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let P=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(P&&b.settlement?.requestId!==P)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");i.assertBinding(b),o.assertRun(b.run),o.bindScope(b.scope);let k=await i.observe(l,b,E,I);return(!o.view||b.run.revision>=o.view.revision)&&(I===void 0||I>=o.readSequence)&&(await e.onAcceptedResponse?.(b),S()),!b.run.stopped&&["running","waiting"].includes(b.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(b.run.status)||i.stop(),o.publish(l,b,F,I,k)),b}function O(l){let I=o.generation;v();let C=l(),E=()=>{o.generation===I&&v()};return C.then(E,E),C}let s=(l,I)=>O(()=>i.submit(l,I)),f=null,w=new WeakMap;function N(l){let I=w.get(l);if(I)return I;let C=_(l);return w.set(l,C),C}let x=!1;async function _(l){let I=await l;if(I.run.instruction?.type!=="evaluate_segment")return I;if(f)return f;x=!0;let C=o.generation,E=(async()=>{for(let S=0;S<32&&I.run.instruction?.type==="evaluate_segment";S++){if(i.pending||i.closeRequested)return I;let F=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:P}=await Re(e.configuration,F,{predict:!1});if(C!==o.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(i.pending||i.closeRequested)return I;if(o.view&&(o.view.revision!==F.revision||o.view.visit!==F.visit||o.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Re(e.configuration,F).then(({prediction:B})=>{k&&C===o.generation&&!i.closeRequested&&o.view?.id===F.id&&!o.view.stopped&&o.view.nodeId===F.nodeId&&o.view.visit===F.visit&&o.view.revision===F.revision&&(d=B)}).catch(()=>{});try{I=await s({operation:"commit_segment",requestId:Xe(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...P})}finally{k=!1,d=null}}}return I})();f=E;try{return await E}finally{f===E&&(f=null)}}let D={get configuration(){return x?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=o.currentView;return l?structuredClone(l):null},get viewAgeMs(){return o.viewAgeMs},get pendingCommand(){let l=i.closing??i.pending;return l?structuredClone(q(l)):null},get pendingCommands(){return[i.pending,i.closing].filter(l=>l!==null).map(l=>structuredClone(q(l)))},get pendingPurchase(){return i.purchase?structuredClone(i.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=o.view;return d&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===d.runId&&l.nodeId===d.from.nodeId&&l.visit===d.from.visit&&l.revision===d.from.revision&&!i.closeRequested?structuredClone(d):null},settle:(...l)=>O(()=>i.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return nn(e,l)},async pageExperiments(l,I=[]){let C=o.generation;o.assertCurrent(C);let E=o.view?.id;if(!E)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let S=dn.parse(await h(fe.parse({operation:"page_experiments",release:l,usedReceiptIds:I})));if(o.assertCurrent(C),S.runId!==E||S.scope.projectId!==o.scope?.projectId||S.scope.environment!==o.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},o.nextRead())},async get(l,I){let C=o.generation;l=l&&structuredClone(l),I=I&&{...I},a&&await i.ready,o.assertCurrent(C),I??=i.purchase&&{receiptId:i.purchase.receiptId,operationId:i.purchase.operationId};let E=JSON.stringify([o.generation,g,l??null,I??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=o.nextRead(),b=N(T({operation:"get",...l?{data:l}:{},...I?{purchase:I}:{}},F));y.set(E,b);let P=()=>{y.get(E)===b&&y.delete(E)};return b.then(P,P),b.then(k=>structuredClone(k))},resume(l=o.view?.pendingRequest?.requestId){return l?i.closeRequested?D.settle(l):i.pending?.requestId===l?N(s(i.pending)):N(s({operation:"resume",requestId:l})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(l){return N(s(l))},async retry(){if(i.closeFlight)return i.closeFlight;if(i.closing)return s(i.closing);if(i.closeRequested&&i.pending)return D.settle(i.pending.requestId);if(i.inFlight)return N(i.inFlight);if(!i.pending)throw new m("INVALID_REQUEST","No command is pending");let l=i.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let I=o.generation;if(await D.settle(l.requestId),o.assertCurrent(I),!i.pending)return D.get();if(i.pending!==l||i.closeRequested)throw new m("COMMAND_PENDING","The original quote is being recovered")}return N(s(l))},identify(l){let I=o.customerToken?void 0:t;v(),o.identify(l),t=I,d=null,r.reset()},get identitySignal(){return o.signal},subscribe:o.subscribe,reset:R};return tn(D,(l,I)=>N(s(l,I))),D}function po(e,t){return Zn({...e,runToken:"",initialResponse:t})}export{un as a,Cn as b,pe as c,On as d,sn as e,kn as f,_t as g,kt as h,Dt as i,fe as j,dn as k,X as l,Vn as m,$t as n,dr as o,pr as p,In as q,xe as r,hr as s,Qn as t,hn as u,H as v,an as w,Fn as x,Tr as y,te as z,Se as A,qr as B,jr as C,xn as D,Zn as E,po as F};
1
+ import{a as tn}from"./chunk-EQ64JD4L.js";import{b as rn}from"./chunk-LBYMDTGD.js";import{b as nn}from"./chunk-ST7XO45I.js";import{d as We,e as ce}from"./chunk-ULED3B5P.js";import{c as qe,d as je,e as K,l as Ze}from"./chunk-ECUGL7AO.js";import{A as Je,F as He,G as Qe,H as z,I as Ye,J as le,K as G,a as Me,c as Y,g as Z,h as Ge,i as Ue,m as $e}from"./chunk-3NV6NBQB.js";import{A as ie,B as ae,z as oe}from"./chunk-WVTKVQLZ.js";import{a as de,b as Xe}from"./chunk-DXNTXCSI.js";import{a as j,b as _e,c as ke,e as De,h as Ve,i as Le,l as Be}from"./chunk-44ZJPQM6.js";import{b as W}from"./chunk-MT4OQFDI.js";import{a as Q}from"./chunk-KJTHMRSH.js";import{m as Ke,n as ue,o as ze,p as se}from"./chunk-JW4MSBYN.js";import{g as Ee,m as Ce,w as re}from"./chunk-EJSTRCBQ.js";import{b as Pe,d as L,e as Ae,f as Te}from"./chunk-LUVTP4VU.js";import{a as m}from"./chunk-ZRU7WONE.js";import{h as V}from"./chunk-TFPLIX5E.js";import{a as en}from"./chunk-5MRSFLQA.js";import{b as n}from"./chunk-S7NHVERO.js";import{a as on}from"./chunk-DSPLGTQI.js";import{c as Ne,f as Oe}from"./chunk-VPT5MFDG.js";function an(e){return Fn({...e,namespace:"commands",identity:[e.runToken]})}function Fn(e){let t,u,r=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),o=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let c=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??en).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",c));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,i=>i.toString(16).padStart(2,"0")).join("")});o.catch(()=>{});async function p(c){try{let a=await o;return await u.request(a,{mode:"exclusive"},()=>c(a))}catch(a){throw a instanceof m?a:r()}}function d(c){let a=t.getItem(c);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let i=JSON.parse(a);if(!i||typeof i!="object"||!("revision"in i)||!("entry"in i)||!Number.isSafeInteger(i.revision)||Number(i.revision)<0)throw r();return{revision:Number(i.revision),entry:i.entry}}return{read:()=>p(d),write:(c,a)=>p(i=>{if(d(i).revision!==c)return null;if(!Number.isSafeInteger(c+1))throw r();let y=JSON.stringify({revision:c+1,entry:a});if(y.length>1048576)throw r();return t.setItem(i,y),c+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var M=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),En=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Cn=n.discriminatedUnion("type",[$e,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:M.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:He,openIn:Qe}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:M})]),Pn={id:M,presentation:Pe,outputs:n.array(M).max(250),inputs:se,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Ee,customerData:Ce,dataCursors:n.record(M,Ke.nullable())},Nn=n.strictObject({...Pn,content:n.strictObject({type:n.literal("document"),document:re})}),pe=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:M,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:En,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:ue,parameters:ze,variables:n.record(n.string(),L),output:L.nullable(),screen:Nn.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([We,ce]),quote:oe.nullable(),operation:ie.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Cn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),On=n.strictObject({scope:V,run:pe,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:oe.nullable(),operation:ie.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative(),document:re,answers:ue,inputs:se,values:n.record(n.string(),L).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),sn=On.extend({run:pe.extend({paywall:pe.shape.paywall.unwrap().extend({resolution:ce}).nullable()})});var ln="X-Indiana-Server-Key";var An=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),Tn=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(An).max(200).default([]),iam:Ge.optional(),renderGuard:Z.optional()}),me=Tn.omit({variation:!0,description:!0,iam:!0}),_n=qe.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([me,me]).rest(me).refine(e=>e.length<=20)}),cn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(_n).max(100),savedGroups:je});var $=n.string().regex(/^[a-f0-9]{64}$/),Tt=n.strictObject({iam:$,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),kn=n.strictObject({release:$,render:Z,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),_t=n.strictObject({scope:V.extend({environmentId:n.uuid()}),release:$,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),delivery:Ue.optional(),target:kn})).max(4e3)}),kt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:$,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Dt=n.strictObject({scope:V,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Vt=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Dn=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),fe=n.strictObject({operation:n.literal("page_experiments"),release:$,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(Q).optional()}),dn=n.strictObject({scope:V,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:cn});var U=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),mn=n.strictObject({entry:U,nodes:n.array(n.strictObject({id:U,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),U),writes:n.record(j,j),resources:n.strictObject({screenId:U.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),pn={scope:V,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:mn},X=n.discriminatedUnion("evaluationMode",[n.strictObject({...pn,evaluationMode:n.literal("local"),growth:K,conditions:n.record(U,n.array(n.strictObject({condition:Te,port:n.string()})))}),n.strictObject({...pn,evaluationMode:n.literal("remote")})]),Vn=X.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,ke),outputSchema:_e,terminals:n.record(U,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Je.nullable()}))})});function Ln(e){return mn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(d=>d.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,d)=>{u[`case:${d}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let o=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return o?.type==="feature"&&(r.featureKey=o.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ge(e){let t=le.parse(e.document),u=e.evaluationMode==="local"?K.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:Ln(t)};return X.parse(e.evaluationMode==="remote"?r:{...r,growth:Ze(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(o=>o.type==="condition").map(o=>[o.id,o.cases.map((p,d)=>({condition:p.condition,port:`case:${d}`}))]))})}function $t(e){let t=ge(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=le.parse(e.document);return Vn.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let o=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:o&&o.type!=="literal"&&o.type!=="feature"&&o.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:o??null}]]}))}})}var Ie=32,Mn=522240;function ve(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var qn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),ye=n.record(n.string(),L),jn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:z.shape.schemaVersion,kind:z.shape.kind,selector:z.shape.selector,contract:z.shape.contract}),context:ye,removed:n.array(n.string()).max(100),attributes:ye,removedAttributes:n.array(n.string()).max(100),result:Ye,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),Wt=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:qn,context:ye,steps:n.array(jn).min(1).max(Ie)}).refine(e=>Y(e)<=Mn,"Segment exceeds its byte budget");var Gn=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function J(e){return Array.isArray(e)?e.some(J):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&J(u):!Gn.test(t))}function fn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(c=>c.id===t.screenId&&c.type==="paywall")))return"customer_required";let o=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(o&&["bundle","selection","offering"].includes(o.type)||t.type==="condition"&&t.cases.some(c=>J(c.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(c=>c.id===t.screenId):null]);for(let[c,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${c}`)||p.includes(JSON.stringify(c))))return"customer_required";if(t.type==="split"){let c=u.experiments?.[t.experimentId];if((c?.hashAttribute??"id")!=="funnelParticipantId"||J(c?.condition)||c?.parentConditions?.length)return"customer_experiment_required"}let d=t.type==="feature"?t.featureKey:o?.type==="feature"?o.featureKey:void 0;return d&&u.features?.[d]?.rules?.some(c=>(c.hashAttribute??"id")!=="funnelParticipantId"||J(c.condition)||c.parentConditions?.length)?"customer_experiment_required":null}var he=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},ee=(e,t)=>new he(e,t),Un=e=>({experiments:e.experiments,features:e.features});function we(e,t=ee){let u=new Map(e.topology.nodes.map(d=>[d.id,d])),r=Ne(e.growth.savedGroups),o=Un(e.growth);function p(d,c){if(!Object.hasOwn(e.growth.features,d))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Oe(d,c).value}return{nodes:u,savedGroups:r,features:o.features,feature:p,evaluate(d,c){let a=u.get(d);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let i,g;if(a.type==="condition"){let v=e.conditions[a.id];if(!v)throw t("INVALID_RESPONSE","Local condition rules are unavailable");i=de({id:a.id,name:a.id,type:"condition",cases:v.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},c,o.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,c),i="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=de({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},c,o.experiments);g=h.value,i=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,c),i=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[i]??(i==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:d,port:i,target:y,...g===void 0?{}:{value:g}}}}}function dr(e,t,u,r=ee){return be(e,r)(t,u)}function be(e,t){let u=X.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,o=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};o();let p=we(u,t);return(d,c)=>(o(),Bn(p,d,c))}function Bn(e,t,u){let r=Ae.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:o,onFeatureUsage:p,onExperimentViewed:d}=u,c={attributes:r,...o?{saveStickyBucketAssignmentDoc:a=>o(structuredClone(a))}:{},...p?{onFeatureUsage:(a,i)=>p(a,structuredClone(i))}:{},...d?{onExperimentViewed:(a,i)=>d(structuredClone(a),structuredClone(i))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,c)}function pr(e,t,u,r=ee){return gn(be(e,r),t,u)}function gn(e,t,u){let r=[],o=[],p=[],d=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(c){let a=r.findIndex(y=>y.next.attributeName===c.attributeName&&y.next.attributeValue===c.attributeValue),i=c.attributeName+"||"+c.attributeValue,g={expected:u.sticky[i]??null,next:c};a<0?r.push(g):r[a]=g},onExperimentViewed(c,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&o.push(L.parse({key:c.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(c,a){p.push(L.parse({feature:c,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:d.port,...d.value===void 0?{}:{value:d.value},sticky:r,exposures:o,features:p}}function yn(e,t,u,r=ee){let o=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),d=structuredClone(u.variables),c=structuredClone(o.sticky),a=[],i=u.nodeId,g=u.visit,y=!1,v,h=O=>fn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},o.attributes.funnelCustomerBound===!0),R=O=>(v??=be(e,r),gn(v,O,{attributes:Be({declarations:t.variables,attributes:o.attributes,parameters:u.parameters,answers:u.answers,results:d,savedGroups:{}}),sticky:c}));for(let O=0;O<Ie;O++){let s=p.get(i);if(!s||!ve(s)||h(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let f,w;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")f=R(s.id),s.type==="offering"&&(f.value={type:"offering_version",id:String(f.value)}),s.type==="condition"?w=f.port==="default"?s.default:s.cases[Number(f.port.slice(5))]?.target:s.type==="split"?w=f.port==="notParticipating"?s.notParticipating:s.routes[f.port]:(s.type==="feature"||s.type==="offering")&&(w=s.next);else if(f={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(w=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(f.value={type:"offering_version",id:s.configuration.versionId},w=s.next),s.type==="end"||s.type==="output"){let x=s.type==="end"?s.output:s.value;if(f=x?.type==="feature"?R(s.id):{...f,port:"value",value:x?.type==="literal"?x.value:x?.type==="variable"?Me({source:"variable",key:x.key,...x.path?{path:x.path}:{}},{declarations:t.variables,answers:u.answers,results:d,parameters:u.parameters,attributes:o.attributes,savedGroups:{}}):null},x&&(f.value===void 0||!De(t.outputSchema,f.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let N=[...a,{nodeId:i,result:f}];if(Y({steps:N})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:i,result:f}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let x=s.type==="coupons"?s.couponIds.map(D=>({type:"reward",id:D})):s.type==="coupon"?{type:"reward",id:s.couponId}:f.value;if(x===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=Ve(s,{value:x});Le(t.variables,s,_),Object.assign(d,_)}for(let x of f.sticky)c[`${x.next.attributeName}||${x.next.attributeValue}`]=structuredClone(x.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!w)throw r("INVALID_RESPONSE","Local pure exit is unavailable");i=w,g++}let T=p.get(i);return{steps:a,...!y&&T&&(!ve(T)||h(T))?{boundary:{nodeId:i,visit:g}}:{}}}function In(e,t){let u=sn.safeParse(t);if(!u.success)throw new m("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Funnel scope changed");return r}var xe=(e,t)=>new m(e,t);function hr(e){return we(e,xe)}var Kn=3,zn=2e3;function $n(e){return e instanceof TypeError||e instanceof m&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Jn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Kn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*zn))}}async function Re(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let o=null,p;if(u)try{let d=await e.funnel(t.source.id,t.source.versionId);p=d.manifest.generation,o=Hn(e,t,d)}catch{o=null}return p??=e.snapshot?.generation??(await Jn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:o}}function Hn(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:o,remoteFeatures:p,...d}=u.growth,c=ge({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:K.parse(d)}),a=Qn(c,u.document,{...t,...r}),i=a.steps.at(-1),g=a.boundary??(i?.result.port==="value"?{nodeId:i.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Qn(e,t,u){return yn(e,t,u,xe)}var vn=G.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 m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),hn=n.strictObject({schemaVersion:n.literal(1),scope:V,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:vn.optional(),closeCommand:vn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.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"),A=()=>new m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),ne=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function H(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function wn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),o=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:hn.parse(a.entry)}}function d(a){let i=o.then(a);return o=i.catch(()=>{}),i}async function c(a){for(let i=0;i<4;i++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(ne(g.entry,y)){t=g.revision;return}let v=await e.write(g.revision,y);if(v!==null){if(!Number.isSafeInteger(v)||v<=g.revision)throw A();t=v;return}}throw A()}return{bind(a){let i=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==i)throw A();u=i},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let i=hn.parse(a),g=i.command;return!g||u!==null&&r(i)!==u?Promise.reject(A()):(u??=r(i),d(()=>c((y,v)=>{if(y&&!ne(r(y),r(i)))throw A();if(y&&i.processBindingIds){for(let[h,R]of Object.entries(i.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==R)throw A();y={...y,processBindingIds:{...y.processBindingIds,...i.processBindingIds}}}if(!y){if(v!==t&&g.operation!=="close")throw A();return i}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!ne(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!ne(y.command,g))throw A();return y})))},observePurchase(a,i,g,y){return d(()=>c((v,h)=>{if(!v&&h!==t||v&&r(v)!==r({...a,schemaVersion:1}))throw A();if(v?.purchase&&v.purchase.generation>i.generation)return H(v,y);if(v?.purchase&&v.purchase.generation===i.generation&&v.purchase.operationId!==i.operationId)throw A();return g?!v?.purchase||v.purchase.operationId!==i.operationId?H(v,y):H(v.command?{...v,purchase:void 0}:null,y):H({schemaVersion:1,...a,...v,purchase:i},y)}))},settle(a){return d(()=>c(i=>H(i,a)))}}}function Tr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function te(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((o,p)=>te(o,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([o,p])=>Object.hasOwn(t,o)&&te(p,Reflect.get(t,o)))}function bn(e,t){let u=t&&{...t},r=null,o=0,p=-1,d=0,c=new AbortController;function a(){d++,c.abort(new m("IDENTITY_CHANGED","Run identity changed")),c=new AbortController}let i=!1,g,y=0,v=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new m("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===d?r:null},get viewAgeMs(){return r&&p===d?performance.now()-o:void 0},get generation(){return d},get signal(){return c.signal},get disposed(){return i},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,R="Run identity changed during the request"){if(h!==d||i)throw new m("IDENTITY_CHANGED",R)},assertRun(h){if(r&&(h.id!==r.id||h.source.type!==r.source.type||h.source.id!==r.source.id||h.source.versionId!==r.source.versionId||h.locale!==r.locale||!te(h.parameters,r.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,R,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&R.run.revision<=r.revision)&&!(r&&R.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!R.run.stopped&&["running","waiting"].includes(R.run.status)&&r&&p===d&&R.run.nodeId===r.nodeId&&R.run.visit===r.visit&&R.run.revision===r.revision&&(R.run.screen=r.screen,(r.paywall?.quote?.operationId===R.review?.activeOperationId||!r.paywall?.quote&&R.review?.activeOperationId===null)&&(R.run.paywall=r.paywall)),!(r?.paywall&&R.run.paywall&&r.paywall.receiptId===R.run.paywall.receiptId&&(R.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||R.run.revision>=r.revision)r=R.run,o=performance.now(),p=d;else if(!s)return;if(r&&p===d)for(let f of v)try{f(structuredClone(r))}catch{}}},identify(h){if(i)throw new m("IDENTITY_CHANGED","Controller was reset");if(!Q.test(h))throw new m("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return v.add(h),()=>v.delete(h)},reset(){i||(i=!0,a(),g=void 0,r=null,v.clear())}}}var Se=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function qr(e,t,u="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",t);if(!Se.test(e))throw new m("INVALID_TOKEN",u)}function jr(e){let t=W(e);return t.identify(e.apiKey),t}function xn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&!ae(t)&&["apple","google"].includes(t.provider)?"native":t&&!ae(t)&&t.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new m("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function q(e){let{customerToken:t,...u}=e;return u}var Yn=e=>!(e instanceof m&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Rn({journal:e,state:t,call:u,processIdentity:r}){let o=null,p=null,d=!1,c={command:null,close:null},a=new Set,i,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(w=>w&&!Object.hasOwn(s.processBindingIds??{},w.requestId)))throw new m("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new m("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=s.purchase,d=s.closed===!0,!s.command)return;let f=s.command;o=f.operation==="close"?null:f,p=f.operation==="close"?f:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(d=!0);for(let w of[o,p])w&&a.add(w.requestId)}):Promise.resolve();y.catch(()=>{});async function v(s,f){e&&await y;let w=t.generation;if(e){if(!t.view||!t.scope)throw new m("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:q(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(w!==t.generation||o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");if(e&&on(f),t.assertCurrent(w),o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let N=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(x){let _=s.operation==="submit"&&s.input.type==="paywall_quote",D=!N&&!Yn(x),l=!1;if(_&&D&&w===t.generation&&o===s&&x instanceof m&&x.status!==void 0){let I=await T(s.requestId).catch(()=>{});l=I?.settlement?.state==="unknown"&&I.settlement.operationId===null}throw w===t.generation&&(o===s||p===s)&&D&&(!_||!(x instanceof m)||x.status===void 0||l)&&(e&&await e.settle(s.requestId),w===t.generation&&O(s)),x}}function h(s,f){let w=G.parse(s);if(w.operation==="start"||w.operation==="get"||w.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(d&&w.operation!=="close"){if(o?.requestId===w.requestId)return T(w.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(w.operation==="close"){if(o?.requestId===w.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(d=!0,p&&JSON.stringify(q(p))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original Close");return p??=w,c.close?c.close:R(p,"close",f)}if(o){if(JSON.stringify(q(o))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(c.command)return c.command}else o=w;return R(o,"command",f)}function R(s,f,w){let N=v(s,w);c[f]=N;let x=()=>{c[f]===N&&(c[f]=null)};return N.then(x,x),N}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||o!==s&&p!==s?!1:(o===s&&(o=null),p===s&&(p=null),a.delete(s.requestId),!o&&!p&&(g=null),!0)}return{ready:y,get pending(){return o},get closing(){return p},get closeRequested(){return d},get inFlight(){return c.command},get closeFlight(){return c.close},get purchase(){return i},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,f,w,N){let x=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=x&&f.settlement?.state==="settled"&&f.run.pendingRequest?.requestId!==x&&(s.operation==="get"||!d||s.operation==="close"||!["running","waiting"].includes(f.run.status))?x:void 0,D=o?.requestId===_?o:p?.requestId===_?p:void 0;e?.bind({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId});let l=f.run.paywall,I=l??f.purchase,C=I?.operation,E=f.settlement&&(!l||l.purchaseRequestId===f.settlement.requestId)&&(!i||i.operationId===f.settlement.operationId)?f.settlement:void 0,S=C?.operationId??I?.quote?.operationId??E?.operationId,F=I?.receiptId??E?.receiptId,b=l?.selectionGeneration??i?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||f.run.revision>=t.view.revision)&&(N===void 0||N>=t.readSequence)&&(!i||b>=i.generation)){let P={receiptId:F,operationId:S,generation:b},k=rn(C,I?.canReselect===!0);await e.observePurchase({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId},P,k,_),t.assertCurrent(w),(!i||P.generation>=i.generation)&&(N===void 0||N>=t.readSequence)&&(k?i?.operationId===P.operationId&&(i=void 0):i=P)}else e&&_&&await e.settle(_);return t.assertCurrent(w),_?O(D):!1},stop(){d=!0},submit:h,settle:T,reset(){d=!0,o=null,p=null,i=void 0,g=null,c.close=null,a.clear(),c.command=null}}}function Zn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new m("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new m("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Se.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=W({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),o=bn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(R),d=null,c=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=c&&wn(c),i=Rn({journal:a,state:o,call:T,processIdentity:e.process}),g=0,y=new Map;function v(){g++,y.clear(),t=void 0}async function h(l){let I=l.operation==="resume"?i.pending?.operation==="resume"?null:i.pending:l;if(u&&l.operation==="resume"&&!I&&l.requestId!==e.customerRun?.startRequestId)throw new m("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(I?.operation==="submit"&&I.input.type==="paywall_confirm"){let P=o.view?.paywall;xn(u,P?.quote?.operationId===I.input.operationId?P.quote:void 0)}if(e.process)return e.process.request(l);let C=o.generation;o.assertCurrent(C);let E=performance.now()+(e.timeoutMs??35e3),S=o.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let P=o.signal,k,B=()=>{},Sn=new Promise((Wn,Fe)=>{B=()=>Fe(P.reason),P.addEventListener("abort",B,{once:!0}),k=setTimeout(()=>Fe(new m("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(o.assertCurrent(C),e.session.access())),Sn])}finally{clearTimeout(k),P.removeEventListener("abort",B)}}o.assertCurrent(C);let F={...l,...S?{customerToken:S}:{}},b=l.operation==="page_experiments"?fe.parse(F):G.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new m("IDENTITY_CHANGED","Original recovery Customer changed");let P={...b};return"customerToken"in P&&delete P.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:P},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",b,e.runToken,{headers:e.serverKey&&!S?{[ln]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function R(){v(),p?.(),o.reset(),i.reset(),d=null,r.dispose()}async function T(l,I){let C=t;t=void 0;let E=o.generation,S=()=>o.assertCurrent(E);a&&await i.ready,S();let F=o.view,b=In(e,C!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?C:await h(l));if(l.operation==="review"&&!b.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&b.run.id!==e.customerRun.runId)throw new m("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&b.purchase&&(b.purchase.receiptId!==l.purchase.receiptId||(b.purchase.operation?.operationId??b.purchase.quote?.operationId)!==l.purchase.operationId))throw new m("INVALID_RESPONSE","The requested original purchase changed");if(S(),b.runToken&&b.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let P=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(P&&b.settlement?.requestId!==P)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");i.assertBinding(b),o.assertRun(b.run),o.bindScope(b.scope);let k=await i.observe(l,b,E,I);return(!o.view||b.run.revision>=o.view.revision)&&(I===void 0||I>=o.readSequence)&&(await e.onAcceptedResponse?.(b),S()),!b.run.stopped&&["running","waiting"].includes(b.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(b.run.status)||i.stop(),o.publish(l,b,F,I,k)),b}function O(l){let I=o.generation;v();let C=l(),E=()=>{o.generation===I&&v()};return C.then(E,E),C}let s=(l,I)=>O(()=>i.submit(l,I)),f=null,w=new WeakMap;function N(l){let I=w.get(l);if(I)return I;let C=_(l);return w.set(l,C),C}let x=!1;async function _(l){let I=await l;if(I.run.instruction?.type!=="evaluate_segment")return I;if(f)return f;x=!0;let C=o.generation,E=(async()=>{for(let S=0;S<32&&I.run.instruction?.type==="evaluate_segment";S++){if(i.pending||i.closeRequested)return I;let F=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:P}=await Re(e.configuration,F,{predict:!1});if(C!==o.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(i.pending||i.closeRequested)return I;if(o.view&&(o.view.revision!==F.revision||o.view.visit!==F.visit||o.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Re(e.configuration,F).then(({prediction:B})=>{k&&C===o.generation&&!i.closeRequested&&o.view?.id===F.id&&!o.view.stopped&&o.view.nodeId===F.nodeId&&o.view.visit===F.visit&&o.view.revision===F.revision&&(d=B)}).catch(()=>{});try{I=await s({operation:"commit_segment",requestId:Xe(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...P})}finally{k=!1,d=null}}}return I})();f=E;try{return await E}finally{f===E&&(f=null)}}let D={get configuration(){return x?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=o.currentView;return l?structuredClone(l):null},get viewAgeMs(){return o.viewAgeMs},get pendingCommand(){let l=i.closing??i.pending;return l?structuredClone(q(l)):null},get pendingCommands(){return[i.pending,i.closing].filter(l=>l!==null).map(l=>structuredClone(q(l)))},get pendingPurchase(){return i.purchase?structuredClone(i.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=o.view;return d&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===d.runId&&l.nodeId===d.from.nodeId&&l.visit===d.from.visit&&l.revision===d.from.revision&&!i.closeRequested?structuredClone(d):null},settle:(...l)=>O(()=>i.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return nn(e,l)},async pageExperiments(l,I=[]){let C=o.generation;o.assertCurrent(C);let E=o.view?.id;if(!E)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let S=dn.parse(await h(fe.parse({operation:"page_experiments",release:l,usedReceiptIds:I})));if(o.assertCurrent(C),S.runId!==E||S.scope.projectId!==o.scope?.projectId||S.scope.environment!==o.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},o.nextRead())},async get(l,I){let C=o.generation;l=l&&structuredClone(l),I=I&&{...I},a&&await i.ready,o.assertCurrent(C),I??=i.purchase&&{receiptId:i.purchase.receiptId,operationId:i.purchase.operationId};let E=JSON.stringify([o.generation,g,l??null,I??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=o.nextRead(),b=N(T({operation:"get",...l?{data:l}:{},...I?{purchase:I}:{}},F));y.set(E,b);let P=()=>{y.get(E)===b&&y.delete(E)};return b.then(P,P),b.then(k=>structuredClone(k))},resume(l=o.view?.pendingRequest?.requestId){return l?i.closeRequested?D.settle(l):i.pending?.requestId===l?N(s(i.pending)):N(s({operation:"resume",requestId:l})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(l){return N(s(l))},async retry(){if(i.closeFlight)return i.closeFlight;if(i.closing)return s(i.closing);if(i.closeRequested&&i.pending)return D.settle(i.pending.requestId);if(i.inFlight)return N(i.inFlight);if(!i.pending)throw new m("INVALID_REQUEST","No command is pending");let l=i.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let I=o.generation;if(await D.settle(l.requestId),o.assertCurrent(I),!i.pending)return D.get();if(i.pending!==l||i.closeRequested)throw new m("COMMAND_PENDING","The original quote is being recovered")}return N(s(l))},identify(l){let I=o.customerToken?void 0:t;v(),o.identify(l),t=I,d=null,r.reset()},get identitySignal(){return o.signal},subscribe:o.subscribe,reset:R};return tn(D,(l,I)=>N(s(l,I))),D}function po(e,t){return Zn({...e,runToken:"",initialResponse:t})}export{un as a,Cn as b,pe as c,On as d,sn as e,kn as f,_t as g,kt as h,Dt as i,fe as j,dn as k,X as l,Vn as m,$t as n,dr as o,pr as p,In as q,xe as r,hr as s,Qn as t,hn as u,H as v,an as w,Fn as x,Tr as y,te as z,Se as A,qr as B,jr as C,xn as D,Zn as E,po as F};
@@ -1 +1 @@
1
- import{a as m,m as f,p as y}from"./chunk-FUP5JVDE.js";import{g as d}from"./chunk-56YCOGQZ.js";import{e as l,f as u,j as p}from"./chunk-O5YYORDW.js";import{b as e}from"./chunk-YLH3AYCK.js";var h={funnelId:e.uuid().optional(),funnelVersionId:e.uuid().optional()};var w=e.strictObject({runId:e.uuid(),bindingId:e.uuid(),receiptId:e.uuid()});var q=e.strictObject({processContext:w.optional(),...h,selector:e.discriminatedUnion("type",[e.strictObject({type:e.literal("paywall"),paywallId:e.uuid()}),e.strictObject({type:e.literal("version"),versionId:e.uuid()})]),customerId:e.uuid().optional(),commerce:l,locale:e.string().min(1).max(35),requirement:u.optional()}),c=e.strictObject({id:e.uuid(),paywallId:e.uuid(),version:e.number().int().positive(),document:m.omit({requirement:!0,offeringId:!0}),offering:e.strictObject({id:e.uuid()}),content:e.strictObject({environmentId:e.uuid(),offeringVersionId:e.uuid(),artifact:y.refine(n=>n.kind==="paywall"&&n.formatVersion===1)}).optional(),capabilities:d,check:p.nullable()}).superRefine((n,r)=>{let t=new Set(n.document.products.items.map(o=>o.productVersionId));(n.document.offeringVersionId!==n.offering.id||Object.values(n.capabilities.plans).some(o=>!t.has(o.versionId)))&&r.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),M=e.strictObject(c.shape).omit({document:!0,offering:!0}).extend({content:c.shape.content.unwrap()});function _(n,r){let t=f.parse(r);if(t.offeringVersionId!==n.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let o=structuredClone(n.capabilities);for(let[g,i]of Object.entries(t.catalog)){let a=o.plans[g],s=i.channels.stripe?.prices.find(I=>I.currency===a?.currency);a&&s&&Object.assign(a,{amountMinor:s.amountMinor,interval:i.interval,intervalCount:i.intervalCount,...i.prepaid?.length?{prepaid:i.prepaid}:{}})}return c.parse({...n,capabilities:o,document:{schemaVersion:3,kind:t.kind,name:t.name,presentation:t.presentation,products:t.products,offeringVersionId:t.offeringVersionId,screen:t.screen,buttons:t.buttons},offering:{id:t.offeringVersionId}})}export{h as a,w as b,q as c,c as d,M as e,_ as f};
1
+ import{a as m,m as f,p as y}from"./chunk-ECUGL7AO.js";import{g as d}from"./chunk-EJSTRCBQ.js";import{e as l,f as u,j as p}from"./chunk-26QYDE7V.js";import{b as e}from"./chunk-S7NHVERO.js";var h={funnelId:e.uuid().optional(),funnelVersionId:e.uuid().optional()};var w=e.strictObject({runId:e.uuid(),bindingId:e.uuid(),receiptId:e.uuid()});var q=e.strictObject({processContext:w.optional(),...h,selector:e.discriminatedUnion("type",[e.strictObject({type:e.literal("paywall"),paywallId:e.uuid()}),e.strictObject({type:e.literal("version"),versionId:e.uuid()})]),customerId:e.uuid().optional(),commerce:l,locale:e.string().min(1).max(35),requirement:u.optional()}),c=e.strictObject({id:e.uuid(),paywallId:e.uuid(),version:e.number().int().positive(),document:m.omit({requirement:!0,offeringId:!0}),offering:e.strictObject({id:e.uuid()}),content:e.strictObject({environmentId:e.uuid(),offeringVersionId:e.uuid(),artifact:y.refine(n=>n.kind==="paywall"&&n.formatVersion===1)}).optional(),capabilities:d,check:p.nullable()}).superRefine((n,r)=>{let t=new Set(n.document.products.items.map(o=>o.productVersionId));(n.document.offeringVersionId!==n.offering.id||Object.values(n.capabilities.plans).some(o=>!t.has(o.versionId)))&&r.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),M=e.strictObject(c.shape).omit({document:!0,offering:!0}).extend({content:c.shape.content.unwrap()});function _(n,r){let t=f.parse(r);if(t.offeringVersionId!==n.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let o=structuredClone(n.capabilities);for(let[g,i]of Object.entries(t.catalog)){let a=o.plans[g],s=i.channels.stripe?.prices.find(I=>I.currency===a?.currency);a&&s&&Object.assign(a,{amountMinor:s.amountMinor,interval:i.interval,intervalCount:i.intervalCount,...i.prepaid?.length?{prepaid:i.prepaid}:{}})}return c.parse({...n,capabilities:o,document:{schemaVersion:3,kind:t.kind,name:t.name,presentation:t.presentation,products:t.products,offeringVersionId:t.offeringVersionId,screen:t.screen,buttons:t.buttons},offering:{id:t.offeringVersionId}})}export{h as a,w as b,q as c,c as d,M as e,_ as f};