@tinkerlandai/longplay-sdk 0.10.50 → 0.10.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/dist/chunk-2G23BYBI.js +1 -0
- package/dist/{chunk-GMKLSHXK.js → chunk-3TSFGU4T.js} +1 -1
- package/dist/{chunk-A2ZWWIUK.js → chunk-3Z3HL42M.js} +2 -2
- package/dist/{chunk-CGJMEKO2.js → chunk-4NO6U4X6.js} +1 -1
- package/dist/{chunk-T3AEVS6M.js → chunk-67LPUJMN.js} +1 -1
- package/dist/{chunk-KECKTHAM.js → chunk-7GU34JD4.js} +1 -1
- package/dist/{chunk-ZS2AOY44.js → chunk-B4SM2KRI.js} +1 -1
- package/dist/chunk-CGJZIDG3.js +1 -0
- package/dist/{chunk-PMUKZX2R.js → chunk-DB5S72HJ.js} +1 -1
- package/dist/{chunk-KKKO6GZ5.js → chunk-FN462OVO.js} +1 -1
- package/dist/{chunk-Z7ESO2IN.js → chunk-GJSQZGBE.js} +1 -1
- package/dist/chunk-IXXVMGMF.js +1 -0
- package/dist/{chunk-5J2CFNYR.js → chunk-MVUNV5XR.js} +1 -1
- package/dist/{chunk-K4TQ5REL.js → chunk-TIUD3N72.js} +1 -1
- package/dist/chunk-TM72XBM5.js +1 -0
- package/dist/{chunk-XLTR45M5.js → chunk-US65SQX4.js} +1 -1
- package/dist/{chunk-EFROBK74.js → chunk-VPYKAEHU.js} +1 -1
- package/dist/{content-AZXMOLCZ.js → content-VTHRQSFT.js} +1 -1
- package/dist/funnel-host-purchase-HBQOWEES.js +1 -0
- package/dist/{funnel-paywall-prerender-HWQX4YNE.js → funnel-paywall-prerender-MD4UI2AP.js} +1 -1
- package/dist/{funnel-runtime-host-Y4IEIGCK.js → funnel-runtime-host-NZAV6C5O.js} +1 -1
- package/dist/index.d.ts +21 -7
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/page.js +1 -1
- package/dist/paywall-DKTGQZDJ.js +1 -0
- package/dist/{paywall-content-TPXYF6DN.js → paywall-content-SML4CL2Q.js} +1 -1
- package/dist/{paywall-session-FQ4VC5WG.js → paywall-session-YKE2CHHI.js} +1 -1
- package/dist/popup.d.ts +2 -2
- package/dist/popup.js +1 -1
- package/dist/{presentation-loading-BaPatcfq.d.ts → presentation-loading-BWUNotNa.d.ts} +8 -1
- package/dist/react-native.js +1 -1
- package/dist/{screen-renderer-Y57TAOIX.js → screen-renderer-HW2WXDTR.js} +1 -1
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-A4TLE4OF.js +0 -1
- package/dist/chunk-J6UQGMH5.js +0 -1
- package/dist/chunk-P5NO4YS3.js +0 -1
- package/dist/chunk-WEHUXUXS.js +0 -1
- package/dist/funnel-host-purchase-VS4BXFCP.js +0 -1
- package/dist/paywall-LNVEFOAB.js +0 -1
- /package/dist/{chunk-A2ZWWIUK.js.LEGAL.txt → chunk-3Z3HL42M.js.LEGAL.txt} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as _e}from"./chunk-3ITNAFAH.js";import{a as M}from"./chunk-2I2S5ZIH.js";import{D as ee,F as Ne,c as Re,e as D,j as Ee,u as ke,v as qe,x as Fe,z as Ae}from"./chunk-GMKLSHXK.js";import{a as Se,b as Ce,c as ve}from"./chunk-Y2ASROJH.js";import{K as x}from"./chunk-LE32WTZ7.js";import{a as te}from"./chunk-LSHIR6QM.js";import{i as ne}from"./chunk-OPUIFAQS.js";import{A as X,C as Z,E as Pe}from"./chunk-EGFVGCDG.js";import{x as de}from"./chunk-YFLVGOCJ.js";import{b as Oe}from"./chunk-KKKO6GZ5.js";import{a as l}from"./chunk-ZDIWOE4Q.js";import{h as W}from"./chunk-FYD7CMS7.js";import{b as be}from"./chunk-ZS2AOY44.js";import{b as n}from"./chunk-XVCSRZX4.js";import{a as pe}from"./chunk-DSPLGTQI.js";var g=x.options,Qe=n.discriminatedUnion("operation",[g[1].omit({customerToken:!0}),g[2].omit({customerToken:!0}),g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0}),g[8].omit({customerToken:!0}),Ee.omit({customerToken:!0})]),me=n.strictObject({receiptId:n.uuid(),operationId:n.uuid()}),nt=n.discriminatedUnion("operation",[n.strictObject({operation:n.literal("find_purchase")}),n.strictObject({operation:n.literal("recover_start"),intent:n.enum(["lookup","resume","start"]),start:n.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),n.strictObject({operation:n.literal("recover_run"),runId:n.uuid(),funnelId:n.uuid()}),n.strictObject({operation:n.literal("recover_purchase"),runId:n.uuid(),funnelId:n.uuid(),purchase:me}),n.strictObject({operation:n.literal("terminate_checkout"),runId:n.uuid(),funnelId:n.uuid(),purchase:me}),n.strictObject({operation:n.literal("settle_command"),runId:n.uuid(),funnelId:n.uuid(),requestId:n.uuid(),command:n.discriminatedUnion("operation",[g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0})]).optional()}).refine(a=>!a.command||a.requestId===a.command.requestId),n.strictObject({operation:n.literal("run_command"),runId:n.uuid(),funnelId:n.uuid(),command:Qe})]),re=n.strictObject({runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),startRequestId:n.uuid(),runExpiresAt:n.iso.datetime({offset:!0}),status:D.shape.run.shape.status}),j={scope:W,customerId:n.uuid()},je=n.discriminatedUnion("outcome",[n.strictObject({...j,outcome:n.literal("unknown"),target:n.null(),view:n.null(),access:n.null()}),n.strictObject({...j,outcome:n.literal("resolved"),target:re,view:D.shape.run.nullable(),access:n.discriminatedUnion("type",[n.strictObject({type:n.literal("customer")}),n.strictObject({type:n.literal("operation_only"),cause:n.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((a,d)=>{a.outcome==="resolved"&&(a.access.type==="customer"!=(a.view!==null)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Te=n.strictObject({...j,target:re,view:D.shape.run.nullable(),settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),acceptance:n.enum(["accepted","not_accepted","unknown"]),receiptPhase:n.enum(["accepted","processing","done"]).nullable(),basis:n.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:n.uuid().nullable(),operationId:n.uuid().nullable()}),purchase:D.shape.purchase.unwrap().nullable()}).superRefine((a,d)=>{let m=a.settlement;(m.acceptance==="accepted"!=(m.receiptPhase!==null)||m.acceptance==="accepted"&&m.basis!=="receipt"||m.acceptance==="unknown"&&(m.state!=="unknown"||m.basis!=="none")||m.acceptance!=="accepted"&&(m.operationId!==null||m.receiptId!==null)||m.acceptance==="not_accepted"&&(m.state!=="settled"||!["run_terminal","position_advanced"].includes(m.basis))||a.purchase&&(a.purchase.receiptId!==m.receiptId||a.purchase.operation&&a.purchase.operation.operationId!==m.operationId||a.purchase.quote&&a.purchase.quote.operationId!==m.operationId)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ue=n.strictObject({...j,target:re,purchase:D.shape.purchase.unwrap()}).superRefine((a,d)=>{(!a.purchase.operation||typeof a.purchase.canReselect!="boolean"||a.purchase.quote&&a.purchase.quote.operationId!==a.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),xe=n.discriminatedUnion("outcome",[n.strictObject({...j,outcome:n.literal("none")}),n.strictObject({...j,outcome:n.literal("blocked")}),n.strictObject({...j,outcome:n.literal("found"),target:re,start:n.strictObject({locale:g[0].shape.locale,parameters:g[0].shape.parameters}),purchase:me})]);var Ye=x.options[0].refine(a=>!a.customer&&!a.customerData),Je=n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),terminal:n.enum(["complete","native"]).nullable()}),De=n.strictObject({schemaVersion:n.literal(1),baseUrl:n.url(),scope:W,customerId:n.uuid(),sessionId:n.uuid(),start:Ye,allowed:n.array(n.enum(["merchant","record_only","indiana","native"])),run:n.strictObject({id:n.uuid(),versionId:n.uuid(),status:Re.shape.status,revision:n.number().int().nonnegative(),runExpiresAt:n.iso.datetime({offset:!0}).optional()}).optional(),purchases:n.array(Je).max(100),operationCommand:n.strictObject({operationId:n.uuid(),intent:n.literal("confirm")}).optional(),journal:n.strictObject({revision:n.number().int().nonnegative(),entry:ke.nullable()})});function He(a){return Fe({...a,namespace:"purchases",identity:[a.scope.projectId,a.scope.environment,a.customerId]})}function Le(a){let d=new URL(a.baseUrl??be).href,m=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function P(){a.assertCurrent();try{let v=await a.storage.read();if(a.assertCurrent(),!Number.isSafeInteger(v.revision)||v.revision<0)throw m();let s=v.entry===null?null:De.parse(v.entry);if(s&&(s.baseUrl!==d||s.customerId!==a.customerId||s.scope.projectId!==a.scope.projectId||s.scope.environment!==a.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(s?.journal.entry&&(s.journal.entry.scope.projectId!==s.scope.projectId||s.journal.entry.scope.environment!==s.scope.environment||s.journal.entry.funnelId!==s.start.funnelId||s.journal.entry.runId!==s.run?.id||s.journal.entry.versionId!==s.run?.versionId)||s?.operationCommand&&!s.purchases.some(E=>E.operationId===s.operationCommand?.operationId))throw m();return{revision:v.revision,entry:s}}catch(v){throw v instanceof l?v:m()}}async function z(v){for(let s=0;s<8;s++){let E=await P(),O=v(structuredClone(E.entry));if(JSON.stringify(O)===JSON.stringify(E.entry))return O;O&&De.parse(O),a.assertCurrent();let R;try{R=await a.storage.write(E.revision,O)}catch{throw m()}if(a.assertCurrent(),R!==null){if(!Number.isSafeInteger(R)||R<=E.revision)throw m();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:P,update:z,baseUrl:d}}var Ke=5*6e4;function $e(a,d){let m=a.purchases.find(P=>P.type==="checkout");if(!a.actions.includes("continue_checkout")||m?.type!=="checkout"||d!==void 0&&m.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return m.checkoutUrl}function kt(a){let d={...a,scope:{...a.scope},executionPolicy:structuredClone(a.executionPolicy)},m=d.session.snapshot();if(!m)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:P,sessionId:z}=m,v=!1,s=null,E,O=null,R=!1,F,B,Q,k={mode:"idle",status:"idle",actions:["start"],purchases:[]},S=new Map,T=new Map,fe=new AbortController,Y=new Set,H=Oe(d),J=_e(H.request);function L(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function y(){if(v||d.session.snapshot()?.customerId!==P)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let h=Le({...d,customerId:P,assertCurrent:y,storage:d.storage??He({baseUrl:d.baseUrl,scope:d.scope,customerId:P})}),Ve=d.session.subscribeIdentity(he);function he(){v||(v=!0,clearTimeout(Q),fe.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),Ve(),s?.reset(),s=null,O=null,H.dispose(),Y.clear(),S.clear(),T.clear())}function C(e){y();let t=JSON.stringify(e)!==JSON.stringify(k);k=e,clearTimeout(Q),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Q=setTimeout(()=>{U().catch(()=>{})},5e3)),t&&pe(d.onRecovery,structuredClone(e));for(let r of t?Y:[]){if(v)break;pe(r,structuredClone(e))}return structuredClone(e)}function I(e){if(y(),!e||e.start.requestId!==E)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function b(e){let t=[...e.purchases],r=e.journal.entry?.purchase;return r&&!t.some(o=>o.operationId===r.operationId)&&t.push({receiptId:r.receiptId,operationId:r.operationId,terminal:null}),t}function A(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&b(e).every(t=>t.terminal!==null)}function _(e,t){let r=e.journal.entry?.command??e.journal.entry?.closeCommand,o=b(e).map(w=>{let le=S.get(w.operationId);return w.terminal&&!le?{type:w.terminal,operationId:w.operationId}:te({quote:le?.quote??null,operation:le??null,requestId:r?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(w.operationId)===!0})}),u=o.filter(w=>!["complete","native"].includes(w.type)),i=u[0],c=u.length===1&&i?.operationId?S.get(i.operationId):void 0;if(c&&(i?.type==="checkout"||i?.type==="cancel"))try{ee({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},c.quote)}catch(w){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:L(w)}}let f;if(t==="operation"&&!r&&i?.type==="cancel"&&c?.quote&&!c.problem&&!c.confirmedAt)try{ee({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},c.quote),Date.parse(c.quote.expiresAt)>Date.now()&&(f={operationId:c.operationId,quote:c.quote})}catch{}let p=o.length>0&&u.length===0,N=A(e)||t==="operation"&&p&&!r&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":r||e.operationCommand||i&&i.type!=="cancel"||t==="operation"&&!f?"waiting_result":"ready";return{mode:t,status:N,purchases:o,...f?{confirmation:structuredClone(f)}:{},actions:["refresh",...A(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:f?["confirm"]:[],...u.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function oe(e){let t=te({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function ae(e){if(!e.operation)return;let t=X.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==P)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let r=ne(S.get(t.operationId)??null,t);S.set(t.operationId,r),r===t&&T.set(t.operationId,e.canReselect===!0)}async function Ge(e){y();for(let r of[e.purchase,e.run.paywall])r&&ae(r);let t=await h.update(r=>{if(I(r),r.run&&(r.run.id!==e.run.id||r.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=b(r);for(let u of[e.purchase,e.run.paywall]){let i=u?.operation?.operationId??u?.quote?.operationId;if(!u||!i)continue;let c=o.find(p=>p.operationId===i);if(c&&c.receiptId!==u.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let f=oe(S.get(i));c?c.terminal??=f:o.push({receiptId:u.receiptId,operationId:i,terminal:f})}return{...r,purchases:o,run:r.run&&(r.run.revision>e.run.revision||!["running","waiting"].includes(r.run.status)&&["running","waiting"].includes(e.run.status))?r.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});I(t),t.run&&!["running","waiting"].includes(t.run.status)&&b(t).some(r=>!r.terminal)&&(t=await V(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(r=>!!r)))),I(t),C(_(t,"run"))}function Me(){return{async read(){let{entry:e}=await h.read();return I(e),structuredClone(e.journal)},async write(e,t){let r=null;return await h.update(o=>{if(I(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return r=null,o.journal.revision!==e?o:(r=e+1,{...o,journal:{revision:r,entry:t}})}),r}}}async function V(e,t=!1,r=new Set){I(e);let o=b(e);for(let i of o){if(i.terminal)continue;let c=r.has(i.operationId)?S.get(i.operationId):void 0;if(c??=await se(e,i),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(c.merchantExecution&&c.merchantExecution.customerId!==P)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&te({quote:c.quote??null,operation:c,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let f=Z(c)?await J.update({operationId:i.operationId,intent:"cancel"}):await J.attach({operationId:i.operationId,intent:"cancel"});if(c=X.parse(f.operation),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");c=await se(e,i)}S.set(i.operationId,ne(S.get(i.operationId)??null,c))}let u=await h.update(i=>{I(i);let c=i.operationCommand&&S.get(i.operationCommand.operationId);return{...i,...c&&(c.confirmedAt||c.merchantExecution||!Pe(c))?{operationCommand:void 0}:{},purchases:b(i).map(f=>({...f,terminal:f.terminal??oe(S.get(f.operationId))}))}});return I(u),u}async function G(e){y();let t=await H.request("funnels",e);return y(),t}async function ze(e){try{return await G(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return G({...e,intent:"resume"})}}async function Be(){let e=M(xe,await G({operation:"find_purchase"}));if(e.customerId!==P||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:r}=e;return await h.update(o=>o&&!A(o)?o:{schemaVersion:1,baseUrl:h.baseUrl,scope:d.scope,customerId:P,sessionId:z,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...r,terminal:null}],journal:{revision:0,entry:null}}),"found"}let K;function ie(e){let t=K;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<Ke))return t.job;let r={at:Date.now(),job:Be().then(o=>(r.outcome=o,r.at=Date.now(),o),o=>{throw K===r&&(K=void 0),o})};return K=r,r.job}async function se(e,t,r="recover_purchase"){let o=M(Ue,await G({operation:r,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId}}));if(ue(e,o),o.purchase.receiptId!==t.receiptId||o.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return ae(o.purchase),S.get(t.operationId)}async function Ie(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let r=M(Te,await G({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(ue(e,r),r.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");r.purchase&&ae(r.purchase);let o=await h.update(u=>{I(u);let i=b(u),{receiptId:c,operationId:f}=r.settlement;if(c&&f){let N=i.find(w=>w.operationId===f);if(N&&N.receiptId!==c)throw new l("INVALID_RESPONSE","Original Receipt changed");N||i.push({receiptId:c,operationId:f,terminal:oe(S.get(f))})}let p=r.settlement.state==="settled"?qe(u.journal.entry,t.requestId):u.journal.entry;return{...u,purchases:i,journal:p===u.journal.entry?u.journal:{revision:u.journal.revision+1,entry:p}}});I(o),e=o}return e}function ue(e,t){if(t.customerId!==P||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function ce(e,t){if(I(e),e.run&&(e=await Ie(e)),!b(e).length&&A(e))return C(_(e,"operation"));if(!b(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(t)});R=!0;let r=await V(e);return C(_(r,"operation"))}async function $(e,t=!1,r=!0){if(E=e.start.requestId,O=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!s){let o=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await ze(o)}catch(p){if(!e.run&&p instanceof l&&(p.status===void 0||p.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:L(p)});throw p}let i=M(je,u);if(i.customerId!==P||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});ue(e,i);let c=await h.update(p=>(I(p),{...p,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??p.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(I(c),e=c,i.access.type==="operation_only")return ce(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ie(e);let f=i.view;if(f.locale!==e.start.locale||!Ae(f.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");s=Ne({...d,customerRun:{runId:i.target.runId,customerId:P,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},funnelCommandStorage:Me(),onAcceptedResponse:Ge},{scope:i.scope,run:f})}try{await s.get(),s.view?.pendingRequest?.requestId===e.start.requestId&&!s.pendingCommands?.length&&await s.resume(s.view.pendingRequest.requestId);for(let u of s.pendingCommands??[])u.operation!=="close"&&await s.settle?.(u.requestId);s.pendingCommands?.length&&await s.retry(),y();let o=(await h.read()).entry;return I(o),C(_(o,"run"))}catch(o){if(y(),r&&o instanceof l&&(o.status===401||o.status===409&&o.reason==="STATE_CHANGED")){s.reset(),s=null;let u=(await h.read()).entry;return I(u),$(u,!1,!1)}throw o}}function q(e,t="read",r){if(y(),F)return t==="read"||t===B?F:F.then(()=>q(e,t,r),()=>q(e,t,r));clearTimeout(Q);let o=e().catch(u=>{throw!v&&!r?.(u)&&C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:k.purchases,error:L(u)}),u});return F=o,B=t,o.then(()=>{F===o&&(F=void 0,B=void 0)},()=>{F===o&&(F=void 0,B=void 0)}),o}function U(){return q(async()=>{let{entry:e}=await h.read();if(!e||A(e)){if(await ie(!1)==="blocked")return we();({entry:e}=await h.read())}return e?(E&&e.start.requestId!==E&&(s?.reset(),s=null,S.clear(),T.clear(),R=!1),R&&E===e.start.requestId?ce(e,k.error):$(e)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function we(){return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function ye(){let e=await U();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:q(async()=>{let t=(await h.read()).entry;if(I(t),!R){if(!s?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=s.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(Z(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return C(_(t,"run"));if(s.pendingCommands?.length)await s.retry();else{let w=s.view;await s.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:w.nodeId,visit:w.visit,revision:w.revision,input:{type:"paywall_confirm",operationId:w.paywall.quote.operationId,...w.paywall.quote.merchantTerms?{merchantConfirmation:de(w.paywall.quote.merchantTerms)}:{}}})}let N=(await h.read()).entry;return I(N),C(_(N,"run"))}let r=t.operationCommand?.operationId??k.confirmation?.operationId,o=r&&S.get(r);if(!r||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");ee({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await h.update(p=>{if(I(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==r)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:r,intent:"confirm"}}});let u={operationId:r,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:de(o.quote.merchantTerms)}:{}},i=Z(o)?await J.update(u):await J.attach(u),c=X.parse(i.operation);if(y(),i.operation.operationId!==r)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");S.set(r,ne(o,c));let f=(await h.read()).entry;return I(f),C(_(await V(f,!1,new Set([r])),"operation"))},"confirm")}async function ge(){y();let{entry:e}=await h.read();return e?A(e)?"finished":"pending":"none"}return{get controller(){return s},get recovery(){return structuredClone(k)},get attempt(){return y(),structuredClone(O)},get identitySignal(){return fe.signal},get customerId(){return P},retained:ge,async findPurchase(){let e=await ge();if(e==="pending")return e;let t=await ie(!0);return y(),t==="none"?e:t},async readPaywall(e){y();let t=Se(e),[r,{readPaywallContent:o},{validateResourceCheck:u}]=await Promise.all([Ce(H.request,"resolvePaywall"),import("./paywall-content-TPXYF6DN.js"),import("./check-response-MCT5RGOM.js")]);y();let i=r.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),c=await ve(H.request,r,i);u(i,c.paywall.check,c.scope);let f=await o(d,c.paywall);if(y(),t.paywallVersionId?f.id!==t.paywallVersionId:f.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return f},start(e){let t=x.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return q(async()=>{let r=(await h.read()).entry;if((!r||A(r))&&await ie(!0)==="blocked")return we();let o=await h.update(u=>{if(u&&!A(u)){if(u.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return u}return{schemaVersion:1,baseUrl:h.baseUrl,scope:d.scope,customerId:P,sessionId:z,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return E!==o.start.requestId&&(s?.reset(),s=null,S.clear(),T.clear(),R=!1),R?ce(o,k.error):$(o,!0)},`start:${t.funnelId}`)},refresh:U,confirm:ye,retry:()=>R?ye():q(async()=>{let{entry:e}=await h.read();return e?$(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return s?.view?q(async()=>{if(!s?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(s.pendingCommands?.find(r=>r.operation==="close"))await s.retry();else if(["running","waiting"].includes(s.view.status)){let r=s.view;await s.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:r.nodeId,visit:r.visit,revision:r.revision})}let t=(await h.read()).entry;return I(t),C(_(t,"run"))},"close"):U()},async continueCheckout(e,t){let r=t?await q(async()=>{let{entry:o}=await h.read();if(I(o),!o.run||!b(o).some(i=>i.operationId===t&&!i.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let u=await V(o);return C(_(u,R?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await U();y(),await e($e(r,t))},async terminateCheckout(e){let t=await U();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return q(async()=>{let{entry:o}=await h.read();I(o);let u=b(o).find(c=>c.operationId===e&&!c.terminal);if(!u||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await se(o,u,"terminate_checkout");let i=await V(o,!1,new Set([e]));return C(_(i,R?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return Y.add(e),()=>{Y.delete(e)}},destroy:he}}export{He as a,$e as b,kt as c};
|
|
1
|
+
import{b as _e}from"./chunk-3ITNAFAH.js";import{a as M}from"./chunk-2I2S5ZIH.js";import{D as ee,F as Ne,c as Re,e as D,j as Ee,u as ke,v as qe,x as Fe,z as Ae}from"./chunk-3TSFGU4T.js";import{a as Se,b as Ce,c as ve}from"./chunk-Y2ASROJH.js";import{K as x}from"./chunk-LE32WTZ7.js";import{a as te}from"./chunk-LSHIR6QM.js";import{i as ne}from"./chunk-OPUIFAQS.js";import{A as X,C as Z,E as Pe}from"./chunk-EGFVGCDG.js";import{x as de}from"./chunk-YFLVGOCJ.js";import{b as Oe}from"./chunk-FN462OVO.js";import{a as l}from"./chunk-ZDIWOE4Q.js";import{h as W}from"./chunk-FYD7CMS7.js";import{b as be}from"./chunk-B4SM2KRI.js";import{b as n}from"./chunk-XVCSRZX4.js";import{a as pe}from"./chunk-DSPLGTQI.js";var g=x.options,Qe=n.discriminatedUnion("operation",[g[1].omit({customerToken:!0}),g[2].omit({customerToken:!0}),g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0}),g[8].omit({customerToken:!0}),Ee.omit({customerToken:!0})]),me=n.strictObject({receiptId:n.uuid(),operationId:n.uuid()}),nt=n.discriminatedUnion("operation",[n.strictObject({operation:n.literal("find_purchase")}),n.strictObject({operation:n.literal("recover_start"),intent:n.enum(["lookup","resume","start"]),start:n.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),n.strictObject({operation:n.literal("recover_run"),runId:n.uuid(),funnelId:n.uuid()}),n.strictObject({operation:n.literal("recover_purchase"),runId:n.uuid(),funnelId:n.uuid(),purchase:me}),n.strictObject({operation:n.literal("terminate_checkout"),runId:n.uuid(),funnelId:n.uuid(),purchase:me}),n.strictObject({operation:n.literal("settle_command"),runId:n.uuid(),funnelId:n.uuid(),requestId:n.uuid(),command:n.discriminatedUnion("operation",[g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0})]).optional()}).refine(a=>!a.command||a.requestId===a.command.requestId),n.strictObject({operation:n.literal("run_command"),runId:n.uuid(),funnelId:n.uuid(),command:Qe})]),re=n.strictObject({runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),startRequestId:n.uuid(),runExpiresAt:n.iso.datetime({offset:!0}),status:D.shape.run.shape.status}),j={scope:W,customerId:n.uuid()},je=n.discriminatedUnion("outcome",[n.strictObject({...j,outcome:n.literal("unknown"),target:n.null(),view:n.null(),access:n.null()}),n.strictObject({...j,outcome:n.literal("resolved"),target:re,view:D.shape.run.nullable(),access:n.discriminatedUnion("type",[n.strictObject({type:n.literal("customer")}),n.strictObject({type:n.literal("operation_only"),cause:n.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((a,d)=>{a.outcome==="resolved"&&(a.access.type==="customer"!=(a.view!==null)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Te=n.strictObject({...j,target:re,view:D.shape.run.nullable(),settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),acceptance:n.enum(["accepted","not_accepted","unknown"]),receiptPhase:n.enum(["accepted","processing","done"]).nullable(),basis:n.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:n.uuid().nullable(),operationId:n.uuid().nullable()}),purchase:D.shape.purchase.unwrap().nullable()}).superRefine((a,d)=>{let m=a.settlement;(m.acceptance==="accepted"!=(m.receiptPhase!==null)||m.acceptance==="accepted"&&m.basis!=="receipt"||m.acceptance==="unknown"&&(m.state!=="unknown"||m.basis!=="none")||m.acceptance!=="accepted"&&(m.operationId!==null||m.receiptId!==null)||m.acceptance==="not_accepted"&&(m.state!=="settled"||!["run_terminal","position_advanced"].includes(m.basis))||a.purchase&&(a.purchase.receiptId!==m.receiptId||a.purchase.operation&&a.purchase.operation.operationId!==m.operationId||a.purchase.quote&&a.purchase.quote.operationId!==m.operationId)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ue=n.strictObject({...j,target:re,purchase:D.shape.purchase.unwrap()}).superRefine((a,d)=>{(!a.purchase.operation||typeof a.purchase.canReselect!="boolean"||a.purchase.quote&&a.purchase.quote.operationId!==a.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),xe=n.discriminatedUnion("outcome",[n.strictObject({...j,outcome:n.literal("none")}),n.strictObject({...j,outcome:n.literal("blocked")}),n.strictObject({...j,outcome:n.literal("found"),target:re,start:n.strictObject({locale:g[0].shape.locale,parameters:g[0].shape.parameters}),purchase:me})]);var Ye=x.options[0].refine(a=>!a.customer&&!a.customerData),Je=n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),terminal:n.enum(["complete","native"]).nullable()}),De=n.strictObject({schemaVersion:n.literal(1),baseUrl:n.url(),scope:W,customerId:n.uuid(),sessionId:n.uuid(),start:Ye,allowed:n.array(n.enum(["merchant","record_only","indiana","native"])),run:n.strictObject({id:n.uuid(),versionId:n.uuid(),status:Re.shape.status,revision:n.number().int().nonnegative(),runExpiresAt:n.iso.datetime({offset:!0}).optional()}).optional(),purchases:n.array(Je).max(100),operationCommand:n.strictObject({operationId:n.uuid(),intent:n.literal("confirm")}).optional(),journal:n.strictObject({revision:n.number().int().nonnegative(),entry:ke.nullable()})});function He(a){return Fe({...a,namespace:"purchases",identity:[a.scope.projectId,a.scope.environment,a.customerId]})}function Le(a){let d=new URL(a.baseUrl??be).href,m=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function P(){a.assertCurrent();try{let v=await a.storage.read();if(a.assertCurrent(),!Number.isSafeInteger(v.revision)||v.revision<0)throw m();let s=v.entry===null?null:De.parse(v.entry);if(s&&(s.baseUrl!==d||s.customerId!==a.customerId||s.scope.projectId!==a.scope.projectId||s.scope.environment!==a.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(s?.journal.entry&&(s.journal.entry.scope.projectId!==s.scope.projectId||s.journal.entry.scope.environment!==s.scope.environment||s.journal.entry.funnelId!==s.start.funnelId||s.journal.entry.runId!==s.run?.id||s.journal.entry.versionId!==s.run?.versionId)||s?.operationCommand&&!s.purchases.some(E=>E.operationId===s.operationCommand?.operationId))throw m();return{revision:v.revision,entry:s}}catch(v){throw v instanceof l?v:m()}}async function z(v){for(let s=0;s<8;s++){let E=await P(),O=v(structuredClone(E.entry));if(JSON.stringify(O)===JSON.stringify(E.entry))return O;O&&De.parse(O),a.assertCurrent();let R;try{R=await a.storage.write(E.revision,O)}catch{throw m()}if(a.assertCurrent(),R!==null){if(!Number.isSafeInteger(R)||R<=E.revision)throw m();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:P,update:z,baseUrl:d}}var Ke=5*6e4;function $e(a,d){let m=a.purchases.find(P=>P.type==="checkout");if(!a.actions.includes("continue_checkout")||m?.type!=="checkout"||d!==void 0&&m.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return m.checkoutUrl}function kt(a){let d={...a,scope:{...a.scope},executionPolicy:structuredClone(a.executionPolicy)},m=d.session.snapshot();if(!m)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:P,sessionId:z}=m,v=!1,s=null,E,O=null,R=!1,F,B,Q,k={mode:"idle",status:"idle",actions:["start"],purchases:[]},S=new Map,T=new Map,fe=new AbortController,Y=new Set,H=Oe(d),J=_e(H.request);function L(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function y(){if(v||d.session.snapshot()?.customerId!==P)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let h=Le({...d,customerId:P,assertCurrent:y,storage:d.storage??He({baseUrl:d.baseUrl,scope:d.scope,customerId:P})}),Ve=d.session.subscribeIdentity(he);function he(){v||(v=!0,clearTimeout(Q),fe.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),Ve(),s?.reset(),s=null,O=null,H.dispose(),Y.clear(),S.clear(),T.clear())}function C(e){y();let t=JSON.stringify(e)!==JSON.stringify(k);k=e,clearTimeout(Q),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Q=setTimeout(()=>{U().catch(()=>{})},5e3)),t&&pe(d.onRecovery,structuredClone(e));for(let r of t?Y:[]){if(v)break;pe(r,structuredClone(e))}return structuredClone(e)}function I(e){if(y(),!e||e.start.requestId!==E)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function b(e){let t=[...e.purchases],r=e.journal.entry?.purchase;return r&&!t.some(o=>o.operationId===r.operationId)&&t.push({receiptId:r.receiptId,operationId:r.operationId,terminal:null}),t}function A(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&b(e).every(t=>t.terminal!==null)}function _(e,t){let r=e.journal.entry?.command??e.journal.entry?.closeCommand,o=b(e).map(w=>{let le=S.get(w.operationId);return w.terminal&&!le?{type:w.terminal,operationId:w.operationId}:te({quote:le?.quote??null,operation:le??null,requestId:r?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(w.operationId)===!0})}),u=o.filter(w=>!["complete","native"].includes(w.type)),i=u[0],c=u.length===1&&i?.operationId?S.get(i.operationId):void 0;if(c&&(i?.type==="checkout"||i?.type==="cancel"))try{ee({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},c.quote)}catch(w){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:L(w)}}let f;if(t==="operation"&&!r&&i?.type==="cancel"&&c?.quote&&!c.problem&&!c.confirmedAt)try{ee({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},c.quote),Date.parse(c.quote.expiresAt)>Date.now()&&(f={operationId:c.operationId,quote:c.quote})}catch{}let p=o.length>0&&u.length===0,N=A(e)||t==="operation"&&p&&!r&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":r||e.operationCommand||i&&i.type!=="cancel"||t==="operation"&&!f?"waiting_result":"ready";return{mode:t,status:N,purchases:o,...f?{confirmation:structuredClone(f)}:{},actions:["refresh",...A(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:f?["confirm"]:[],...u.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function oe(e){let t=te({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function ae(e){if(!e.operation)return;let t=X.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==P)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let r=ne(S.get(t.operationId)??null,t);S.set(t.operationId,r),r===t&&T.set(t.operationId,e.canReselect===!0)}async function Ge(e){y();for(let r of[e.purchase,e.run.paywall])r&&ae(r);let t=await h.update(r=>{if(I(r),r.run&&(r.run.id!==e.run.id||r.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=b(r);for(let u of[e.purchase,e.run.paywall]){let i=u?.operation?.operationId??u?.quote?.operationId;if(!u||!i)continue;let c=o.find(p=>p.operationId===i);if(c&&c.receiptId!==u.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let f=oe(S.get(i));c?c.terminal??=f:o.push({receiptId:u.receiptId,operationId:i,terminal:f})}return{...r,purchases:o,run:r.run&&(r.run.revision>e.run.revision||!["running","waiting"].includes(r.run.status)&&["running","waiting"].includes(e.run.status))?r.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});I(t),t.run&&!["running","waiting"].includes(t.run.status)&&b(t).some(r=>!r.terminal)&&(t=await V(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(r=>!!r)))),I(t),C(_(t,"run"))}function Me(){return{async read(){let{entry:e}=await h.read();return I(e),structuredClone(e.journal)},async write(e,t){let r=null;return await h.update(o=>{if(I(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return r=null,o.journal.revision!==e?o:(r=e+1,{...o,journal:{revision:r,entry:t}})}),r}}}async function V(e,t=!1,r=new Set){I(e);let o=b(e);for(let i of o){if(i.terminal)continue;let c=r.has(i.operationId)?S.get(i.operationId):void 0;if(c??=await se(e,i),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(c.merchantExecution&&c.merchantExecution.customerId!==P)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&te({quote:c.quote??null,operation:c,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let f=Z(c)?await J.update({operationId:i.operationId,intent:"cancel"}):await J.attach({operationId:i.operationId,intent:"cancel"});if(c=X.parse(f.operation),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");c=await se(e,i)}S.set(i.operationId,ne(S.get(i.operationId)??null,c))}let u=await h.update(i=>{I(i);let c=i.operationCommand&&S.get(i.operationCommand.operationId);return{...i,...c&&(c.confirmedAt||c.merchantExecution||!Pe(c))?{operationCommand:void 0}:{},purchases:b(i).map(f=>({...f,terminal:f.terminal??oe(S.get(f.operationId))}))}});return I(u),u}async function G(e){y();let t=await H.request("funnels",e);return y(),t}async function ze(e){try{return await G(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return G({...e,intent:"resume"})}}async function Be(){let e=M(xe,await G({operation:"find_purchase"}));if(e.customerId!==P||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:r}=e;return await h.update(o=>o&&!A(o)?o:{schemaVersion:1,baseUrl:h.baseUrl,scope:d.scope,customerId:P,sessionId:z,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...r,terminal:null}],journal:{revision:0,entry:null}}),"found"}let K;function ie(e){let t=K;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<Ke))return t.job;let r={at:Date.now(),job:Be().then(o=>(r.outcome=o,r.at=Date.now(),o),o=>{throw K===r&&(K=void 0),o})};return K=r,r.job}async function se(e,t,r="recover_purchase"){let o=M(Ue,await G({operation:r,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId}}));if(ue(e,o),o.purchase.receiptId!==t.receiptId||o.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return ae(o.purchase),S.get(t.operationId)}async function Ie(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let r=M(Te,await G({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(ue(e,r),r.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");r.purchase&&ae(r.purchase);let o=await h.update(u=>{I(u);let i=b(u),{receiptId:c,operationId:f}=r.settlement;if(c&&f){let N=i.find(w=>w.operationId===f);if(N&&N.receiptId!==c)throw new l("INVALID_RESPONSE","Original Receipt changed");N||i.push({receiptId:c,operationId:f,terminal:oe(S.get(f))})}let p=r.settlement.state==="settled"?qe(u.journal.entry,t.requestId):u.journal.entry;return{...u,purchases:i,journal:p===u.journal.entry?u.journal:{revision:u.journal.revision+1,entry:p}}});I(o),e=o}return e}function ue(e,t){if(t.customerId!==P||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function ce(e,t){if(I(e),e.run&&(e=await Ie(e)),!b(e).length&&A(e))return C(_(e,"operation"));if(!b(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(t)});R=!0;let r=await V(e);return C(_(r,"operation"))}async function $(e,t=!1,r=!0){if(E=e.start.requestId,O=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!s){let o=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await ze(o)}catch(p){if(!e.run&&p instanceof l&&(p.status===void 0||p.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:L(p)});throw p}let i=M(je,u);if(i.customerId!==P||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});ue(e,i);let c=await h.update(p=>(I(p),{...p,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??p.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(I(c),e=c,i.access.type==="operation_only")return ce(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ie(e);let f=i.view;if(f.locale!==e.start.locale||!Ae(f.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");s=Ne({...d,customerRun:{runId:i.target.runId,customerId:P,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},funnelCommandStorage:Me(),onAcceptedResponse:Ge},{scope:i.scope,run:f})}try{await s.get(),s.view?.pendingRequest?.requestId===e.start.requestId&&!s.pendingCommands?.length&&await s.resume(s.view.pendingRequest.requestId);for(let u of s.pendingCommands??[])u.operation!=="close"&&await s.settle?.(u.requestId);s.pendingCommands?.length&&await s.retry(),y();let o=(await h.read()).entry;return I(o),C(_(o,"run"))}catch(o){if(y(),r&&o instanceof l&&(o.status===401||o.status===409&&o.reason==="STATE_CHANGED")){s.reset(),s=null;let u=(await h.read()).entry;return I(u),$(u,!1,!1)}throw o}}function q(e,t="read",r){if(y(),F)return t==="read"||t===B?F:F.then(()=>q(e,t,r),()=>q(e,t,r));clearTimeout(Q);let o=e().catch(u=>{throw!v&&!r?.(u)&&C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:k.purchases,error:L(u)}),u});return F=o,B=t,o.then(()=>{F===o&&(F=void 0,B=void 0)},()=>{F===o&&(F=void 0,B=void 0)}),o}function U(){return q(async()=>{let{entry:e}=await h.read();if(!e||A(e)){if(await ie(!1)==="blocked")return we();({entry:e}=await h.read())}return e?(E&&e.start.requestId!==E&&(s?.reset(),s=null,S.clear(),T.clear(),R=!1),R&&E===e.start.requestId?ce(e,k.error):$(e)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function we(){return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function ye(){let e=await U();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:q(async()=>{let t=(await h.read()).entry;if(I(t),!R){if(!s?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=s.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(Z(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return C(_(t,"run"));if(s.pendingCommands?.length)await s.retry();else{let w=s.view;await s.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:w.nodeId,visit:w.visit,revision:w.revision,input:{type:"paywall_confirm",operationId:w.paywall.quote.operationId,...w.paywall.quote.merchantTerms?{merchantConfirmation:de(w.paywall.quote.merchantTerms)}:{}}})}let N=(await h.read()).entry;return I(N),C(_(N,"run"))}let r=t.operationCommand?.operationId??k.confirmation?.operationId,o=r&&S.get(r);if(!r||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");ee({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await h.update(p=>{if(I(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==r)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:r,intent:"confirm"}}});let u={operationId:r,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:de(o.quote.merchantTerms)}:{}},i=Z(o)?await J.update(u):await J.attach(u),c=X.parse(i.operation);if(y(),i.operation.operationId!==r)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");S.set(r,ne(o,c));let f=(await h.read()).entry;return I(f),C(_(await V(f,!1,new Set([r])),"operation"))},"confirm")}async function ge(){y();let{entry:e}=await h.read();return e?A(e)?"finished":"pending":"none"}return{get controller(){return s},get recovery(){return structuredClone(k)},get attempt(){return y(),structuredClone(O)},get identitySignal(){return fe.signal},get customerId(){return P},retained:ge,async findPurchase(){let e=await ge();if(e==="pending")return e;let t=await ie(!0);return y(),t==="none"?e:t},async readPaywall(e){y();let t=Se(e),[r,{readPaywallContent:o},{validateResourceCheck:u}]=await Promise.all([Ce(H.request,"resolvePaywall"),import("./paywall-content-SML4CL2Q.js"),import("./check-response-MCT5RGOM.js")]);y();let i=r.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),c=await ve(H.request,r,i);u(i,c.paywall.check,c.scope);let f=await o(d,c.paywall);if(y(),t.paywallVersionId?f.id!==t.paywallVersionId:f.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return f},start(e){let t=x.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return q(async()=>{let r=(await h.read()).entry;if((!r||A(r))&&await ie(!0)==="blocked")return we();let o=await h.update(u=>{if(u&&!A(u)){if(u.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return u}return{schemaVersion:1,baseUrl:h.baseUrl,scope:d.scope,customerId:P,sessionId:z,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return E!==o.start.requestId&&(s?.reset(),s=null,S.clear(),T.clear(),R=!1),R?ce(o,k.error):$(o,!0)},`start:${t.funnelId}`)},refresh:U,confirm:ye,retry:()=>R?ye():q(async()=>{let{entry:e}=await h.read();return e?$(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return s?.view?q(async()=>{if(!s?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(s.pendingCommands?.find(r=>r.operation==="close"))await s.retry();else if(["running","waiting"].includes(s.view.status)){let r=s.view;await s.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:r.nodeId,visit:r.visit,revision:r.revision})}let t=(await h.read()).entry;return I(t),C(_(t,"run"))},"close"):U()},async continueCheckout(e,t){let r=t?await q(async()=>{let{entry:o}=await h.read();if(I(o),!o.run||!b(o).some(i=>i.operationId===t&&!i.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let u=await V(o);return C(_(u,R?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await U();y(),await e($e(r,t))},async terminateCheckout(e){let t=await U();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return q(async()=>{let{entry:o}=await h.read();I(o);let u=b(o).find(c=>c.operationId===e&&!c.terminal);if(!u||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await se(o,u,"terminate_checkout");let i=await V(o,!1,new Set([e]));return C(_(i,R?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return Y.add(e),()=>{Y.delete(e)}},destroy:he}}export{He as a,$e as b,kt as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as A}from"./chunk-W32FI2A2.js";import{b as D,e as L}from"./chunk-SLUA7ABW.js";import{d as T}from"./chunk-
|
|
1
|
+
import{a as A}from"./chunk-W32FI2A2.js";import{b as D,e as L}from"./chunk-SLUA7ABW.js";import{d as T}from"./chunk-GJSQZGBE.js";import{a as R}from"./chunk-DSPLGTQI.js";import{b as O}from"./chunk-A5KU4MMN.js";var m=new WeakMap;function B(e){let o=e.view,n=o?.paywall?.resolution;if(!o||!["running","waiting"].includes(o.status)||o.stopped||!n||"document"in n||!e.resolvePaywall||e.identitySignal?.aborted)return;let a=JSON.stringify(n);if(m.get(e)?.key===a)return;let i=JSON.parse(a),c=e.identitySignal,u=Promise.resolve().then(async()=>{c?.throwIfAborted();let v=await e.resolvePaywall(i);return c?.throwIfAborted(),v}),f={key:a,content:u};return m.set(e,f),u.catch(()=>{}),()=>{m.get(e)===f&&m.delete(e)}}function Q(e,o){let n=m.get(e);return m.delete(e),n?.key===JSON.stringify(o)?n.content:e.resolvePaywall(o)}function re(e){if(!e.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let o=e.client.pageExperiments.bind(e.client),n=!1,a=!1,i=0,c=!1,u=!1,f="",v=()=>{let t=e.client.view;return JSON.stringify([t?.id,t?.source.versionId,t?.visit,t?.revision,t?.status,t?.stopped])},s=new Map,x=new Set,q={},d=new Map,U=D(e.appManifestRelease),C=()=>{for(let t of s.values())t.effect.revert();s.clear()},g=()=>{C();for(let t of d.values())t();d.clear()};function E(t){if(n||x.has(t))return;x.add(t);let h=i;o(e.appManifestRelease,[t]).catch(k=>{x.delete(t),!n&&h===i&&R(e.onError,k)})}async function w(){if(n)return;f=v();let t=e.client.view;if(!t||t.stopped||!["running","waiting"].includes(t.status)){i++,g();return}if(document.visibilityState==="hidden")return;if(c){u=!0;return}c=!0;let h=++i,k=`${t.id}:${t.visit}:${t.revision}`,W=location.href;try{let[P,{applyVisualVariation:j}]=await Promise.all([o(e.appManifestRelease),import("./visual-dom-IN6DRNX3.js")]),p=e.client.view;if(n||h!==i||!p||p.stopped||!["running","waiting"].includes(p.status)||`${p.id}:${p.visit}:${p.revision}`!==k||location.href!==W)return;let $=new Set,I=new Set;for(let r of P.assignments){let l=`${P.payload.environmentId}:${r.experimentKey}`;if(I.add(l),d.has(l)||d.set(l,L(l,q)),!!r.inExperiment)for(let y of P.payload.experiments){if(y.key!==r.experimentKey||!O(location.href,y.urlPatterns??[]))continue;let z=y.meta?.findIndex(F=>F.key===r.variationKey)??-1,S=y.variations[z];if(!S?.renderGuard)continue;let b=r.receiptId+":"+y.changeId,J=JSON.stringify([r.variationKey,S]);$.add(b);let N=s.get(b);if(N?.signature===J){N.effect.applied&&E(r.receiptId);continue}s.get(b)?.effect.revert(),s.delete(b);let K=j(S,{requireUniqueTargets:!0,boundVariations:y.variations,allowJs:!1,onApplied:()=>E(r.receiptId),onError:F=>R(e.onError,F)});s.set(b,{signature:J,effect:K}),K.applied&&E(r.receiptId)}}for(let[r,l]of s)$.has(r)||(l.effect.revert(),s.delete(r));for(let[r,l]of d)I.has(r)||(l(),d.delete(r))}catch(P){h===i&&g(),!n&&h===i&&R(e.onError,P)}finally{c=!1,u&&!n&&(u=!1,w())}}let G=e.client.subscribe(()=>{if(v()===f)return;f=v(),i++;let t=e.client.view;(!t||t.stopped||!["running","waiting"].includes(t.status))&&g(),a&&w()}),H=T(()=>{i++,g(),a&&w()}),V=()=>{i++,C()};document.addEventListener("visibilitychange",V);let M=A({document,run:async()=>{a&&await w()},delay:()=>a&&!n?15e3:void 0});return{async start(){a||n||(a=!0,await M.refresh())},refresh:w,destroy(){n=!0,i++,M.destroy(),document.removeEventListener("visibilitychange",V),G(),H(),g(),U.destroy()}}}export{B as a,Q as b,re as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as n,r as t}from"./chunk-3TSFGU4T.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as w,f as b}from"./chunk-HYCLLEFU.js";import{n as h,s as u}from"./chunk-KSME3N3A.js";import{a as y}from"./chunk-
|
|
1
|
+
import{e as w,f as b}from"./chunk-HYCLLEFU.js";import{n as h,s as u}from"./chunk-KSME3N3A.js";import{a as y}from"./chunk-FN462OVO.js";import{a as n}from"./chunk-ZDIWOE4Q.js";import{a as g}from"./chunk-3VUPVXAV.js";import{b as f}from"./chunk-B4SM2KRI.js";function p(r,s){let a=typeof r=="string"?new TextEncoder().encode(r):r;return a.byteLength===s.byteLength&&u(a)===s.sha256}async function _(r,s){let a=w.parse(s),{artifact:i,environmentId:P}=a.content,m=new y(r.baseUrl??f).origin,e=new y(i.url,m);if(e.origin!==m||e.username||e.password||e.search||e.hash||e.pathname!==`/api/v1/configuration/${P}/artifacts/${i.sha256}`)throw new n("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,d,I=new Promise((t,l)=>{d=setTimeout(()=>{let c=new n("TIMEOUT","Public Paywall read timed out");o.abort(c),l(c)},h.initializationMs)}),E=(async()=>{let t=await(r.fetch??globalThis.fetch)(e,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(t.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!t.ok||!t.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(t.headers.get("content-length"))>i.byteLength)throw t.body?.cancel().catch(()=>{}),new n("INVALID_RESPONSE","Public Paywall is unavailable");let l=await g(t,i.byteLength,{signal:o.signal,error:c=>new n("INVALID_RESPONSE",c==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!p(l,i))throw new n("INVALID_RESPONSE","Public Paywall digest or size changed");return b(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))})();try{return await Promise.race([E,I])}finally{clearTimeout(d)}}export{p as a,_ as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as p}from"./chunk-VKFLQEW4.js";import{c as g}from"./chunk-Y2ASROJH.js";import{b as B}from"./chunk-RFWVXTZ7.js";import{b as F}from"./chunk-
|
|
1
|
+
import{e as p}from"./chunk-VKFLQEW4.js";import{c as g}from"./chunk-Y2ASROJH.js";import{b as B}from"./chunk-RFWVXTZ7.js";import{b as F}from"./chunk-US65SQX4.js";import{a as $}from"./chunk-LSHIR6QM.js";import{e as Y,f as X,g as Z,h as ee,i as re}from"./chunk-OPUIFAQS.js";import{b as j}from"./chunk-HYX3EDZS.js";import{A as x,B as R,E as K,z as J}from"./chunk-EGFVGCDG.js";import{x as G}from"./chunk-YFLVGOCJ.js";import{b as W}from"./chunk-FN462OVO.js";import{a as M}from"./chunk-FRRKTQNZ.js";import{t as H}from"./chunk-MQ5LJEWV.js";import{a}from"./chunk-ZDIWOE4Q.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{i as ie}from"./chunk-
|
|
1
|
+
import{i as ie}from"./chunk-67LPUJMN.js";import{a as Z,c as ee,e as te,f as ne,h as N,j as re,k as oe,l as se}from"./chunk-2G23BYBI.js";import{b as X}from"./chunk-HP6OV6WF.js";import{r as V}from"./chunk-KSME3N3A.js";import"./chunk-LE32WTZ7.js";import"./chunk-IDDPWGQE.js";import"./chunk-HYX3EDZS.js";import"./chunk-EGFVGCDG.js";import"./chunk-YFLVGOCJ.js";import"./chunk-VILB5M4X.js";import"./chunk-FN462OVO.js";import"./chunk-FRRKTQNZ.js";import{o as Y,p as K}from"./chunk-MQ5LJEWV.js";import{A as G}from"./chunk-JDIFYMSA.js";import"./chunk-TNPBYYAX.js";import"./chunk-KCN6OGYG.js";import{c as $,d as R}from"./chunk-PF6PRPRO.js";import{a as p}from"./chunk-ZDIWOE4Q.js";import"./chunk-FYD7CMS7.js";import"./chunk-B4SM2KRI.js";import{b as u}from"./chunk-XVCSRZX4.js";import{a as h}from"./chunk-DSPLGTQI.js";import"./chunk-A5KU4MMN.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";var z=new WeakMap;function ce(s){let t={string:u.string(),number:u.number().finite(),boolean:u.boolean(),strings:u.array(u.string()),json:R}[s.type];return s.nullable?t.nullable():t}function ae(s,t){let f=u.record(u.string(),R).parse(s);if(Object.keys(f).length>40)throw new p("INVALID_REQUEST","Too many content inputs");for(let[m,r]of Object.entries(f))Y.parse({[m]:r});if(Object.keys(f).some(m=>!Object.hasOwn(t.inputs,m)))throw new p("INVALID_REQUEST","Undeclared content input");for(let[m,r]of Object.entries(t.inputs))if(Object.hasOwn(f,m))ce(r).parse(f[m]);else if(r.required)throw new p("INVALID_REQUEST",`Missing content input ${m}`);return f}async function Ae(s,t){return le(s,t,!1)}async function Se(s,t){return le(s,t,!0)}async function le(s,t,f){t.signal?.throwIfAborted();let m=X.parse(t.content),r=m.document;if(t.closeControl==="content"&&!r.screen.actions.some(e=>e.type==="event"&&e.close))throw new p("INVALID_REQUEST","An authored Close control requires a declared Close action");if(z.has(s))throw new p("CONFLICT","Content is already mounted in this container");let y=ae(t.inputs??{},r.contract),T=new Set(u.array(u.string()).max(40).parse(t.mutableInputs??[]));if(T.size!==(t.mutableInputs?.length??0)||[...T].some(e=>!Object.hasOwn(r.contract.inputs,e)))throw new p("INVALID_REQUEST","Mutable content inputs must name unique declared inputs");for(let e of Object.keys(r.contract.outputs))if(typeof t.actions[e]!="function")throw new p("INVALID_REQUEST",`Missing host handler for ${e}`);let M=K.parse(t.bindings??[]),d=s.ownerDocument,ue=s.clientHeight||d.defaultView?.innerHeight||800,P,w,a,_,x=r.kind==="popup",n=x?d.createElement("dialog"):null,c=d.createElement("div");if(c.dataset.indianaContent=r.kind,c.setAttribute("aria-label",r.name),c.style.cssText="width:100%;min-width:0",n){n.setAttribute("aria-label",r.name);let e=r.screen.presentation;n.style.cssText="box-sizing:border-box;padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto",e.type==="modal"||e.type==="sheet"?(n.style.width=`${$[e.size]}px`,e.type==="sheet"&&(n.style.margin="auto auto 0")):n.style.width="100vw",a=ee(n,r.screen,()=>{w?.resizeViewport(d.defaultView?.innerHeight||800,d.defaultView?.innerWidth||1024)}),n.append(c),s.append(n)}else s.append(c);let i=!1,A=!1,E=!1,S=!1,de=n?oe(n):se(c,s),D=re(s,t,r.kind,()=>{k()&&(b(),h(t.onDismiss))}),q,H,L=new Promise((e,o)=>{q=e,H=o});L.catch(()=>{});let g=null,I=structuredClone(r.screen),W=G(I,[t.locale,...d.defaultView?.navigator.languages??[]]),j=t.capabilities;I.actions=I.actions.map(e=>e.type==="event"?{...e,close:!1}:e);function b(){i||(i=!0,t.signal?.removeEventListener("abort",b),D.finish("dismissed"),H(new Error("Content preparation cancelled")),a?.destroy(),_?.(),w?.destroy(),n?.close(),n?.remove(),c.remove(),z.delete(s),n&&P?.())}let v=()=>{!E||!k()||(b(),h(t.onDismiss))};function k(){try{return t.canDismiss?.()!==!1}catch(e){return h(t.onError,e),!1}}if(n&&t.closeControl!=="content"){let e=d.createElement("button");e.type="button",e.textContent="×",e.setAttribute("aria-label",t.locale?.startsWith("zh")?"关闭":"Close"),ne(e,r.screen.theme),e.addEventListener("click",v),n.prepend(e)}n&&a?.responsive&&(_=Z(n,v,k,t.locale?.startsWith("zh")?"关闭":"Close"),n.addEventListener("click",e=>{if(e.target!==n)return;let o=n.getBoundingClientRect();(e.clientX<o.left||e.clientX>o.right||e.clientY<o.top||e.clientY>o.bottom)&&v()})),n?.addEventListener("cancel",e=>{e.preventDefault(),v()}),n?.addEventListener("keydown",e=>{e.key==="Escape"&&(e.preventDefault(),v())});async function F(){if(i||!E||A||!g)return;let e=g;A=!0,c.setAttribute("aria-busy","true");try{await t.actions[e.actionId](structuredClone(e)),g=null}catch(o){i||h(t.onError,o)}finally{A=!1,i||c.removeAttribute("aria-busy")}}function J(){if(i)throw new p("CONFLICT","Content host has been destroyed");E||!S||(P??=N(d),D.present(e=>{de(),n&&(a?.latch(),n.showModal(),a?.responsive&&n.focus({preventScroll:!0}),!e&&t.loading!=="host"&&te(n,a?.type??r.screen.presentation.type,a?.responsive)),E=!0}))}function U(e){D.finish("error",e),H(e instanceof Error?e:new Error(String(e))),b()}let Q={destroy:b,show:J,get pendingAction(){return g?structuredClone(g):null},retryAction:F,updateInputs(e){if(i)throw new p("CONFLICT","Content host has been destroyed");let o=u.record(u.string(),R).parse(e),C=ae({...y,...o},r.contract);for(let l of Object.keys(o))if(!T.has(l)&&(!Object.hasOwn(y,l)||V(y[l])!==V(C[l])))throw new p("PRECONDITION_FAILED","This content input is frozen; prepare a new presentation");V(y)!==V(C)&&(w?.update(I,W,{capabilities:j,serverInput:{bindings:M,answers:{},values:C}}),y=C)},updateCapabilities(e){if(i)return;let o=structuredClone(e);w?.updateCapabilities(o),j=o}};z.set(s,Q),t.signal?.addEventListener("abort",b,{once:!0});try{if(t.signal?.throwIfAborted(),f||(P=N(d),D.start(x,t.locale??r.screen.strings.defaultLocale),i&&await L),w=ie(c,{mode:"live",rendererUrl:t.rendererUrl,title:r.name,viewportHeight:r.kind==="page"?ue:a?.responsive?d.defaultView?.innerHeight||800:void 0,...a?.responsive?{viewportWidth:d.defaultView?.innerWidth||1024,hostPresentation:()=>a.type}:{},onResize:e=>{i||a?.responsive&&(c.style.height=`${e}px`,c.style.overflow="clip",a.setContentHeight(e))},onRendered:e=>{if(!i&&(e&&n?.setAttribute("aria-label",e),!S))try{S=!0,f||J(),q()}catch(o){U(o),h(t.onError,o)}},onError:e=>{if(i)return;let o=new Error(e);S||U(o),h(t.onError,o)},onEscape:x?v:void 0,onAction:(e,o,C)=>{if(i||!E||A||g)return;let l=r.screen.actions.find(O=>O.id===e),B=r.contract.outputs[e];if(!(l?.type!=="event"||!B)&&!(l.close&&!k()))try{let O=ce(B).parse(Object.hasOwn(l.properties,"value")?l.properties.value:l.properties);g=structuredClone({requestId:crypto.randomUUID(),contentVersionId:m.id,actionId:e,event:l.event,value:O,selection:o??{},answers:C??{},requestedClose:l.close}),F()}catch(O){h(t.onError,O)}}}),w.update(I,W,{capabilities:j,serverInput:{bindings:M,answers:{},values:y}}),await Promise.race([w.ready,L]),f&&await L,i)throw new Error("Content preparation cancelled");return Q}catch(e){throw U(e),e}}export{Ae as mountContent,Se as prepareContent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as ne}from"./chunk-CGJZIDG3.js";import{b as J}from"./chunk-IXXVMGMF.js";import"./chunk-N3PZMMOO.js";import"./chunk-2LEDTNKQ.js";import{a as j}from"./chunk-7GU34JD4.js";import{b as ee}from"./chunk-MVUNV5XR.js";import"./chunk-TIUD3N72.js";import"./chunk-W32FI2A2.js";import{f as te,h as re,i as B,j as Y}from"./chunk-2G23BYBI.js";import"./chunk-3ITNAFAH.js";import"./chunk-2I2S5ZIH.js";import"./chunk-3TSFGU4T.js";import"./chunk-W3B4GT74.js";import"./chunk-Y2ASROJH.js";import"./chunk-US65SQX4.js";import"./chunk-HYCLLEFU.js";import"./chunk-KSME3N3A.js";import"./chunk-LE32WTZ7.js";import"./chunk-SZZIYCXK.js";import"./chunk-IDDPWGQE.js";import"./chunk-LSHIR6QM.js";import"./chunk-OPUIFAQS.js";import"./chunk-HYX3EDZS.js";import"./chunk-EGFVGCDG.js";import"./chunk-YFLVGOCJ.js";import"./chunk-VILB5M4X.js";import"./chunk-FN462OVO.js";import"./chunk-FRRKTQNZ.js";import"./chunk-MQ5LJEWV.js";import"./chunk-JDIFYMSA.js";import"./chunk-TNPBYYAX.js";import"./chunk-KCN6OGYG.js";import"./chunk-PF6PRPRO.js";import{a as O}from"./chunk-ZDIWOE4Q.js";import"./chunk-FYD7CMS7.js";import"./chunk-SLUA7ABW.js";import"./chunk-GJSQZGBE.js";import"./chunk-3VUPVXAV.js";import"./chunk-B4SM2KRI.js";import"./chunk-XVCSRZX4.js";import{a as w}from"./chunk-DSPLGTQI.js";import"./chunk-A5KU4MMN.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";function ae(I,e){let i=I.ownerDocument,p=(e.locale??i.documentElement.lang).startsWith("zh"),q=re(i),P=e.retained?.dialog??i.createElement("dialog"),x=i.createElement("section"),h=i.createElement("h2"),d=i.createElement("p"),f=i.createElement("button"),v=i.createElement("button"),t=i.createElement("button");h.textContent=e.retained?.dialog.getAttribute("aria-label")||(p?"购买状态":e.retained?"Purchase status":"Your purchase"),h.style.cssText="margin:0;font-size:20px;line-height:1.3",P.setAttribute("aria-label",h.textContent),e.retained||(P.style.cssText="box-sizing:border-box;width:min(640px,calc(100% - 32px));max-height:calc(100dvh - 32px);border:0;border-radius:16px;background:Canvas;color:CanvasText;padding:0"),x.style.cssText="padding:24px 56px 24px 24px;font:14px/1.5 system-ui,sans-serif",f.textContent="×",f.setAttribute("aria-label",p?"关闭":"Close"),te(f,{background:"Canvas",text:"CanvasText"}),d.setAttribute("role","status"),t.textContent=p?"查询状态":"Check status";for(let o of[f,v,t])o.type="button";for(let o of[v,t])o.style.cssText="min-height:44px;padding:8px 14px;margin-inline-end:8px;border:1px solid ButtonBorder;border-radius:8px;font:inherit;cursor:pointer";x.append(h,f,d,v,t),P.append(x);let s=!1,y=!1,m=e.checking===!0,C=!1,g=e.initialState;function D(o){if(s)return;g=o;let n=g.actions.includes("continue_checkout"),F=e.allowConfirm&&g.actions.includes("confirm");v.hidden=m||!n&&!F,v.disabled=t.disabled=y||m,v.textContent=n?p?"继续付款":"Continue checkout":p?"确认购买":"Confirm purchase",d.textContent=m?p?"正在核对购买状态…":"Checking your purchase…":C||g.status==="blocked"?p?"暂时无法确认购买状态。请重试。":"We couldn’t check your purchase. Try again.":g.status==="complete"?p?"购买已处理。":"Your purchase has been processed.":n?p?"可以继续原订单付款。":"You can continue your original checkout.":p?"正在核对购买状态…":"Checking your purchase…"}async function A(o){if(!(s||y)){y=!0,C=!1,D(g);try{await o()}catch(n){s||(C=!0,w(e.onError,n))}finally{y=!1,D(e.client.recovery)}}}let T=()=>A(e.refresh),N=e.client.subscribe(D);function k(){s||(s=!0,e.signal.removeEventListener("abort",k),i.removeEventListener("visibilitychange",L),N(),e.retained?e.retained.release():(P.remove(),q()),e.onDismiss())}function L(){i.visibilityState==="visible"&&T()}f.onclick=k,P.addEventListener("cancel",o=>{o.preventDefault(),k()}),t.onclick=()=>{T()},v.onclick=()=>{A(async()=>{g.actions.includes("continue_checkout")?await e.client.continueCheckout(o=>{if(e.signal.throwIfAborted(),!s)return e.onCheckoutUrl?e.onCheckoutUrl(o):i.defaultView?.location.assign(o)}):e.allowConfirm&&g.actions.includes("confirm")&&await e.client.confirm()})},e.signal.addEventListener("abort",k,{once:!0}),i.addEventListener("visibilitychange",L),D(g);function S(){s||e.signal.aborted||(e.retained||(I.append(P),P.showModal?P.showModal():P.open=!0),f.focus({preventScroll:!0}))}return e.loading?.active?e.loading.present(S):S(),{destroy:k,refresh:T,update(o){m=!1,D(o)},get recovery(){let o=g.purchases.filter(n=>!["native","complete"].includes(n.type));return structuredClone(o.length===1?o[0]:{type:"recover",operationId:null,requestId:null})},async prepareFallback(){return{type:"recover",operationId:null,requestId:null}},async review(){},async exitReview(){},get unappliedDrafts(){return new Map}}}var M=new WeakMap,W=new WeakMap,K=new WeakSet;function be(I,e){let i=e.prepared,p=()=>{i&&!K.has(i)&&J(i)?.release()},q=M.get(e.client);if(q)return p(),q;let P=t=>({...t,requestId:t.requestId??crypto.randomUUID()}),x=e.allowNewPurchase!==!1&&e.start instanceof Promise?e.start:void 0,h=e.allowNewPurchase===!1||!e.start||e.start instanceof Promise?void 0:P(e.start);h&&i?.state==="ready"&&i.matches(h)&&i.open();let d=i&&(h&&(i.state==="preparing"||["shown","closed"].includes(i.state)&&i.matches(h))||x&&["preparing","ready"].includes(i.state))?i:void 0;d?K.add(d):p();let f=d&&J(d);f?.claim();let v=Promise.resolve().then(async()=>{let t=!1,s,y,m=0,C,g,D=!1,A=()=>{},T=()=>{},N,k=!1,L=!1,S,o=!1,n=e.signal?AbortSignal.any([e.signal,e.client.identitySignal]):e.client.identitySignal,F=()=>{M.get(e.client)===v&&M.delete(e.client),n.removeEventListener("abort",G),A(),T(),d&&K.delete(d),f?.release()};function Q(){if(S)return S;let r=new Promise(c=>S=c);return W.set(e.client,r),r.then(()=>{W.get(e.client)===r&&W.delete(e.client)}),M.get(e.client)===v&&M.delete(e.client),S}let u=Y(I,e,"funnel",()=>U(),j);function G(){U()}function U(r=!1){if(!t){if(t=!0,u.finish("dismissed"),s){s.destroy();return}if(r&&N){let c=Q();o=!0,N.then(async l=>{l.mode==="run"&&l.status!=="blocked"&&e.client.controller&&e.client.attempt?.requestId===h?.requestId&&await e.client.close()}).catch(()=>{}).finally(()=>{c(),w(e.onDismiss,null)}),F();return}F(),w(e.onDismiss,null)}}let z={destroy:()=>U(),refresh:()=>s?.refresh()??C??Promise.resolve(),get recovery(){return s?.recovery??{type:"recover",operationId:null,requestId:null}},prepareFallback:()=>s?.prepareFallback()??Promise.resolve({type:"recover",operationId:null,requestId:null}),review:(...r)=>s?.review(...r)??Promise.resolve(),exitReview:(...r)=>s?.exitReview(...r)??Promise.resolve(),get unappliedDrafts(){return s?.unappliedDrafts??new Map}};n.addEventListener("abort",G,{once:!0}),f&&(T=f.onClose(()=>{k?t||Q():U(!0)}));try{n.throwIfAborted();let r=e.client.controller?.view?.paywall?.resolution,c=r&&"document"in r?r.document:e.loadingDocument;u.start(!0,h?.locale??e.client.attempt?.locale??c?.screen.strings.defaultLocale,c??null);let l=x?u.wait(x.then(E=>E?P(E):null,()=>null),B):Promise.resolve(h??null);l.catch(()=>{}),d?.state==="shown"?(L=!0,u.present(()=>{})):d&&["preparing","ready"].includes(d.state)&&Promise.all([d.ready,l.catch(()=>null)]).then(([E,a])=>{if(E){if(t||!u.active||!a||!d.matches(a)||!f?.revealable)return f?.release();u.present(()=>{d.open()==="shown"?L=!0:f.release()})}});let R=W.get(e.client);if(R&&await u.wait(R),t)return null;if(n.throwIfAborted(),x){let E=await l;if(t)return null;if(n.throwIfAborted(),!E)return u.finish("skipped"),F(),null;h=E}N=h?e.client.start(h):e.client.refresh();let H=await u.wait(N,B);return t?null:(n.throwIfAborted(),await V(H,u))}catch(r){if(o||S?.(),t)return null;throw u.finish("error",r),F(),w(e.onError,r),r}function X(r=!1){m++;let c=s;s=void 0,y=void 0,A(),A=()=>{};let l=r?c?.retainPurchaseDialog?.():void 0;return c?.destroy(),n.addEventListener("abort",G,{once:!0}),l}function Z(r,c,l=!1){if(t||n.aborted){c?.release();return}let R=++m;s=y=ae(I,{client:e.client,signal:n,loading:u,retained:c,checking:l,locale:e.client.attempt?.locale,onCheckoutUrl:e.onCheckoutUrl,onError:e.onError,refresh:$,initialState:r,allowConfirm:e.allowNewPurchase!==!1,onDismiss(){R===m&&(t=!0,F(),w(e.onDismiss,null))}})}function $(){if(C)return C;if(t||n.aborted)return Promise.resolve();if(!y){let l=X(!0)??f?.retainPurchaseDialog?.();l?Z(e.client.recovery,l,!0):(u=Y(I,e,"funnel",()=>U(),j),u.start(!0,e.client.attempt?.locale))}let r=Promise.resolve().then(async()=>{try{let l=await e.client.refresh();!t&&!n.aborted&&await V(l,u)}catch(l){!t&&!n.aborted&&(w(e.onError,l),await V({...e.client.recovery,mode:"blocked",status:"blocked"},u))}});C=r;let c=()=>{C===r&&(C=void 0)};return r.then(c,c),r}async function V(r,c){let l=e.client.controller;return r.mode==="run"&&r.status!=="blocked"&&l?(y&&X(),ie(l,c?.active?c:void 0)):r.purchases.length||r.status==="blocked"&&k?(y?y.update(r):Z(r,f?.retainPurchaseDialog?.()??u.retainPurchaseDialog()),z):y?(U(),null):(u.finish("skipped"),F(),(L||k)&&(t=!0,w(e.onDismiss,null)),null)}async function ie(r,c){n.removeEventListener("abort",G),k=!0;function l(){!t&&!n.aborted&&!D&&g&&e.client.recovery.status==="complete"&&(D=!0,w(e.onComplete,structuredClone(g)))}function R(a){if(n.throwIfAborted(),t)throw new DOMException("Presentation dismissed","AbortError");return e.onCheckoutUrl?e.onCheckoutUrl(a):I.ownerDocument.defaultView?.location.assign(a)}A(),A=e.client.subscribe(l);let H=++m,E=await ne(I,{...e,prepared:d,client:r,signal:n,checkoutNavigation:"after_confirmation",resumeCheckout:a=>e.client.continueCheckout(R,a),terminateCheckout:e.allowNewPurchase===!1?void 0:a=>e.client.terminateCheckout(a),async onCheckoutUrl(a){if(n.throwIfAborted(),t)throw new DOMException("Presentation dismissed","AbortError");let b=e.client.recovery;if((!b.actions.includes("continue_checkout")||!b.purchases.some(_=>_.type==="checkout"&&_.checkoutUrl===a))&&(b=await e.client.refresh(),n.throwIfAborted(),t))throw new DOMException("Presentation dismissed","AbortError");if(ee(b)!==a)throw new O("PURCHASE_PENDING","Checkout differs from the original recovery proof");return R(a)},async resolveOfferId(a){if(n.throwIfAborted(),t)throw new DOMException("Presentation dismissed","AbortError");let b=e.client.attempt;if(!b)throw new O("PURCHASE_PENDING","Read the original Start before selecting an offer");let _=await e.resolveOfferId?.(a,b);if(n.throwIfAborted(),t)throw new DOMException("Presentation dismissed","AbortError");if(e.client.attempt?.requestId!==b.requestId)throw new O("PURCHASE_STORAGE_CONFLICT","The original purchase changed while selecting an offer");return _},async resolveSubscriptionChange(a){n.throwIfAborted();let b=e.client.attempt;if(t||!b)throw new O("PURCHASE_PENDING","Read the original Start before selecting a membership");let _=await e.resolveSubscriptionChange?.(a);if(n.throwIfAborted(),t||e.client.attempt?.requestId!==b.requestId)throw new O("PURCHASE_STORAGE_CONFLICT","The original purchase changed while selecting a membership");return _},onPresentationState(a){H===m&&w(e.onPresentationState,a)},onComplete(a){H===m&&(g=a,l())},onError(a){H===m&&(w(e.onError,a),a instanceof O&&(a.status===401||a.status===409&&a.reason==="STATE_CHANGED"&&a.recovery==="recover_operation")&&!n.aborted&&$().catch(b=>w(e.onError,b)))},onDismiss(a){H===m&&(t=!0,F(),S?.(),w(e.onDismiss,a))}},c);return H!==m||t||n.aborted?(E.destroy(),t||n.aborted?null:z):(s=E,z)}});return M.set(e.client,v),v}export{be as showFunnelPurchase};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-
|
|
1
|
+
import{a,b,c}from"./chunk-IXXVMGMF.js";import"./chunk-N3PZMMOO.js";import"./chunk-2LEDTNKQ.js";import"./chunk-SZZIYCXK.js";import"./chunk-IDDPWGQE.js";import"./chunk-OPUIFAQS.js";import"./chunk-EGFVGCDG.js";import"./chunk-YFLVGOCJ.js";import"./chunk-VILB5M4X.js";import"./chunk-FRRKTQNZ.js";import"./chunk-JDIFYMSA.js";import"./chunk-TNPBYYAX.js";import"./chunk-KCN6OGYG.js";import"./chunk-PF6PRPRO.js";import"./chunk-ZDIWOE4Q.js";import"./chunk-FYD7CMS7.js";import"./chunk-XVCSRZX4.js";import"./chunk-DSPLGTQI.js";import"./chunk-A5KU4MMN.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";export{a as PRERENDER_MAX_AGE_MS,b as preparedInternals,c as prerenderFunnelPurchase};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b}from"./chunk-
|
|
1
|
+
import{a,b}from"./chunk-CGJZIDG3.js";import"./chunk-IXXVMGMF.js";import"./chunk-N3PZMMOO.js";import"./chunk-2LEDTNKQ.js";import"./chunk-7GU34JD4.js";import"./chunk-TIUD3N72.js";import"./chunk-W32FI2A2.js";import"./chunk-2G23BYBI.js";import"./chunk-W3B4GT74.js";import"./chunk-LE32WTZ7.js";import"./chunk-SZZIYCXK.js";import"./chunk-IDDPWGQE.js";import"./chunk-LSHIR6QM.js";import"./chunk-OPUIFAQS.js";import"./chunk-HYX3EDZS.js";import"./chunk-EGFVGCDG.js";import"./chunk-YFLVGOCJ.js";import"./chunk-VILB5M4X.js";import"./chunk-FN462OVO.js";import"./chunk-FRRKTQNZ.js";import"./chunk-MQ5LJEWV.js";import"./chunk-JDIFYMSA.js";import"./chunk-TNPBYYAX.js";import"./chunk-KCN6OGYG.js";import"./chunk-PF6PRPRO.js";import"./chunk-ZDIWOE4Q.js";import"./chunk-FYD7CMS7.js";import"./chunk-SLUA7ABW.js";import"./chunk-GJSQZGBE.js";import"./chunk-B4SM2KRI.js";import"./chunk-XVCSRZX4.js";import"./chunk-DSPLGTQI.js";import"./chunk-A5KU4MMN.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";export{a as showFunnelRun,b as showObservedFunnelRun};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { S as ScreenAnswers, P as PresentationLoadingOptions, s as screenInputBindingsSchema, a as SurfaceData, b as PaywallLoadingDocument, C as CustomerDataIntent, c as createPresentationLoading } from './presentation-loading-
|
|
3
|
-
export { d as PresentationState } from './presentation-loading-
|
|
2
|
+
import { S as ScreenAnswers, P as PresentationLoadingOptions, s as screenInputBindingsSchema, a as SurfaceData, b as PaywallLoadingDocument, C as CustomerDataIntent, c as createPresentationLoading, R as RetainedPurchaseDialog } from './presentation-loading-BWUNotNa.js';
|
|
3
|
+
export { d as PresentationState } from './presentation-loading-BWUNotNa.js';
|
|
4
4
|
import { J as JsonValue } from './growth-rules-B4YYy64R.js';
|
|
5
5
|
import { S as StackNode, a as ScreenSelection } from './screen-CJepeiBT.js';
|
|
6
6
|
import { C as ConfigurationSync } from './configuration-sync-DObsuVof.js';
|
|
@@ -1905,6 +1905,10 @@ type FunnelHostOptions = PresentationLoadingOptions & {
|
|
|
1905
1905
|
declare function showFunnelRun$1(container: HTMLElement, input: FunnelHostOptions, initialLoading?: ReturnType<typeof createPresentationLoading>): Promise<{
|
|
1906
1906
|
destroy: () => void;
|
|
1907
1907
|
refresh: () => Promise<void>;
|
|
1908
|
+
retainPurchaseDialog(): {
|
|
1909
|
+
dialog: HTMLDialogElement;
|
|
1910
|
+
release(): void;
|
|
1911
|
+
} | undefined;
|
|
1908
1912
|
readonly recovery: PaywallRecovery;
|
|
1909
1913
|
prepareFallback(): Promise<PaywallRecovery>;
|
|
1910
1914
|
review: (receiptId?: string) => Promise<void>;
|
|
@@ -1915,6 +1919,10 @@ declare function showFunnelRun$1(container: HTMLElement, input: FunnelHostOption
|
|
|
1915
1919
|
declare function showObservedFunnelRun(container: HTMLElement, input: FunnelHostOptions, initialLoading?: ReturnType<typeof createPresentationLoading>): Promise<{
|
|
1916
1920
|
destroy: () => void;
|
|
1917
1921
|
refresh: () => Promise<void>;
|
|
1922
|
+
retainPurchaseDialog(): {
|
|
1923
|
+
dialog: HTMLDialogElement;
|
|
1924
|
+
release(): void;
|
|
1925
|
+
} | undefined;
|
|
1918
1926
|
readonly recovery: PaywallRecovery;
|
|
1919
1927
|
prepareFallback(): Promise<PaywallRecovery>;
|
|
1920
1928
|
review: (receiptId?: string) => Promise<void>;
|
|
@@ -1937,7 +1945,8 @@ type FunnelPurchaseHostOptions = Omit<FunnelHostOptions, "client" | "checkoutNav
|
|
|
1937
1945
|
start?: FunnelPurchaseStart | Promise<FunnelPurchaseStart | null | undefined>;
|
|
1938
1946
|
resolveOfferId?: (purchase: Parameters<NonNullable<FunnelHostOptions["resolveOfferId"]>>[0], attempt: FunnelPurchaseAttempt) => ReturnType<NonNullable<FunnelHostOptions["resolveOfferId"]>>;
|
|
1939
1947
|
};
|
|
1940
|
-
type
|
|
1948
|
+
type RunHost = Awaited<ReturnType<typeof showObservedFunnelRun>>;
|
|
1949
|
+
type Host = Omit<RunHost, "retainPurchaseDialog">;
|
|
1941
1950
|
/**
|
|
1942
1951
|
* Same Controller/Host lifecycle; operation-only or blocked recovery goes to onRecovery. An
|
|
1943
1952
|
* unpaid original Checkout is recovered inside its Run's Paywall (Continue checkout, or another
|
|
@@ -2290,7 +2299,8 @@ declare function showPaywall(container: HTMLElement, options: PaywallHostOptions
|
|
|
2290
2299
|
readonly recovery: PaywallRecovery;
|
|
2291
2300
|
prepareFallback(): Promise<PaywallRecovery>;
|
|
2292
2301
|
setSuspended(value: boolean): void;
|
|
2293
|
-
destroy: (reason?: "destroy" | "dismiss" | "action") => void;
|
|
2302
|
+
destroy: (reason?: "destroy" | "dismiss" | "action", retainDialog?: boolean) => void;
|
|
2303
|
+
retainPurchaseDialog(): RetainedPurchaseDialog | undefined;
|
|
2294
2304
|
refresh: () => Promise<{
|
|
2295
2305
|
id: string;
|
|
2296
2306
|
paywallId: string;
|
|
@@ -2676,6 +2686,10 @@ declare function createPaywallSession(...args: Parameters<typeof createPaywallSe
|
|
|
2676
2686
|
declare function showFunnelRun(...args: Parameters<typeof showFunnelRun$1>): Promise<{
|
|
2677
2687
|
destroy: () => void;
|
|
2678
2688
|
refresh: () => Promise<void>;
|
|
2689
|
+
retainPurchaseDialog(): {
|
|
2690
|
+
dialog: HTMLDialogElement;
|
|
2691
|
+
release(): void;
|
|
2692
|
+
} | undefined;
|
|
2679
2693
|
readonly recovery: PaywallRecovery;
|
|
2680
2694
|
prepareFallback(): Promise<PaywallRecovery>;
|
|
2681
2695
|
review: (receiptId?: string) => Promise<void>;
|
|
@@ -2684,10 +2698,10 @@ declare function showFunnelRun(...args: Parameters<typeof showFunnelRun$1>): Pro
|
|
|
2684
2698
|
}>;
|
|
2685
2699
|
|
|
2686
2700
|
declare function showFunnelPurchase(...args: Parameters<typeof showFunnelPurchase$1>): Promise<{
|
|
2687
|
-
destroy: () => void;
|
|
2688
|
-
refresh: () => Promise<void>;
|
|
2689
2701
|
readonly recovery: PaywallRecovery;
|
|
2690
|
-
|
|
2702
|
+
refresh: () => Promise<void>;
|
|
2703
|
+
destroy: () => void;
|
|
2704
|
+
prepareFallback: () => Promise<PaywallRecovery>;
|
|
2691
2705
|
review: (receiptId?: string) => Promise<void>;
|
|
2692
2706
|
exitReview: () => Promise<void>;
|
|
2693
2707
|
readonly unappliedDrafts: Map<string, Record<string, string | boolean | string[]>>;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as En,c as bn}from"./chunk-5J2CFNYR.js";import{a as We,c as Rn}from"./chunk-K4TQ5REL.js";import{a as Ie}from"./chunk-W32FI2A2.js";import{a as pn,c as wn,d as Sn}from"./chunk-CGJMEKO2.js";import"./chunk-3ITNAFAH.js";import{a as In}from"./chunk-WEHUXUXS.js";import"./chunk-2I2S5ZIH.js";import{h as mn,i as vn,k as Pn}from"./chunk-PMUKZX2R.js";import{E as Ae,d as Xe,f as Qe,g as ge,h as ve,i as Ye,w as yn}from"./chunk-GMKLSHXK.js";import"./chunk-W3B4GT74.js";import{a as ze}from"./chunk-Y2ASROJH.js";import"./chunk-TIOPNTMP.js";import"./chunk-RFWVXTZ7.js";import"./chunk-XLTR45M5.js";import"./chunk-HYCLLEFU.js";import"./chunk-KSME3N3A.js";import{K as Ke}from"./chunk-LE32WTZ7.js";import"./chunk-SZZIYCXK.js";import"./chunk-IDDPWGQE.js";import{c as hn,e as gn}from"./chunk-LSHIR6QM.js";import"./chunk-OPUIFAQS.js";import"./chunk-HYX3EDZS.js";import{B as dn,C as ln,D as un,E as fn,c as an,d as sn,e as cn}from"./chunk-EGFVGCDG.js";import{A as Le,B as Be,D as He,F as qe,G as Ue,I as Ve,J as je,K as Ge,L as Je,M as Te,N as $e,z as _e}from"./chunk-YFLVGOCJ.js";import"./chunk-VILB5M4X.js";import{b as Ce}from"./chunk-KKKO6GZ5.js";import"./chunk-FRRKTQNZ.js";import"./chunk-MQ5LJEWV.js";import"./chunk-JDIFYMSA.js";import"./chunk-TNPBYYAX.js";import"./chunk-KCN6OGYG.js";import"./chunk-PF6PRPRO.js";import{a as G}from"./chunk-ZDIWOE4Q.js";import"./chunk-FYD7CMS7.js";import{a as be,c as de}from"./chunk-J6KIN4RH.js";import"./chunk-SLUA7ABW.js";import{c as we,d as Ee}from"./chunk-Z7ESO2IN.js";import"./chunk-3VUPVXAV.js";import"./chunk-ZS2AOY44.js";import{b as U}from"./chunk-XVCSRZX4.js";import{a as Z}from"./chunk-DSPLGTQI.js";import"./chunk-A5KU4MMN.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";var I=class extends Error{constructor(f,b=0,w=!1,h="fix_request"){super(f);this.code=f;this.status=b;this.retryable=w;this.recovery=h;this.name="MerchantBridgeError"}code;status;retryable;recovery};async function _n(n,d){if(!n.headers.get("content-type")?.split(";",1)[0].trim().match(/^application\/(?:json|[a-z0-9.+-]+\+json)$/i))throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let f=n.body?.getReader();if(!f)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let b=()=>{f.cancel().catch(()=>{})};d.addEventListener("abort",b,{once:!0});let w=0,h="",t=new TextDecoder("utf-8",{fatal:!0});try{for(d.throwIfAborted();;){let i=await f.read();if(d.throwIfAborted(),i.done)break;if(w+=i.value.byteLength,w>262144)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");h+=t.decode(i.value,{stream:!0})}return h+=t.decode(),JSON.parse(h)}catch(i){throw d.throwIfAborted(),i instanceof I?i:new I("MERCHANT_BRIDGE_INVALID_RESPONSE")}finally{d.removeEventListener("abort",b),await f.cancel().catch(()=>{}),f.releaseLock()}}function Tn(n){let d=qe.parse(n.origin),f=Ue.parse(n.manifest),b={projectId:n.scope.projectId,environmentId:n.scope.environmentId,environment:n.scope.environment};for(let m of["projectId","environmentId","environment"])if(f[m]!==n.scope[m])throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");let w=n.customerId===void 0?null:U.uuid().parse(n.customerId),h=0,t=null,i=null,u=new AbortController,y=n.fetch??globalThis.fetch;async function P(m,s,E,_,O){if(!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=He[m];if(["merchant_catalog_reader","merchant_refund_authority","indiana_server_key"].includes(S.authority))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);let l=h,o=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],..._?[_]:[]]);o.throwIfAborted();let T=new Headers(await n.headers?.());if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(/\bgg_(?:sk|ct|rt)_/.test(T.get("authorization")??"")||T.has("X-Indiana-Bridge-Signature")||T.has("X-Indiana-Bridge-Key-Id"))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);T.set(Be,String(_e)),T.set("Accept","application/json");let g=crypto.randomUUID();T.set("X-Request-Id",g),T.set("Content-Type","application/json");let M=await y(d+Le,{method:"POST",credentials:"include",redirect:"error",cache:"no-store",headers:T,signal:o,body:JSON.stringify({bridgeVersion:_e,requestId:g,command:S.command,scope:b,data:O??(E===void 0?{}:{operationId:E})})}),J=await _n(M,o);if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(!M.ok){let N=$e.safeParse(J);throw!N.success||N.data.scope.projectId!==n.scope.projectId||N.data.scope.environment!==n.scope.environment||N.data.scope.environmentId!==n.scope.environmentId||N.data.requestId!==g||N.data.command!==S.command?new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status):new I(N.data.error.code,M.status,N.data.error.retryable,N.data.error.recovery)}let c=Ve(U.unknown()).safeParse(J);if(!c.success||c.data.scope.projectId!==n.scope.projectId||c.data.scope.environment!==n.scope.environment||c.data.scope.environmentId!==n.scope.environmentId||c.data.requestId!==g||c.data.command!==S.command)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);let $=s.safeParse(c.data.data);if(!$.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);return $.data}function R(){if(!w)throw new I("MERCHANT_BRIDGE_UNAUTHENTICATED",401);return w}async function B(m,s,E,_){let O=R();if(_!==void 0&&Te.parse({operationId:_,customerId:O}),!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=h,l=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],...s?[s]:[]]);l.throwIfAborted();let o,T=new Promise((g,M)=>{o=()=>M(l.reason),l.addEventListener("abort",o,{once:!0})});try{let M=E(async()=>{let c=await import("./merchant-bridge-contracts-7EHDNPJJ.js");if(l.throwIfAborted(),S!==h||w!==O)throw new DOMException("Merchant identity changed","AbortError");return c},l),J=await Promise.race([M,T]);return l.throwIfAborted(),J}finally{l.removeEventListener("abort",o)}}async function z(m,s,E,_){let O=R(),S=Te.parse({operationId:E,customerId:O}),l=await P(m,s,S.operationId,_,S);if(l.customerId!==O||l.operationId!==S.operationId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return l}return{async readPresentation(m){let s=await P("presentation",Ge,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(s.presentation&&w!==null&&s.presentation.customerId!==w)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return i=s.nativeUserId,t=s.presentation,s},async createSession(m){let s=await P("session",je,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(w!==null&&w!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(t&&t.customerId!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return w=s.session.customerId,i=s.nativeUserId,s.session},async reportPresentation(m,s){let E=R(),_=Je.parse(m);if(!t||t.customerId!==E||t.decisionId!==_.decisionId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return P("presentation_events",U.strictObject({queued:U.literal(!0)}),void 0,s,_)},async readCustomerCommerce(m){let s=R(),E=await B("customer_commerce",m,async(_,O)=>{let[S,l]=await Promise.all([_(),P("customer_commerce",U.unknown(),void 0,O)]),o=S.merchantBridgeCommerceSchema.safeParse(l);if(!o.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return o.data});if(E.customerId!==s)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return E},async executePurchase(m,s){let E=await B("purchases",s,async(_,O)=>z("purchases",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="purchase")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},readOperation:(m,s)=>B("operation_status",s,async(E,_)=>z("operation_status",(await E()).merchantOperationLookupSchema,m,_),m),async executeSubscriptionChange(m,s){let E=await B("subscription_changes",s,async(_,O)=>z("subscription_changes",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="subscription_change")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},reset(){h++,u.abort(),u=new AbortController,w=null,t=null,i=null}}}var en=U.strictObject({command:ve,target:Qe,runId:U.uuid().optional(),expiresAt:U.iso.datetime({offset:!0}).optional(),deliveryLimit:U.number().int().min(1).max(100).optional()}).refine(n=>n.command.release===n.target.release),Ze=U.strictObject({schemaVersion:U.literal(1),entries:U.array(en).max(4e3)});function nn(n){let d=!1,f=()=>{d||n.unavailable(),d=!0};function b(){return n.storage===!1?void 0:n.storage??globalThis.sessionStorage}function w(t){let i=b()?.getItem(t);if(!i)return[];if(i.length>1048576)throw Error("Entry recovery is too large");return Ze.parse(JSON.parse(i)).entries}function h(t,i){let u=b();if(!u)return;if(!i.length)return u.removeItem(t);let y=JSON.stringify(Ze.parse({schemaVersion:1,entries:i}));if(y.length>1048576)throw Error("Entry recovery is too large");u.setItem(t,y)}return{load(){try{let t=n.binding();if(!t||n.storage===!1)return;let i="indiana.funnel.entries.v1."+JSON.stringify(t);return{key:i,entries:w(i)}}catch{f();return}},retain(t,i){if(t)try{let u=en.parse(i);h(t,[...w(t).filter(y=>y.command.funnelId!==u.command.funnelId),u])}catch{f()}},forget(t,i){if(t)try{h(t,w(t).filter(u=>u.command.requestId!==i))}catch{f()}}}}var tn=U.strictObject({version:U.literal(1),runs:U.array(U.uuid()).max(100)}),De=new WeakMap,Oe=new WeakMap;function Se(n){let d=!1;function f(){d||n.unavailable(),d=!0}function b(t){let i=t.storage.getItem(t.key);if(!i)return[];if(i.length>8192)throw Error("Invalid entry delivery record");return tn.parse(JSON.parse(i)).runs}function w(t){let i=De.get(t.storage);i||De.set(t.storage,i=new Map);let u=i.get(t.key);return u||i.set(t.key,u=new Set),u}function h(t){if(!t)return;let i=De.get(t.storage),u=i?.get(t.key);u?.delete(t.requestId),u?.size===0&&i?.delete(t.key)}return{claim(t,i,u,y,P=!1){if(u!==void 0)try{let R=n.binding();if(!R)throw Error("Entry delivery identity is unavailable");let B={storage:n.storage??globalThis.sessionStorage,key:"indiana.funnel.delivery.v1."+JSON.stringify([...R,i,t]),requestId:y},z=b(B);if(Oe.get(B.storage)?.has(B.key))throw Error("Entry delivery storage is unavailable");B.storage.setItem(B.key,JSON.stringify({version:1,runs:z}));let m=w(B);return!P&&!m.has(y)&&z.length+m.size>=u?!1:(m.add(y),B)}catch{return f(),!1}},accept(t,i){if(t)try{let u=b(t);u.includes(i)||t.storage.setItem(t.key,JSON.stringify(tn.parse({version:1,runs:[...u,i].slice(-100)})))}catch{let u=Oe.get(t.storage);u||Oe.set(t.storage,u=new Set),u.add(t.key),f()}finally{h(t)}},release:h}}function Pe(){let n,d,f=()=>{clearTimeout(n),n=void 0;let b=d;d=void 0,b?.cancelled()};return{get active(){return d!==void 0},start(b,w,h,t){if(d)return;if(b===0){w()?h():t();return}let i={valid:w,cancelled:t};d=i,n=setTimeout(()=>{d===i&&(d=void 0,n=void 0,w()?h():t())},b*1e3)},recheck(){d&&!d.valid()&&f()},cancel:f}}var Re=n=>["running","waiting"].includes(n.status)&&!n.pendingRequest&&(n.stopped||!n.screen&&!n.paywall&&n.instruction?.type==="wait"&&n.instruction.kind!=="operation");function Cn(n){let d=we(n.baseUrl),f=n.scope,b=Ce(n),w=n.fetch??globalThis.fetch.bind(globalThis),h,t=!1,i=!1,u=0,y=0,P="",R=0,B=0,z=0,m=!1,s,E=!0,_,O,S,l,o,T=-1,g,M=e=>{g===e&&(N.release(e.deliveryTicket),g=void 0,x())},J=new Set,c=(e,a)=>Z(n.onStatus,e,a),$=Pe(),N=Se({storage:n.deliveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,"customer",e]:void 0},unavailable:()=>c("delivery_unavailable")}),ee=new Set,te=nn({storage:n.recoveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,n.appManifestRelease,e]:void 0},unavailable:()=>c("recovery_unavailable")}),Y=e=>te.forget(e.storageKey,e.command.requestId);function Q(e,a){a&&(e.runId=a.id,e.expiresAt=a.runExpiresAt),te.retain(e.storageKey,{command:e.command,target:e.target,...e.runId&&{runId:e.runId},...e.expiresAt&&{expiresAt:e.expiresAt},...e.deliveryLimit!==void 0&&{deliveryLimit:e.deliveryLimit}})}function re(){let e=o;o=void 0,e?.host.destroy(),e?.slot.remove(),e?.client.reset(),x()}let le=()=>$.active||g!==void 0||o!==void 0&&!o.background;function me(e,a){if(o?.client!==e)return;Q(o.recovery,a);let p=Re(a);o.slot.hidden=p,p!==o.background&&(o.background=p,p?c("run_background",o.entryId):T=y,x())}function pe(e,a,p){let v=e.client.view;if(!a||e.background||!v?.screen||v.paywall||v.pendingRequest||v.stopped||v.status!=="waiting")return;let K=Ke.parse({operation:"close",requestId:crypto.randomUUID(),nodeId:v.nodeId,visit:v.visit,revision:v.revision,customerToken:a}),j=Ce({...n,session:void 0});j.requestWithCredential("funnels",K,e.runToken,{keepalive:p}).then(()=>Y(e.recovery)).catch(()=>{}).finally(()=>j.dispose())}let ae=()=>{o&&pe(o,n.session.peek(),!0)},r=()=>Date.now()<B&&performance.now()<z;function C(e){if(e.target.release!==n.appManifestRelease||!r())return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return c("incompatible",e.id),!1}}function H(e){if(t||e.epoch!==R||e.visit!==y||document.visibilityState==="hidden")return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function W(e){if(le()){c("in_progress",e.id);return}let a=R,p=y;$.start(e.delivery?.delaySeconds??0,()=>!t&&a===R&&p===y&&document.visibilityState!=="hidden"&&C(e)&&h?.entries.some(v=>v.id===e.id&&v.funnelId===e.funnelId&&v.versionId===e.versionId&&v.event===e.event&&JSON.stringify(v.target)===JSON.stringify(e.target)&&JSON.stringify(v.delivery)===JSON.stringify(e.delivery))===!0,()=>{V(e)},()=>{J.delete(`${e.funnelId}:${e.id}`)})}async function V(e){if(le()){c("in_progress",e.id);return}if(!n.session.peek()){c("identity_required",e.id);return}let a=te.load(),p=a?.entries.find(A=>A.command.funnelId===e.funnelId&&(!A.expiresAt||Date.parse(A.expiresAt)>Date.now()));if(p){if(!X(p)){c("recovery_pending",e.id);return}let A={...p,storageKey:a.key,epoch:R,visit:y};ee.add(A.command.requestId),g=A,await F(A);return}let v=crypto.randomUUID(),K=N.claim(e.id,e.funnelId,e.delivery?.maxPerSession,v);if(K===!1){c("frequency",e.id),x();return}let j={freshStart:!0,deliveryLimit:e.delivery?.maxPerSession,deliveryTicket:K,command:ve.parse({operation:"entry_start",entryId:e.id,funnelId:e.funnelId,versionId:e.versionId,release:n.appManifestRelease,requestId:v,locale:document.documentElement.lang||"en"}),epoch:R,visit:y,target:e.target,storageKey:a?.key};ee.add(j.command.requestId),g=j,await F(j)}async function F(e){if(e.dispatching)return;e.dispatching=!0;let a=e.freshStart===!0;e.freshStart=!1;let p,v=!1,K=!1;async function j(A){if(e.epoch!==R)return;let D=A.view;if(!(e.storageKey&&D&&(Re(D)||D.paywall||D.pendingRequest))&&D&&["running","waiting"].includes(D.status))try{await A.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:D.nodeId,visit:D.visit,revision:D.revision}),Y(e)}catch(k){if(!(k instanceof G&&k.code==="FORBIDDEN"))throw k}}try{if(!e.deliveryTicket&&e.deliveryLimit!==void 0){let q=N.claim(e.command.entryId,e.command.funnelId,e.deliveryLimit,e.command.requestId,!0);q!==!1&&(e.deliveryTicket=q)}Q(e),c("starting",e.command.entryId);let A=await b.request("funnels",e.command),D=Ye.safeParse(A);if(D.success){if(D.data.scope.projectId!==f.projectId||D.data.scope.environment!==f.environment)throw new G("SCOPE_MISMATCH","Entry scope changed");e.epoch===R&&c(D.data.reason,e.command.entryId),Y(e),M(e);return}let k=Xe.parse(A);if(!k.runToken||k.scope.projectId!==f.projectId||k.scope.environment!==f.environment||k.run.source.type!=="funnel"||k.run.source.id!==e.command.funnelId||k.run.source.versionId!==e.command.versionId||e.runId!==void 0&&k.run.id!==e.runId)throw new G("INVALID_RESPONSE","Invalid entry Run");if(N.accept(e.deliveryTicket,k.run.id),e.epoch!==R){M(e),c("identity_changed",e.command.entryId);return}Q(e,k.run);let L=Ae({...n,runToken:k.runToken,funnelId:e.command.funnelId,initialResponse:a?A:void 0});p=L,K=!0,await L.get(),K=!1;let ne=L.view;if(!ne||ne.id!==k.run.id||ne.source.type!=="funnel"||ne.source.id!==e.command.funnelId||ne.source.versionId!==e.command.versionId)throw new G("INVALID_RESPONSE","Entry Run version changed");if(!["running","waiting"].includes(ne.status)){Y(e),M(e),c("run_ended",e.command.entryId);return}let{showFunnelRun:fe}=await import("./funnel-runtime-host-Y4IEIGCK.js");if(!H(e)){await j(L),c("left_screen",e.command.entryId),M(e);return}let Fe=!1,xe=!1;if(o&&!o.background){await j(L),c("in_progress",e.command.entryId),M(e);return}o&&re();let ie=document.createElement("div");ie.hidden=Re(ne),n.container.append(ie);let ke=await fe(ie,{...n.host,client:L,appManifestRelease:n.appManifestRelease,onState(q){me(L,q),Z(n.host?.onState,q)},onDismiss(q){Fe=!0,ie.remove(),q&&!["running","waiting"].includes(q.status)&&Y(e),o?.client===L&&(o=void 0,L.reset(),x(),q&&q.status!=="completed"&&c("run_ended",e.command.entryId)),Z(n.host?.onDismiss,q)},onComplete(q){xe=!0,Y(e),o?.client===L&&re(),Z(n.host?.onComplete,q)},onError(q){Z(n.host?.onError,q),o?.client===L&&q instanceof G&&q.code==="FORBIDDEN"&&(Y(e),re(),c("run_ended",e.command.entryId))}}).catch(q=>{throw ie.remove(),q});if(!H(e)||Fe||xe){ke.destroy(),ie.remove(),H(e)||await j(L),M(e);return}let he=Re(L.view??ne);ie.hidden=he,o={host:ke,client:L,slot:ie,entryId:e.command.entryId,background:he,runToken:k.runToken,owner:n.session.peek(),recovery:e},he||(T=e.visit),v=!0,M(e),c("started",e.command.entryId),he&&c("run_background",e.command.entryId)}catch(A){A instanceof G&&(!p||K&&A.code==="FORBIDDEN")&&A.status!==void 0&&A.status>=400&&A.status<500&&!A.retryable&&(Y(e),M(e)),e.epoch===R&&!t&&(c("start_failed",e.command.entryId),Z(n.host?.onError,A))}finally{v||p?.reset(),e.dispatching=!1}}function X(e){if(e.command.release!==n.appManifestRelease||e.target.release!==n.appManifestRelease)return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function ye(){if(le())return!1;let e=te.load();for(let a of e?.entries??[]){if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now()){te.forget(e.key,a.command.requestId);continue}if(a.command.requestId===o?.recovery.command.requestId||ee.has(a.command.requestId)||!X(a))continue;ee.add(a.command.requestId);let p={...a,storageKey:e.key,epoch:R,visit:y};return g=p,F(p),!0}return!1}function ue(){if(m=!1,$.recheck(),t||!i||document.visibilityState==="hidden")return;se();let e=o!==void 0&&!o.background;if(e&&(T=y),!ye()){if(!r()){E=!0;return}E=!1;for(let a of h?.entries??[]){let p=`${a.funnelId}:${a.id}`;if(!(a.event!=="screen_enter"||J.has(p)||!C(a))){if(!n.session.peek()){c("identity_required",a.id);continue}if(T===y){J.add(p),e&&c("in_progress",a.id);continue}if(g||$.active){c("in_progress",a.id);return}J.add(p),W(a);break}}}}let x=()=>{!m&&!t&&(m=!0,queueMicrotask(ue))};function se(){let e=location.origin+location.pathname;return e===P?!1:(P=e,y++,$.cancel(),E=!0,J.clear(),ee.clear(),!0)}function oe(){se()&&x()}function ce(e){if(!e.isTrusted||e.button!==0||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||document.visibilityState==="hidden")return;let a=e.target;if(!(a instanceof Element)||a.closest("[data-indiana-funnel]"))return;let p=a.closest("button,a,input");if(!(!p||p.matches(":disabled,[aria-disabled='true']")||p.closest("[hidden],[inert],[aria-hidden='true']")))for(let v of h?.entries??[]){let K=v.target.button;if(!(v.event!=="button_click"||!K||!C(v))){try{let j=be(document);if(!p.matches(K.selector)||j(K.selector,p)!==1)continue}catch{c("incompatible",v.id);continue}W(v);break}}}async function Me(){if(t)return;if(s)return s;let e=++u,a=new AbortController;_=a;let p,v=new Promise((A,D)=>{p=()=>D(new G("TIMEOUT","Funnel entry configuration read cancelled or timed out")),a.signal.addEventListener("abort",p,{once:!0})}),K=setTimeout(()=>a.abort(),n.timeoutMs??5e3),j=(async()=>{let A=async()=>{let fe=await w(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:a.signal});if(!fe.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",fe.status);return ge.parse(await fe.json())},D=await Promise.race([A(),v]),k=Date.parse(D.validatedAt),L=Date.parse(D.validUntil);if(D.scope.projectId!==f.projectId||D.scope.environment!==f.environment||D.scope.environmentId!==n.environmentId||D.release!==n.appManifestRelease||L<=Date.now()||k>Date.now()+5e3||L-k>6e4||L<=k)throw new G("INVALID_RESPONSE","Entry configuration scope or deadline changed");if(t||e!==u)return;let ne=h===void 0;h=D,B=L,z=performance.now()+Math.min(L-Date.now(),6e4),$.recheck(),(ne||E)&&x()})();s=j;try{await j}finally{clearTimeout(K),a.signal.removeEventListener("abort",p),s===j&&(s=void 0)}}async function on(){if(!(!i||t)){try{await Me()}catch{t||c("configuration_unavailable")}x()}}let Ne=Ie({document,run:on,delay:()=>i&&!t?15e3:void 0});return{async start(){i||t||(i=!0,P=location.origin+location.pathname,O=Ee(oe),S=n.session.subscribeIdentity(()=>{R++,$.cancel(),N.release(g?.deliveryTicket),E=!0,g=void 0,J.clear(),T=-1,ee.clear(),o&&pe(o,o.owner,!1),re(),x()}),l=new MutationObserver(x),l.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",ce,!0),document.addEventListener("visibilitychange",x),addEventListener("pagehide",ae),await Ne.refresh())},refresh:Me,async retry(){g&&!t&&g.epoch===R&&await F(g)},destroy(){t=!0,u++,$.cancel(),N.release(g?.deliveryTicket),Ne.destroy(),_?.abort(),l?.disconnect(),O?.(),S?.(),document.removeEventListener("click",ce,!0),document.removeEventListener("visibilitychange",x),removeEventListener("pagehide",ae),ae(),re(),b.dispose(),h=void 0}}}function An(n){let d=we(n.baseUrl),f=n.fetch??globalThis.fetch.bind(globalThis),b,w=0,h=0,t=!1,i=!1,u=!1,y=0,P=0,R=-1,B=!1,z="",m,s,E,_,O=new Set,S,l,o,T=(r,C)=>Z(n.onStatus,r,C),g=Pe(),M=()=>{try{return n.deliveryIdentity?.()}catch{return}},J=()=>JSON.stringify(M()),c=Se({storage:n.deliveryStorage,binding:()=>{let r=M();return r?.id?[d,n.scope.projectId,n.scope.environment,n.environmentId,r.type,r.id]:void 0},unavailable:()=>T("delivery_unavailable")}),$=()=>Date.now()<w&&performance.now()<h;function N(r){try{return $()&&r.target.release===n.appManifestRelease&&de(r.target.render,document,location.pathname,()=>{})}catch{return T("incompatible",r.id),!1}}function ee(){let r=o;o=void 0,r?.host.destroy(),r?.slot.remove()}async function te(r){if(r.dispatching)return;r.dispatching=!0;let C=y;try{let H=await r.process.open({operation:"entry_start",funnelId:r.entry.funnelId,versionId:r.entry.versionId,entryId:r.entry.id,release:n.appManifestRelease,locale:n.locale??"en"});c.accept(r.deliveryTicket,H.run.id);let{showFunnelRun:W}=await import("./funnel-runtime-host-Y4IEIGCK.js");if(t||C!==y||l!==r)return;let V=document.createElement("div");n.container.append(V),R=P;let F=await W(V,{...n.host,client:H.controller,appManifestRelease:n.appManifestRelease,onDismiss(X){o?.process===r.process&&(o=void 0,V.remove()),Z(n.host?.onDismiss,X)}});if(t||C!==y||l!==r){F.destroy(),V.remove();return}o={entry:r.entry,process:r.process,host:F,slot:V,deliveryTicket:r.deliveryTicket},l=void 0,T("run_presented",r.entry.id)}catch(H){if(t||C!==y||l!==r)return;H instanceof G&&"result"in H?(c.release(r.deliveryTicket),l=void 0,r.process.destroy(),T("suppressed",r.entry.id),Q()):T("entry_unavailable",r.entry.id)}finally{r.dispatching=!1}}function Y(r){if(t||i||l||o||S||g.active||R===P||!N(r))return;let C=`${P}:${r.id}`;if(O.has(C))return;O.add(C);let H=P,W=y,V=J();g.start(r.delivery?.delaySeconds??0,()=>!t&&y===W&&P===H&&J()===V&&document.visibilityState!=="hidden"&&N(r)&&b?.entries.some(F=>F.id===r.id&&F.funnelId===r.funnelId&&F.versionId===r.versionId&&F.event===r.event&&JSON.stringify(F.target)===JSON.stringify(r.target)&&JSON.stringify(F.delivery)===JSON.stringify(r.delivery))===!0,()=>{let F=c.claim(r.id,r.funnelId,r.delivery?.maxPerSession,crypto.randomUUID());if(F===!1){T("frequency",r.id),Q();return}try{let X={entry:r,process:n.createProcess(r),visit:P,deliveryTicket:F};l=X,te(X)}catch(X){c.release(F),T("entry_unavailable",r.id),Z(n.host?.onError,X)}},()=>{O.delete(C)})}function Q(){B||t||(B=!0,queueMicrotask(()=>{if(B=!1,g.recheck(),!(t||i||document.visibilityState==="hidden"||!$()||l||o||S||g.active||R===P)){for(let r of b?.entries??[])if(r.event==="screen_enter"&&!O.has(`${P}:${r.id}`)&&N(r)){Y(r);break}}}))}function re(r){if(!r.isTrusted||r.defaultPrevented||!(r.target instanceof Element)||l||o||S||R===P)return;let C=be(document,()=>{});for(let H of b?.entries??[]){let W=H.target.button;if(H.event!=="button_click"||!W||!N(H))continue;let V=r.target.closest(W.selector);if(!(!V||V.tagName.toLowerCase()!==W.tag||C(W.selector)!==1||V.matches(":disabled")||V.closest('[inert],[hidden],[aria-hidden="true"]'))){Y(H);break}}}let le=()=>{let r=location.origin+location.pathname;r!==z&&(z=r,P++,g.cancel(),O.clear(),Q())};async function me(){if(t)return;if(s)return s;let r=y,C=new AbortController;m=C;let H,W=new Promise((ye,ue)=>{H=ue}),V=()=>H(new G("TIMEOUT","Funnel entry read cancelled"));C.signal.addEventListener("abort",V,{once:!0});let F=setTimeout(()=>C.abort(),n.timeoutMs??5e3),X=(async()=>{let ye=encodeURIComponent(JSON.stringify(["funnel-process/1"])),ue=async()=>{let ce=await f(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}&executionContracts=${ye}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:C.signal});if(!ce.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",ce.status);return ge.parse(await ce.json())},x=await Promise.race([ue(),W]),se=Date.parse(x.validatedAt),oe=Date.parse(x.validUntil);if(x.scope.projectId!==n.scope.projectId||x.scope.environment!==n.scope.environment||x.scope.environmentId!==n.environmentId||x.release!==n.appManifestRelease||oe<=Date.now()||se>Date.now()+5e3||oe<=se||oe-se>6e4)throw new G("INVALID_RESPONSE","Entry scope or deadline changed");t||r!==y||(b=x,w=oe,h=performance.now()+Math.min(oe-Date.now(),6e4),g.recheck(),Q())})();s=X;try{await X}finally{clearTimeout(F),C.signal.removeEventListener("abort",V),s===X&&(s=void 0)}}async function pe(){if(!(!u||t))try{await me()}catch{t||T("configuration_unavailable")}}let ae=Ie({document,run:pe,delay:()=>u&&!t?15e3:void 0});return{async start(){u||t||(u=!0,z=location.origin+location.pathname,E=Ee(le),_=new MutationObserver(Q),_.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",re,!0),document.addEventListener("visibilitychange",Q),await ae.refresh())},refresh:me,async retry(){l&&!t&&await te(l)},async syncIdentity(){g.cancel();let r=o??l??S;if(!r){i=!1,Q();return}try{let C=await r.process.syncIdentity();return i=!1,S===r&&(l={...r,visit:P},S=void 0,await te(l)),C}catch(C){throw r.process.view||(S={...r,visit:P},l=void 0,ee()),C}},async detach(){i=!0,y++,g.cancel(),m?.abort();let r=o??l??S;r&&(S={...r,visit:P}),l=void 0,ee(),r&&await r.process.detach()},destroy(){t=!0,y++,g.cancel(),ae.destroy(),m?.abort(),_?.disconnect(),E?.(),document.removeEventListener("click",re,!0),document.removeEventListener("visibilitychange",Q);let r=o??l??S;c.release(r?.deliveryTicket),l=void 0,S=void 0,ee(),r?.process.destroy(),b=void 0}}}async function Dn(n,d){return(await import("./paywall-LNVEFOAB.js")).showPaywall(n,d)}async function dt(){return await Promise.all([import("./paywall-LNVEFOAB.js"),import("./screen-renderer-Y57TAOIX.js")]),Dn}async function lt(...n){return n[1]=ze(n[1]),(await import("./paywall-session-FQ4VC5WG.js")).createPaywallSession(...n)}async function ut(...n){let d=n[1].signal?.aborted?void 0:We(n[1].client);try{return import("./screen-renderer-Y57TAOIX.js").catch(()=>{}),import("./paywall-LNVEFOAB.js").catch(()=>{}),await(await rn(()=>import("./funnel-runtime-host-Y4IEIGCK.js"),n[1].prepared)).showFunnelRun(...n)}finally{d?.()}}async function rn(n,d){try{return await n()}catch(f){throw d&&d.state!=="adopted"&&await import("./funnel-paywall-prerender-HWQX4YNE.js").then(b=>b.preparedInternals(d)?.release(),()=>{}),f}}async function ft(...n){return import("./screen-renderer-Y57TAOIX.js").catch(()=>{}),import("./paywall-LNVEFOAB.js").catch(()=>{}),(await rn(()=>import("./funnel-host-purchase-VS4BXFCP.js"),n[1].prepared)).showFunnelPurchase(...n)}async function mt(...n){return import("./funnel-host-purchase-VS4BXFCP.js").catch(()=>{}),import("./screen-renderer-Y57TAOIX.js").catch(()=>{}),(await import("./funnel-paywall-prerender-HWQX4YNE.js")).prerenderFunnelPurchase(...n)}async function pt(){await Promise.all([import("./funnel-paywall-prerender-HWQX4YNE.js"),import("./funnel-host-purchase-VS4BXFCP.js"),import("./paywall-LNVEFOAB.js"),import("./screen-renderer-Y57TAOIX.js"),import("./paywall-content-TPXYF6DN.js"),import("./check-response-MCT5RGOM.js"),import("./operation-contracts-C6CMAO6S.js")])}async function yt(...n){return(await import("./funnel-route-prediction-XNIKDJIM.js")).predictFunnelStart(...n)}async function ht(...n){return(await import("./funnel-route-prediction-XNIKDJIM.js")).predictedPaywallLoadingDocument(...n)}async function gt(...n){return(await import("./content-AZXMOLCZ.js")).mountContent(...n)}async function vt(...n){return(await import("./content-AZXMOLCZ.js")).prepareContent(...n)}export{G as LongplayError,I as MerchantBridgeError,yn as createBrowserFunnelCommandStorage,En as createBrowserFunnelPurchaseStorage,vn as createConfigurationSync,mn as createFeatureClient,wn as createFunnelClient,Rn as createFunnelPageExperiments,Sn as createFunnelProcess,bn as createFunnelPurchaseClient,Ae as createFunnelRunController,Cn as createIamFunnelEntries,An as createIamFunnelProcessEntries,Pn as createLocalFunnelClient,pn as createLongplay,Tn as createMerchantBridge,lt as createPaywallSession,In as evaluateFunnelNode,sn as formatCouponDiscount,an as formatCouponMoney,cn as formatCouponTerms,hn as getPaywallRecovery,un as isPaywallOperationComplete,fn as isPaywallOperationPending,ln as isPaywallUpdateOperation,dn as isPaywallUpdateQuote,gt as mountContent,yt as predictFunnelStart,ht as predictedPaywallLoadingDocument,pt as preloadFunnelPurchase,dt as preloadPaywall,vt as prepareContent,gn as preparePaywallFallback,mt as prerenderFunnelPurchase,ft as showFunnelPurchase,ut as showFunnelRun,Dn as showPaywall};
|
|
1
|
+
import{a as En,c as bn}from"./chunk-MVUNV5XR.js";import{a as We,c as Rn}from"./chunk-TIUD3N72.js";import{a as Ie}from"./chunk-W32FI2A2.js";import{a as pn,c as wn,d as Sn}from"./chunk-4NO6U4X6.js";import"./chunk-3ITNAFAH.js";import{a as In}from"./chunk-TM72XBM5.js";import"./chunk-2I2S5ZIH.js";import{h as mn,i as vn,k as Pn}from"./chunk-DB5S72HJ.js";import{E as Ae,d as Xe,f as Qe,g as ge,h as ve,i as Ye,w as yn}from"./chunk-3TSFGU4T.js";import"./chunk-W3B4GT74.js";import{a as ze}from"./chunk-Y2ASROJH.js";import"./chunk-TIOPNTMP.js";import"./chunk-RFWVXTZ7.js";import"./chunk-US65SQX4.js";import"./chunk-HYCLLEFU.js";import"./chunk-KSME3N3A.js";import{K as Ke}from"./chunk-LE32WTZ7.js";import"./chunk-SZZIYCXK.js";import"./chunk-IDDPWGQE.js";import{c as hn,e as gn}from"./chunk-LSHIR6QM.js";import"./chunk-OPUIFAQS.js";import"./chunk-HYX3EDZS.js";import{B as dn,C as ln,D as un,E as fn,c as an,d as sn,e as cn}from"./chunk-EGFVGCDG.js";import{A as Le,B as Be,D as He,F as qe,G as Ue,I as Ve,J as je,K as Ge,L as Je,M as Te,N as $e,z as _e}from"./chunk-YFLVGOCJ.js";import"./chunk-VILB5M4X.js";import{b as Ce}from"./chunk-FN462OVO.js";import"./chunk-FRRKTQNZ.js";import"./chunk-MQ5LJEWV.js";import"./chunk-JDIFYMSA.js";import"./chunk-TNPBYYAX.js";import"./chunk-KCN6OGYG.js";import"./chunk-PF6PRPRO.js";import{a as G}from"./chunk-ZDIWOE4Q.js";import"./chunk-FYD7CMS7.js";import{a as be,c as de}from"./chunk-J6KIN4RH.js";import"./chunk-SLUA7ABW.js";import{c as we,d as Ee}from"./chunk-GJSQZGBE.js";import"./chunk-3VUPVXAV.js";import"./chunk-B4SM2KRI.js";import{b as U}from"./chunk-XVCSRZX4.js";import{a as Z}from"./chunk-DSPLGTQI.js";import"./chunk-A5KU4MMN.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";var I=class extends Error{constructor(f,b=0,w=!1,h="fix_request"){super(f);this.code=f;this.status=b;this.retryable=w;this.recovery=h;this.name="MerchantBridgeError"}code;status;retryable;recovery};async function _n(n,d){if(!n.headers.get("content-type")?.split(";",1)[0].trim().match(/^application\/(?:json|[a-z0-9.+-]+\+json)$/i))throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let f=n.body?.getReader();if(!f)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let b=()=>{f.cancel().catch(()=>{})};d.addEventListener("abort",b,{once:!0});let w=0,h="",t=new TextDecoder("utf-8",{fatal:!0});try{for(d.throwIfAborted();;){let i=await f.read();if(d.throwIfAborted(),i.done)break;if(w+=i.value.byteLength,w>262144)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");h+=t.decode(i.value,{stream:!0})}return h+=t.decode(),JSON.parse(h)}catch(i){throw d.throwIfAborted(),i instanceof I?i:new I("MERCHANT_BRIDGE_INVALID_RESPONSE")}finally{d.removeEventListener("abort",b),await f.cancel().catch(()=>{}),f.releaseLock()}}function Tn(n){let d=qe.parse(n.origin),f=Ue.parse(n.manifest),b={projectId:n.scope.projectId,environmentId:n.scope.environmentId,environment:n.scope.environment};for(let m of["projectId","environmentId","environment"])if(f[m]!==n.scope[m])throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");let w=n.customerId===void 0?null:U.uuid().parse(n.customerId),h=0,t=null,i=null,u=new AbortController,y=n.fetch??globalThis.fetch;async function P(m,s,E,_,O){if(!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=He[m];if(["merchant_catalog_reader","merchant_refund_authority","indiana_server_key"].includes(S.authority))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);let l=h,o=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],..._?[_]:[]]);o.throwIfAborted();let T=new Headers(await n.headers?.());if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(/\bgg_(?:sk|ct|rt)_/.test(T.get("authorization")??"")||T.has("X-Indiana-Bridge-Signature")||T.has("X-Indiana-Bridge-Key-Id"))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);T.set(Be,String(_e)),T.set("Accept","application/json");let g=crypto.randomUUID();T.set("X-Request-Id",g),T.set("Content-Type","application/json");let M=await y(d+Le,{method:"POST",credentials:"include",redirect:"error",cache:"no-store",headers:T,signal:o,body:JSON.stringify({bridgeVersion:_e,requestId:g,command:S.command,scope:b,data:O??(E===void 0?{}:{operationId:E})})}),J=await _n(M,o);if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(!M.ok){let N=$e.safeParse(J);throw!N.success||N.data.scope.projectId!==n.scope.projectId||N.data.scope.environment!==n.scope.environment||N.data.scope.environmentId!==n.scope.environmentId||N.data.requestId!==g||N.data.command!==S.command?new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status):new I(N.data.error.code,M.status,N.data.error.retryable,N.data.error.recovery)}let c=Ve(U.unknown()).safeParse(J);if(!c.success||c.data.scope.projectId!==n.scope.projectId||c.data.scope.environment!==n.scope.environment||c.data.scope.environmentId!==n.scope.environmentId||c.data.requestId!==g||c.data.command!==S.command)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);let $=s.safeParse(c.data.data);if(!$.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);return $.data}function R(){if(!w)throw new I("MERCHANT_BRIDGE_UNAUTHENTICATED",401);return w}async function B(m,s,E,_){let O=R();if(_!==void 0&&Te.parse({operationId:_,customerId:O}),!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=h,l=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],...s?[s]:[]]);l.throwIfAborted();let o,T=new Promise((g,M)=>{o=()=>M(l.reason),l.addEventListener("abort",o,{once:!0})});try{let M=E(async()=>{let c=await import("./merchant-bridge-contracts-7EHDNPJJ.js");if(l.throwIfAborted(),S!==h||w!==O)throw new DOMException("Merchant identity changed","AbortError");return c},l),J=await Promise.race([M,T]);return l.throwIfAborted(),J}finally{l.removeEventListener("abort",o)}}async function z(m,s,E,_){let O=R(),S=Te.parse({operationId:E,customerId:O}),l=await P(m,s,S.operationId,_,S);if(l.customerId!==O||l.operationId!==S.operationId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return l}return{async readPresentation(m){let s=await P("presentation",Ge,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(s.presentation&&w!==null&&s.presentation.customerId!==w)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return i=s.nativeUserId,t=s.presentation,s},async createSession(m){let s=await P("session",je,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(w!==null&&w!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(t&&t.customerId!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return w=s.session.customerId,i=s.nativeUserId,s.session},async reportPresentation(m,s){let E=R(),_=Je.parse(m);if(!t||t.customerId!==E||t.decisionId!==_.decisionId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return P("presentation_events",U.strictObject({queued:U.literal(!0)}),void 0,s,_)},async readCustomerCommerce(m){let s=R(),E=await B("customer_commerce",m,async(_,O)=>{let[S,l]=await Promise.all([_(),P("customer_commerce",U.unknown(),void 0,O)]),o=S.merchantBridgeCommerceSchema.safeParse(l);if(!o.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return o.data});if(E.customerId!==s)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return E},async executePurchase(m,s){let E=await B("purchases",s,async(_,O)=>z("purchases",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="purchase")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},readOperation:(m,s)=>B("operation_status",s,async(E,_)=>z("operation_status",(await E()).merchantOperationLookupSchema,m,_),m),async executeSubscriptionChange(m,s){let E=await B("subscription_changes",s,async(_,O)=>z("subscription_changes",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="subscription_change")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},reset(){h++,u.abort(),u=new AbortController,w=null,t=null,i=null}}}var en=U.strictObject({command:ve,target:Qe,runId:U.uuid().optional(),expiresAt:U.iso.datetime({offset:!0}).optional(),deliveryLimit:U.number().int().min(1).max(100).optional()}).refine(n=>n.command.release===n.target.release),Ze=U.strictObject({schemaVersion:U.literal(1),entries:U.array(en).max(4e3)});function nn(n){let d=!1,f=()=>{d||n.unavailable(),d=!0};function b(){return n.storage===!1?void 0:n.storage??globalThis.sessionStorage}function w(t){let i=b()?.getItem(t);if(!i)return[];if(i.length>1048576)throw Error("Entry recovery is too large");return Ze.parse(JSON.parse(i)).entries}function h(t,i){let u=b();if(!u)return;if(!i.length)return u.removeItem(t);let y=JSON.stringify(Ze.parse({schemaVersion:1,entries:i}));if(y.length>1048576)throw Error("Entry recovery is too large");u.setItem(t,y)}return{load(){try{let t=n.binding();if(!t||n.storage===!1)return;let i="indiana.funnel.entries.v1."+JSON.stringify(t);return{key:i,entries:w(i)}}catch{f();return}},retain(t,i){if(t)try{let u=en.parse(i);h(t,[...w(t).filter(y=>y.command.funnelId!==u.command.funnelId),u])}catch{f()}},forget(t,i){if(t)try{h(t,w(t).filter(u=>u.command.requestId!==i))}catch{f()}}}}var tn=U.strictObject({version:U.literal(1),runs:U.array(U.uuid()).max(100)}),De=new WeakMap,Oe=new WeakMap;function Se(n){let d=!1;function f(){d||n.unavailable(),d=!0}function b(t){let i=t.storage.getItem(t.key);if(!i)return[];if(i.length>8192)throw Error("Invalid entry delivery record");return tn.parse(JSON.parse(i)).runs}function w(t){let i=De.get(t.storage);i||De.set(t.storage,i=new Map);let u=i.get(t.key);return u||i.set(t.key,u=new Set),u}function h(t){if(!t)return;let i=De.get(t.storage),u=i?.get(t.key);u?.delete(t.requestId),u?.size===0&&i?.delete(t.key)}return{claim(t,i,u,y,P=!1){if(u!==void 0)try{let R=n.binding();if(!R)throw Error("Entry delivery identity is unavailable");let B={storage:n.storage??globalThis.sessionStorage,key:"indiana.funnel.delivery.v1."+JSON.stringify([...R,i,t]),requestId:y},z=b(B);if(Oe.get(B.storage)?.has(B.key))throw Error("Entry delivery storage is unavailable");B.storage.setItem(B.key,JSON.stringify({version:1,runs:z}));let m=w(B);return!P&&!m.has(y)&&z.length+m.size>=u?!1:(m.add(y),B)}catch{return f(),!1}},accept(t,i){if(t)try{let u=b(t);u.includes(i)||t.storage.setItem(t.key,JSON.stringify(tn.parse({version:1,runs:[...u,i].slice(-100)})))}catch{let u=Oe.get(t.storage);u||Oe.set(t.storage,u=new Set),u.add(t.key),f()}finally{h(t)}},release:h}}function Pe(){let n,d,f=()=>{clearTimeout(n),n=void 0;let b=d;d=void 0,b?.cancelled()};return{get active(){return d!==void 0},start(b,w,h,t){if(d)return;if(b===0){w()?h():t();return}let i={valid:w,cancelled:t};d=i,n=setTimeout(()=>{d===i&&(d=void 0,n=void 0,w()?h():t())},b*1e3)},recheck(){d&&!d.valid()&&f()},cancel:f}}var Re=n=>["running","waiting"].includes(n.status)&&!n.pendingRequest&&(n.stopped||!n.screen&&!n.paywall&&n.instruction?.type==="wait"&&n.instruction.kind!=="operation");function Cn(n){let d=we(n.baseUrl),f=n.scope,b=Ce(n),w=n.fetch??globalThis.fetch.bind(globalThis),h,t=!1,i=!1,u=0,y=0,P="",R=0,B=0,z=0,m=!1,s,E=!0,_,O,S,l,o,T=-1,g,M=e=>{g===e&&(N.release(e.deliveryTicket),g=void 0,x())},J=new Set,c=(e,a)=>Z(n.onStatus,e,a),$=Pe(),N=Se({storage:n.deliveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,"customer",e]:void 0},unavailable:()=>c("delivery_unavailable")}),ee=new Set,te=nn({storage:n.recoveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,n.appManifestRelease,e]:void 0},unavailable:()=>c("recovery_unavailable")}),Y=e=>te.forget(e.storageKey,e.command.requestId);function Q(e,a){a&&(e.runId=a.id,e.expiresAt=a.runExpiresAt),te.retain(e.storageKey,{command:e.command,target:e.target,...e.runId&&{runId:e.runId},...e.expiresAt&&{expiresAt:e.expiresAt},...e.deliveryLimit!==void 0&&{deliveryLimit:e.deliveryLimit}})}function re(){let e=o;o=void 0,e?.host.destroy(),e?.slot.remove(),e?.client.reset(),x()}let le=()=>$.active||g!==void 0||o!==void 0&&!o.background;function me(e,a){if(o?.client!==e)return;Q(o.recovery,a);let p=Re(a);o.slot.hidden=p,p!==o.background&&(o.background=p,p?c("run_background",o.entryId):T=y,x())}function pe(e,a,p){let v=e.client.view;if(!a||e.background||!v?.screen||v.paywall||v.pendingRequest||v.stopped||v.status!=="waiting")return;let K=Ke.parse({operation:"close",requestId:crypto.randomUUID(),nodeId:v.nodeId,visit:v.visit,revision:v.revision,customerToken:a}),j=Ce({...n,session:void 0});j.requestWithCredential("funnels",K,e.runToken,{keepalive:p}).then(()=>Y(e.recovery)).catch(()=>{}).finally(()=>j.dispose())}let ae=()=>{o&&pe(o,n.session.peek(),!0)},r=()=>Date.now()<B&&performance.now()<z;function C(e){if(e.target.release!==n.appManifestRelease||!r())return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return c("incompatible",e.id),!1}}function H(e){if(t||e.epoch!==R||e.visit!==y||document.visibilityState==="hidden")return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function W(e){if(le()){c("in_progress",e.id);return}let a=R,p=y;$.start(e.delivery?.delaySeconds??0,()=>!t&&a===R&&p===y&&document.visibilityState!=="hidden"&&C(e)&&h?.entries.some(v=>v.id===e.id&&v.funnelId===e.funnelId&&v.versionId===e.versionId&&v.event===e.event&&JSON.stringify(v.target)===JSON.stringify(e.target)&&JSON.stringify(v.delivery)===JSON.stringify(e.delivery))===!0,()=>{V(e)},()=>{J.delete(`${e.funnelId}:${e.id}`)})}async function V(e){if(le()){c("in_progress",e.id);return}if(!n.session.peek()){c("identity_required",e.id);return}let a=te.load(),p=a?.entries.find(A=>A.command.funnelId===e.funnelId&&(!A.expiresAt||Date.parse(A.expiresAt)>Date.now()));if(p){if(!X(p)){c("recovery_pending",e.id);return}let A={...p,storageKey:a.key,epoch:R,visit:y};ee.add(A.command.requestId),g=A,await F(A);return}let v=crypto.randomUUID(),K=N.claim(e.id,e.funnelId,e.delivery?.maxPerSession,v);if(K===!1){c("frequency",e.id),x();return}let j={freshStart:!0,deliveryLimit:e.delivery?.maxPerSession,deliveryTicket:K,command:ve.parse({operation:"entry_start",entryId:e.id,funnelId:e.funnelId,versionId:e.versionId,release:n.appManifestRelease,requestId:v,locale:document.documentElement.lang||"en"}),epoch:R,visit:y,target:e.target,storageKey:a?.key};ee.add(j.command.requestId),g=j,await F(j)}async function F(e){if(e.dispatching)return;e.dispatching=!0;let a=e.freshStart===!0;e.freshStart=!1;let p,v=!1,K=!1;async function j(A){if(e.epoch!==R)return;let D=A.view;if(!(e.storageKey&&D&&(Re(D)||D.paywall||D.pendingRequest))&&D&&["running","waiting"].includes(D.status))try{await A.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:D.nodeId,visit:D.visit,revision:D.revision}),Y(e)}catch(k){if(!(k instanceof G&&k.code==="FORBIDDEN"))throw k}}try{if(!e.deliveryTicket&&e.deliveryLimit!==void 0){let q=N.claim(e.command.entryId,e.command.funnelId,e.deliveryLimit,e.command.requestId,!0);q!==!1&&(e.deliveryTicket=q)}Q(e),c("starting",e.command.entryId);let A=await b.request("funnels",e.command),D=Ye.safeParse(A);if(D.success){if(D.data.scope.projectId!==f.projectId||D.data.scope.environment!==f.environment)throw new G("SCOPE_MISMATCH","Entry scope changed");e.epoch===R&&c(D.data.reason,e.command.entryId),Y(e),M(e);return}let k=Xe.parse(A);if(!k.runToken||k.scope.projectId!==f.projectId||k.scope.environment!==f.environment||k.run.source.type!=="funnel"||k.run.source.id!==e.command.funnelId||k.run.source.versionId!==e.command.versionId||e.runId!==void 0&&k.run.id!==e.runId)throw new G("INVALID_RESPONSE","Invalid entry Run");if(N.accept(e.deliveryTicket,k.run.id),e.epoch!==R){M(e),c("identity_changed",e.command.entryId);return}Q(e,k.run);let L=Ae({...n,runToken:k.runToken,funnelId:e.command.funnelId,initialResponse:a?A:void 0});p=L,K=!0,await L.get(),K=!1;let ne=L.view;if(!ne||ne.id!==k.run.id||ne.source.type!=="funnel"||ne.source.id!==e.command.funnelId||ne.source.versionId!==e.command.versionId)throw new G("INVALID_RESPONSE","Entry Run version changed");if(!["running","waiting"].includes(ne.status)){Y(e),M(e),c("run_ended",e.command.entryId);return}let{showFunnelRun:fe}=await import("./funnel-runtime-host-NZAV6C5O.js");if(!H(e)){await j(L),c("left_screen",e.command.entryId),M(e);return}let Fe=!1,xe=!1;if(o&&!o.background){await j(L),c("in_progress",e.command.entryId),M(e);return}o&&re();let ie=document.createElement("div");ie.hidden=Re(ne),n.container.append(ie);let ke=await fe(ie,{...n.host,client:L,appManifestRelease:n.appManifestRelease,onState(q){me(L,q),Z(n.host?.onState,q)},onDismiss(q){Fe=!0,ie.remove(),q&&!["running","waiting"].includes(q.status)&&Y(e),o?.client===L&&(o=void 0,L.reset(),x(),q&&q.status!=="completed"&&c("run_ended",e.command.entryId)),Z(n.host?.onDismiss,q)},onComplete(q){xe=!0,Y(e),o?.client===L&&re(),Z(n.host?.onComplete,q)},onError(q){Z(n.host?.onError,q),o?.client===L&&q instanceof G&&q.code==="FORBIDDEN"&&(Y(e),re(),c("run_ended",e.command.entryId))}}).catch(q=>{throw ie.remove(),q});if(!H(e)||Fe||xe){ke.destroy(),ie.remove(),H(e)||await j(L),M(e);return}let he=Re(L.view??ne);ie.hidden=he,o={host:ke,client:L,slot:ie,entryId:e.command.entryId,background:he,runToken:k.runToken,owner:n.session.peek(),recovery:e},he||(T=e.visit),v=!0,M(e),c("started",e.command.entryId),he&&c("run_background",e.command.entryId)}catch(A){A instanceof G&&(!p||K&&A.code==="FORBIDDEN")&&A.status!==void 0&&A.status>=400&&A.status<500&&!A.retryable&&(Y(e),M(e)),e.epoch===R&&!t&&(c("start_failed",e.command.entryId),Z(n.host?.onError,A))}finally{v||p?.reset(),e.dispatching=!1}}function X(e){if(e.command.release!==n.appManifestRelease||e.target.release!==n.appManifestRelease)return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function ye(){if(le())return!1;let e=te.load();for(let a of e?.entries??[]){if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now()){te.forget(e.key,a.command.requestId);continue}if(a.command.requestId===o?.recovery.command.requestId||ee.has(a.command.requestId)||!X(a))continue;ee.add(a.command.requestId);let p={...a,storageKey:e.key,epoch:R,visit:y};return g=p,F(p),!0}return!1}function ue(){if(m=!1,$.recheck(),t||!i||document.visibilityState==="hidden")return;se();let e=o!==void 0&&!o.background;if(e&&(T=y),!ye()){if(!r()){E=!0;return}E=!1;for(let a of h?.entries??[]){let p=`${a.funnelId}:${a.id}`;if(!(a.event!=="screen_enter"||J.has(p)||!C(a))){if(!n.session.peek()){c("identity_required",a.id);continue}if(T===y){J.add(p),e&&c("in_progress",a.id);continue}if(g||$.active){c("in_progress",a.id);return}J.add(p),W(a);break}}}}let x=()=>{!m&&!t&&(m=!0,queueMicrotask(ue))};function se(){let e=location.origin+location.pathname;return e===P?!1:(P=e,y++,$.cancel(),E=!0,J.clear(),ee.clear(),!0)}function oe(){se()&&x()}function ce(e){if(!e.isTrusted||e.button!==0||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||document.visibilityState==="hidden")return;let a=e.target;if(!(a instanceof Element)||a.closest("[data-indiana-funnel]"))return;let p=a.closest("button,a,input");if(!(!p||p.matches(":disabled,[aria-disabled='true']")||p.closest("[hidden],[inert],[aria-hidden='true']")))for(let v of h?.entries??[]){let K=v.target.button;if(!(v.event!=="button_click"||!K||!C(v))){try{let j=be(document);if(!p.matches(K.selector)||j(K.selector,p)!==1)continue}catch{c("incompatible",v.id);continue}W(v);break}}}async function Me(){if(t)return;if(s)return s;let e=++u,a=new AbortController;_=a;let p,v=new Promise((A,D)=>{p=()=>D(new G("TIMEOUT","Funnel entry configuration read cancelled or timed out")),a.signal.addEventListener("abort",p,{once:!0})}),K=setTimeout(()=>a.abort(),n.timeoutMs??5e3),j=(async()=>{let A=async()=>{let fe=await w(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:a.signal});if(!fe.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",fe.status);return ge.parse(await fe.json())},D=await Promise.race([A(),v]),k=Date.parse(D.validatedAt),L=Date.parse(D.validUntil);if(D.scope.projectId!==f.projectId||D.scope.environment!==f.environment||D.scope.environmentId!==n.environmentId||D.release!==n.appManifestRelease||L<=Date.now()||k>Date.now()+5e3||L-k>6e4||L<=k)throw new G("INVALID_RESPONSE","Entry configuration scope or deadline changed");if(t||e!==u)return;let ne=h===void 0;h=D,B=L,z=performance.now()+Math.min(L-Date.now(),6e4),$.recheck(),(ne||E)&&x()})();s=j;try{await j}finally{clearTimeout(K),a.signal.removeEventListener("abort",p),s===j&&(s=void 0)}}async function on(){if(!(!i||t)){try{await Me()}catch{t||c("configuration_unavailable")}x()}}let Ne=Ie({document,run:on,delay:()=>i&&!t?15e3:void 0});return{async start(){i||t||(i=!0,P=location.origin+location.pathname,O=Ee(oe),S=n.session.subscribeIdentity(()=>{R++,$.cancel(),N.release(g?.deliveryTicket),E=!0,g=void 0,J.clear(),T=-1,ee.clear(),o&&pe(o,o.owner,!1),re(),x()}),l=new MutationObserver(x),l.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",ce,!0),document.addEventListener("visibilitychange",x),addEventListener("pagehide",ae),await Ne.refresh())},refresh:Me,async retry(){g&&!t&&g.epoch===R&&await F(g)},destroy(){t=!0,u++,$.cancel(),N.release(g?.deliveryTicket),Ne.destroy(),_?.abort(),l?.disconnect(),O?.(),S?.(),document.removeEventListener("click",ce,!0),document.removeEventListener("visibilitychange",x),removeEventListener("pagehide",ae),ae(),re(),b.dispose(),h=void 0}}}function An(n){let d=we(n.baseUrl),f=n.fetch??globalThis.fetch.bind(globalThis),b,w=0,h=0,t=!1,i=!1,u=!1,y=0,P=0,R=-1,B=!1,z="",m,s,E,_,O=new Set,S,l,o,T=(r,C)=>Z(n.onStatus,r,C),g=Pe(),M=()=>{try{return n.deliveryIdentity?.()}catch{return}},J=()=>JSON.stringify(M()),c=Se({storage:n.deliveryStorage,binding:()=>{let r=M();return r?.id?[d,n.scope.projectId,n.scope.environment,n.environmentId,r.type,r.id]:void 0},unavailable:()=>T("delivery_unavailable")}),$=()=>Date.now()<w&&performance.now()<h;function N(r){try{return $()&&r.target.release===n.appManifestRelease&&de(r.target.render,document,location.pathname,()=>{})}catch{return T("incompatible",r.id),!1}}function ee(){let r=o;o=void 0,r?.host.destroy(),r?.slot.remove()}async function te(r){if(r.dispatching)return;r.dispatching=!0;let C=y;try{let H=await r.process.open({operation:"entry_start",funnelId:r.entry.funnelId,versionId:r.entry.versionId,entryId:r.entry.id,release:n.appManifestRelease,locale:n.locale??"en"});c.accept(r.deliveryTicket,H.run.id);let{showFunnelRun:W}=await import("./funnel-runtime-host-NZAV6C5O.js");if(t||C!==y||l!==r)return;let V=document.createElement("div");n.container.append(V),R=P;let F=await W(V,{...n.host,client:H.controller,appManifestRelease:n.appManifestRelease,onDismiss(X){o?.process===r.process&&(o=void 0,V.remove()),Z(n.host?.onDismiss,X)}});if(t||C!==y||l!==r){F.destroy(),V.remove();return}o={entry:r.entry,process:r.process,host:F,slot:V,deliveryTicket:r.deliveryTicket},l=void 0,T("run_presented",r.entry.id)}catch(H){if(t||C!==y||l!==r)return;H instanceof G&&"result"in H?(c.release(r.deliveryTicket),l=void 0,r.process.destroy(),T("suppressed",r.entry.id),Q()):T("entry_unavailable",r.entry.id)}finally{r.dispatching=!1}}function Y(r){if(t||i||l||o||S||g.active||R===P||!N(r))return;let C=`${P}:${r.id}`;if(O.has(C))return;O.add(C);let H=P,W=y,V=J();g.start(r.delivery?.delaySeconds??0,()=>!t&&y===W&&P===H&&J()===V&&document.visibilityState!=="hidden"&&N(r)&&b?.entries.some(F=>F.id===r.id&&F.funnelId===r.funnelId&&F.versionId===r.versionId&&F.event===r.event&&JSON.stringify(F.target)===JSON.stringify(r.target)&&JSON.stringify(F.delivery)===JSON.stringify(r.delivery))===!0,()=>{let F=c.claim(r.id,r.funnelId,r.delivery?.maxPerSession,crypto.randomUUID());if(F===!1){T("frequency",r.id),Q();return}try{let X={entry:r,process:n.createProcess(r),visit:P,deliveryTicket:F};l=X,te(X)}catch(X){c.release(F),T("entry_unavailable",r.id),Z(n.host?.onError,X)}},()=>{O.delete(C)})}function Q(){B||t||(B=!0,queueMicrotask(()=>{if(B=!1,g.recheck(),!(t||i||document.visibilityState==="hidden"||!$()||l||o||S||g.active||R===P)){for(let r of b?.entries??[])if(r.event==="screen_enter"&&!O.has(`${P}:${r.id}`)&&N(r)){Y(r);break}}}))}function re(r){if(!r.isTrusted||r.defaultPrevented||!(r.target instanceof Element)||l||o||S||R===P)return;let C=be(document,()=>{});for(let H of b?.entries??[]){let W=H.target.button;if(H.event!=="button_click"||!W||!N(H))continue;let V=r.target.closest(W.selector);if(!(!V||V.tagName.toLowerCase()!==W.tag||C(W.selector)!==1||V.matches(":disabled")||V.closest('[inert],[hidden],[aria-hidden="true"]'))){Y(H);break}}}let le=()=>{let r=location.origin+location.pathname;r!==z&&(z=r,P++,g.cancel(),O.clear(),Q())};async function me(){if(t)return;if(s)return s;let r=y,C=new AbortController;m=C;let H,W=new Promise((ye,ue)=>{H=ue}),V=()=>H(new G("TIMEOUT","Funnel entry read cancelled"));C.signal.addEventListener("abort",V,{once:!0});let F=setTimeout(()=>C.abort(),n.timeoutMs??5e3),X=(async()=>{let ye=encodeURIComponent(JSON.stringify(["funnel-process/1"])),ue=async()=>{let ce=await f(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}&executionContracts=${ye}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:C.signal});if(!ce.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",ce.status);return ge.parse(await ce.json())},x=await Promise.race([ue(),W]),se=Date.parse(x.validatedAt),oe=Date.parse(x.validUntil);if(x.scope.projectId!==n.scope.projectId||x.scope.environment!==n.scope.environment||x.scope.environmentId!==n.environmentId||x.release!==n.appManifestRelease||oe<=Date.now()||se>Date.now()+5e3||oe<=se||oe-se>6e4)throw new G("INVALID_RESPONSE","Entry scope or deadline changed");t||r!==y||(b=x,w=oe,h=performance.now()+Math.min(oe-Date.now(),6e4),g.recheck(),Q())})();s=X;try{await X}finally{clearTimeout(F),C.signal.removeEventListener("abort",V),s===X&&(s=void 0)}}async function pe(){if(!(!u||t))try{await me()}catch{t||T("configuration_unavailable")}}let ae=Ie({document,run:pe,delay:()=>u&&!t?15e3:void 0});return{async start(){u||t||(u=!0,z=location.origin+location.pathname,E=Ee(le),_=new MutationObserver(Q),_.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",re,!0),document.addEventListener("visibilitychange",Q),await ae.refresh())},refresh:me,async retry(){l&&!t&&await te(l)},async syncIdentity(){g.cancel();let r=o??l??S;if(!r){i=!1,Q();return}try{let C=await r.process.syncIdentity();return i=!1,S===r&&(l={...r,visit:P},S=void 0,await te(l)),C}catch(C){throw r.process.view||(S={...r,visit:P},l=void 0,ee()),C}},async detach(){i=!0,y++,g.cancel(),m?.abort();let r=o??l??S;r&&(S={...r,visit:P}),l=void 0,ee(),r&&await r.process.detach()},destroy(){t=!0,y++,g.cancel(),ae.destroy(),m?.abort(),_?.disconnect(),E?.(),document.removeEventListener("click",re,!0),document.removeEventListener("visibilitychange",Q);let r=o??l??S;c.release(r?.deliveryTicket),l=void 0,S=void 0,ee(),r?.process.destroy(),b=void 0}}}async function Dn(n,d){return(await import("./paywall-DKTGQZDJ.js")).showPaywall(n,d)}async function dt(){return await Promise.all([import("./paywall-DKTGQZDJ.js"),import("./screen-renderer-HW2WXDTR.js")]),Dn}async function lt(...n){return n[1]=ze(n[1]),(await import("./paywall-session-YKE2CHHI.js")).createPaywallSession(...n)}async function ut(...n){let d=n[1].signal?.aborted?void 0:We(n[1].client);try{return import("./screen-renderer-HW2WXDTR.js").catch(()=>{}),import("./paywall-DKTGQZDJ.js").catch(()=>{}),await(await rn(()=>import("./funnel-runtime-host-NZAV6C5O.js"),n[1].prepared)).showFunnelRun(...n)}finally{d?.()}}async function rn(n,d){try{return await n()}catch(f){throw d&&d.state!=="adopted"&&await import("./funnel-paywall-prerender-MD4UI2AP.js").then(b=>b.preparedInternals(d)?.release(),()=>{}),f}}async function ft(...n){return import("./screen-renderer-HW2WXDTR.js").catch(()=>{}),import("./paywall-DKTGQZDJ.js").catch(()=>{}),(await rn(()=>import("./funnel-host-purchase-HBQOWEES.js"),n[1].prepared)).showFunnelPurchase(...n)}async function mt(...n){return import("./funnel-host-purchase-HBQOWEES.js").catch(()=>{}),import("./screen-renderer-HW2WXDTR.js").catch(()=>{}),(await import("./funnel-paywall-prerender-MD4UI2AP.js")).prerenderFunnelPurchase(...n)}async function pt(){await Promise.all([import("./funnel-paywall-prerender-MD4UI2AP.js"),import("./funnel-host-purchase-HBQOWEES.js"),import("./paywall-DKTGQZDJ.js"),import("./screen-renderer-HW2WXDTR.js"),import("./paywall-content-SML4CL2Q.js"),import("./check-response-MCT5RGOM.js"),import("./operation-contracts-C6CMAO6S.js")])}async function yt(...n){return(await import("./funnel-route-prediction-XNIKDJIM.js")).predictFunnelStart(...n)}async function ht(...n){return(await import("./funnel-route-prediction-XNIKDJIM.js")).predictedPaywallLoadingDocument(...n)}async function gt(...n){return(await import("./content-VTHRQSFT.js")).mountContent(...n)}async function vt(...n){return(await import("./content-VTHRQSFT.js")).prepareContent(...n)}export{G as LongplayError,I as MerchantBridgeError,yn as createBrowserFunnelCommandStorage,En as createBrowserFunnelPurchaseStorage,vn as createConfigurationSync,mn as createFeatureClient,wn as createFunnelClient,Rn as createFunnelPageExperiments,Sn as createFunnelProcess,bn as createFunnelPurchaseClient,Ae as createFunnelRunController,Cn as createIamFunnelEntries,An as createIamFunnelProcessEntries,Pn as createLocalFunnelClient,pn as createLongplay,Tn as createMerchantBridge,lt as createPaywallSession,In as evaluateFunnelNode,sn as formatCouponDiscount,an as formatCouponMoney,cn as formatCouponTerms,hn as getPaywallRecovery,un as isPaywallOperationComplete,fn as isPaywallOperationPending,ln as isPaywallUpdateOperation,dn as isPaywallUpdateQuote,gt as mountContent,yt as predictFunnelStart,ht as predictedPaywallLoadingDocument,pt as preloadFunnelPurchase,dt as preloadPaywall,vt as prepareContent,gn as preparePaywallFallback,mt as prerenderFunnelPurchase,ft as showFunnelPurchase,ut as showFunnelRun,Dn as showPaywall};
|