@tinkerlandai/longplay-sdk 0.10.47 → 0.10.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +7 -0
  3. package/README.zh-CN.md +2 -0
  4. package/dist/{chunk-SH5YAVAL.js → chunk-AACOUGCH.js} +1 -1
  5. package/dist/{chunk-IZ3EKFZE.js → chunk-C5VTYFI7.js} +1 -1
  6. package/dist/{chunk-EG5KX2GQ.js → chunk-CIYPQIPH.js} +1 -1
  7. package/dist/chunk-CMKMFT4H.js +1 -0
  8. package/dist/{chunk-OU2PQMUK.js → chunk-F4X2JSXX.js} +1 -1
  9. package/dist/chunk-FEEBBJEK.js +1 -0
  10. package/dist/{chunk-UI2ASG3W.js → chunk-IA66JXF6.js} +1 -1
  11. package/dist/{chunk-HNSYKEV4.js → chunk-JOTTHPSC.js} +2 -2
  12. package/dist/{chunk-3SRNEKBL.js → chunk-JXWRLNK7.js} +1 -1
  13. package/dist/{chunk-AQMIPU7N.js → chunk-KN2QFJOQ.js} +1 -1
  14. package/dist/{chunk-2IZ7ET6O.js → chunk-MOHKDHS2.js} +1 -1
  15. package/dist/{chunk-BGXHQKUU.js → chunk-QRHCZEV6.js} +1 -1
  16. package/dist/{chunk-UDVGZQ7Y.js → chunk-YONZ4NEY.js} +1 -1
  17. package/dist/{chunk-G3C322IZ.js → chunk-ZV23WM25.js} +1 -1
  18. package/dist/{content-LZCSQYX7.js → content-B3RWDOOH.js} +1 -1
  19. package/dist/{funnel-host-purchase-QTC45BIJ.js → funnel-host-purchase-QRREIXEJ.js} +1 -1
  20. package/dist/{funnel-paywall-prerender-Z5QR4BQV.js → funnel-paywall-prerender-SM7FH55U.js} +1 -1
  21. package/dist/{funnel-runtime-host-4WRNN5WT.js → funnel-runtime-host-T7QZU2NO.js} +1 -1
  22. package/dist/index.d.ts +3 -0
  23. package/dist/index.js +1 -1
  24. package/dist/native-shell.js +1 -1
  25. package/dist/openrouter.js +1 -1
  26. package/dist/page.js +1 -1
  27. package/dist/paywall-6OURDDMJ.js +1 -0
  28. package/dist/{paywall-content-AII4EQZS.js → paywall-content-MVU3X635.js} +1 -1
  29. package/dist/{paywall-session-NRG2GZJR.js → paywall-session-ISBKCULC.js} +1 -1
  30. package/dist/react-native.js +1 -1
  31. package/dist/server.js +1 -1
  32. package/dist/visual.js +1 -1
  33. package/package.json +1 -1
  34. package/dist/chunk-APWXKYRG.js +0 -1
  35. package/dist/chunk-ZHSMUTI6.js +0 -1
  36. package/dist/paywall-QGZNK5QL.js +0 -1
  37. /package/dist/{chunk-HNSYKEV4.js.LEGAL.txt → chunk-JOTTHPSC.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-G3C322IZ.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-3SRNEKBL.js";import{a as l}from"./chunk-ZDIWOE4Q.js";import{h as W}from"./chunk-FYD7CMS7.js";import{b as be}from"./chunk-EG5KX2GQ.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-AII4EQZS.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-ZV23WM25.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-JXWRLNK7.js";import{a as l}from"./chunk-ZDIWOE4Q.js";import{h as W}from"./chunk-FYD7CMS7.js";import{b as be}from"./chunk-CIYPQIPH.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-MVU3X635.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{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-3SRNEKBL.js";import{a as n}from"./chunk-ZDIWOE4Q.js";import{a as g}from"./chunk-3VUPVXAV.js";import{b as f}from"./chunk-EG5KX2GQ.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
+ 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-JXWRLNK7.js";import{a as n}from"./chunk-ZDIWOE4Q.js";import{a as g}from"./chunk-3VUPVXAV.js";import{b as f}from"./chunk-CIYPQIPH.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{a as T,b as se}from"./chunk-3ITNAFAH.js";import{b as re,h as ae,j as ce}from"./chunk-OU2PQMUK.js";import{E as M,a as J}from"./chunk-G3C322IZ.js";import{a as b,b as f,c as m}from"./chunk-Y2ASROJH.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-TIOPNTMP.js";import{a as oe,b as j}from"./chunk-RFWVXTZ7.js";import{b as W,j as X}from"./chunk-KSME3N3A.js";import{n as $}from"./chunk-LE32WTZ7.js";import{b as ie}from"./chunk-3SRNEKBL.js";import{a as B}from"./chunk-FRRKTQNZ.js";import{a as s}from"./chunk-ZDIWOE4Q.js";import{h as Q}from"./chunk-FYD7CMS7.js";import{b as K}from"./chunk-XVCSRZX4.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-C6CMAO6S.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-C6CMAO6S.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-C6CMAO6S.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-C6CMAO6S.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};
1
+ import{a as T,b as se}from"./chunk-3ITNAFAH.js";import{b as re,h as ae,j as ce}from"./chunk-F4X2JSXX.js";import{E as M,a as J}from"./chunk-ZV23WM25.js";import{a as b,b as f,c as m}from"./chunk-Y2ASROJH.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-TIOPNTMP.js";import{a as oe,b as j}from"./chunk-RFWVXTZ7.js";import{b as W,j as X}from"./chunk-KSME3N3A.js";import{n as $}from"./chunk-LE32WTZ7.js";import{b as ie}from"./chunk-JXWRLNK7.js";import{a as B}from"./chunk-FRRKTQNZ.js";import{a as s}from"./chunk-ZDIWOE4Q.js";import{h as Q}from"./chunk-FYD7CMS7.js";import{b as K}from"./chunk-XVCSRZX4.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-C6CMAO6S.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-C6CMAO6S.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-C6CMAO6S.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-C6CMAO6S.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};
@@ -1 +1 @@
1
- import{b as Kn}from"./chunk-APWXKYRG.js";import{a as Jn,b as jn,c as mn,d as wn,e as $e,f as Bn,h as Wn,i as Yn,j as Xn,k as Zn}from"./chunk-L7C5TKKV.js";import{b as Sn,c as et}from"./chunk-UI2ASG3W.js";import{a as Mn}from"./chunk-W32FI2A2.js";import{c as $n,e as xn,f as Gn,h as Qn,i as _e,j as tn,k as zn,l as rn}from"./chunk-2UXX62Y4.js";import{b as Fn}from"./chunk-W3B4GT74.js";import{K as nn}from"./chunk-LE32WTZ7.js";import{a as Me,d as Nn}from"./chunk-LSHIR6QM.js";import{c as On,e as _n,f as Ln,g as Hn,h as Vn,i as Un}from"./chunk-OPUIFAQS.js";import{b as kn}from"./chunk-HYX3EDZS.js";import{B as fn}from"./chunk-EGFVGCDG.js";import{x as Dn}from"./chunk-YFLVGOCJ.js";import{t as An}from"./chunk-MQ5LJEWV.js";import{C as Tn}from"./chunk-JDIFYMSA.js";import{a as m}from"./chunk-ZDIWOE4Q.js";import{a as Ee}from"./chunk-DSPLGTQI.js";async function yn(t){let{session:b,load:P}=ut(t);try{return await P(),b}catch(n){throw b.destroy(),n}}function ut(t){let b=t.view;if(!b?.paywall)throw new m("INVALID_REQUEST","The current node is not a Paywall");let P=b.paywall.receiptId,n=b.nodeId,g=b.visit,A=b.paywall.resolution,o=b.paywall,O="document"in A?{document:A.document,offering:A.offering,capabilities:A.capabilities}:null;function u(){let i=o.resolution;return"document"in i?i:O&&{...i,document:O.document,offering:O.offering,capabilities:On(i.capabilities,O.capabilities)}}function C(i){if(!_n(i,A))throw new m("INVALID_RESPONSE","The pinned Paywall binding changed")}let R=!1,x=new Set,ie=null;function w(){let i=u();if(i&&!R)for(let a of x)Ee(a,structuredClone(i))}async function _(){I();let i=u();if(i)return structuredClone(i);if(!ie){let a=(async()=>{if("document"in o.resolution||!t.resolvePaywall)throw new m("INVALID_RESPONSE","Public Paywall reader is unavailable");let q=await Sn(t,o.resolution);return I(),C(q),O={document:q.document,offering:q.offering,capabilities:q.capabilities},w(),u()})();ie=a;let s=()=>{ie===a&&(ie=null)};a.then(s,s)}return ie.then(a=>structuredClone(a))}let l=new AbortController,E=(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===n&&i.visit===g&&i.input.type==="paywall_quote")?.requestId??b.paywall.purchaseRequestId,S=0,re=null,U=new Set,M=null,z=new Map;function Q(i){if(i.purchase&&i.purchase.receiptId!==P)throw new m("INVALID_RESPONSE","Purchase receipt changed");let a=i.run.paywall;return i.purchase??(a?.receiptId===P?a:null)}function I(){if(R)throw new m("IDENTITY_CHANGED","Paywall presentation has closed")}function Z(i,a,s){if(I(),a!==S||s!==void 0&&o.quote?.operationId!==s)return!1;let q=o.selectionGeneration??0,f=i.run.paywall;if(f?.receiptId===P){if((f.selectionGeneration??0)<(o.selectionGeneration??0))return!1;C(f.resolution)}let p=Q(i),F=f?.receiptId===P&&(f.selectionGeneration??0)>q,y=F?p?.quote??null:p?.quote??o.quote,Y=p?.operation??(y?.operationId===o.quote?.operationId?o.operation:null);return o.quote&&y&&Vn(o.quote,y),y&&Y&&Ln(Y,{operationId:y.operationId,membershipId:fn(y)?y.membershipId:null,...fn(y)?{featureQuantities:y.featureQuantities??{}}:{}},"Purchase operation changed"),(F||y?.operationId!==o.quote?.operationId)&&(S++,f?.receiptId===P&&(E=f.purchaseRequestId)),f?.canReselect===!0&&f.purchaseRequestId===M&&!(t.pendingCommands??[t.pendingCommand]).some(X=>X?.requestId===M)&&(M=null),o={...o,...f?.receiptId===P?f:{},...s!==void 0&&!F&&p?.canReselect!==void 0?{canReselect:p.canReselect}:{},quote:y,operation:Un(o.operation,Y,!0)},w(),!0}function N(i,a,s){return new Promise((q,f)=>{let p=!1,F=()=>{clearTimeout(j),l.signal.removeEventListener("abort",X)},y=ge=>{p||(p=!0,F(),q(ge))},Y=ge=>{p||(p=!0,F(),f(ge))},X=()=>Y(new m("IDENTITY_CHANGED","Paywall presentation has closed")),j=setTimeout(()=>Y(new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,s)),Math.max(0,a-Date.now()));l.signal.addEventListener("abort",X,{once:!0}),l.signal.aborted&&X(),i.then(y,Y)})}function qe(i){return new Promise(a=>{let s=()=>{clearTimeout(q),l.signal.removeEventListener("abort",s),a()},q=setTimeout(s,i);l.signal.addEventListener("abort",s,{once:!0}),l.signal.aborted&&s()})}function he(i,a){I();let s=z.get(i)??t.pendingCommands?.find(p=>p.requestId===i)??t.pendingCommand;if(s?.operation==="submit"&&s.requestId===i&&s.nodeId===n&&s.visit===g){a.type==="paywall_quote"&&s.input.type==="paywall_quote"&&s.input.predecessor&&!a.predecessor&&(a={...a,predecessor:s.input.predecessor});let p=nn.parse(s),F=nn.parse({...s,input:a});if(p.operation!=="submit"||F.operation!=="submit"||JSON.stringify(p.input)!==JSON.stringify(F.input))throw new m("CONFLICT","A purchase request cannot change its input");return z.set(i,p),p}let q=t.view;if(!q||q.nodeId!==n||q.visit!==g||q.paywall?.receiptId!==P)throw new m("PRECONDITION_FAILED","The Paywall visit has changed");let f=nn.parse({operation:"submit",requestId:i,nodeId:n,visit:g,revision:q.revision,input:structuredClone(a)});if(f.operation!=="submit")throw new m("INVALID_REQUEST","A purchase submission is required");return z.set(i,f),f}async function we(i,a){I();let{requestId:s,input:q}=i,f=Date.now()+3e4;U.add(s);try{let p=await N(t.submit(i),f,s);for(;p.run.pendingRequest?.requestId===s&&Date.now()<f&&!R&&(await qe(Math.min(1e3,f-Date.now())),!(R||Date.now()>=f));)p=await N(t.resume(s),f,s);if(R)throw new m("IDENTITY_CHANGED","Paywall presentation has closed");if(p.run.pendingRequest?.requestId===s)throw new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,s);if(!Z(p,a,q.type==="paywall_confirm"||q.type==="paywall_cancel"?q.operationId:void 0))throw new m("PRECONDITION_FAILED","The purchase selection has changed");M===s&&(M=null)}catch(p){if(M=s,q.type==="paywall_quote"&&t.settle&&!R&&p instanceof m&&p.status!==void 0&&![401,425].includes(p.status)&&!p.retryable&&p.recovery!=="recover_operation")try{if((await N(t.settle(s),f,s)).settlement?.state==="settled"){let y=await N(t.get(),f,s);Z(y,a)&&y.run.paywall?.purchaseRequestId===s&&o.canReselect===!0&&z.delete(s)}}catch{}throw p instanceof m&&p.code==="COMMAND_PENDING"&&p.status===void 0&&z.delete(s),p}finally{U.delete(s)}}async function W(i){if(!o.quote)throw new m("INVALID_REQUEST","A quoted purchase is required");let a=i==="confirm"?"paywall_confirm":"paywall_cancel",s=[...z.values(),...t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])].find(f=>f.operation==="submit"&&f.input.type===a&&"operationId"in f.input&&f.input.operationId===o.quote.operationId),q=s?.operation==="submit"&&s.input.type===a&&"operationId"in s.input&&s.input.operationId===o.quote.operationId?s.requestId:crypto.randomUUID();if(await we(he(q,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.quote.operationId,...i==="confirm"&&o.quote.merchantTerms?{merchantConfirmation:Dn(o.quote.merchantTerms)}:{}}),S),!o.operation)throw new m("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(o.operation)}let le={get view(){return structuredClone(u())},get quote(){return o.quote?structuredClone(o.quote):null},get operation(){return o.operation?structuredClone(o.operation):null},get webViewUrl(){return t.webViewUrl},get locale(){return t.view?.locale??b.locale},get canReselect(){return o.canReselect===!0&&M===null},get recovery(){let i=t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[]),a=t.pendingPurchase;if(a&&(a.receiptId!==P||a.operationId!==o.quote?.operationId))return{type:"recover",operationId:a.operationId,requestId:i[0]?.requestId??null};let s=Me({quote:o.quote,operation:o.operation,requestId:i[0]?.requestId??M??E,pending:U.size>0||i.length>0||M!==null,destroyed:R,canReselect:o.canReselect});return s.type==="recover"&&s.requestId===null&&!R&&t.hasDurableJournal===!0&&!o.quote&&!o.operation&&(o.selectionGeneration??0)===0&&!a&&!i.length&&!U.size&&!E?{type:"native",operationId:null}:s},get pendingCancellation(){return!R&&(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===n&&i.visit===g&&i.input.type==="paywall_cancel"&&i.input.operationId===o.quote?.operationId)},subscribe(i){return R?()=>{}:(x.add(i),()=>x.delete(i))},async refresh(){I();let i=S,a=await t.get();if(Z(a,i),a.run.paywall?.receiptId!==P)throw new m("PRECONDITION_FAILED","Paywall presentation has changed");return _()},preview(i){let a=u();if(!a)return Promise.reject(new m("PRECONDITION_FAILED","Load the Paywall presentation first"));if(E&&E!==i.requestId&&(re||o.canReselect!==!0))return Promise.reject(new m("COMMAND_PENDING","Retry the original purchase before starting another"));let s=a.document.buttons[i.actionId],q=s?.type==="checkout"?kn(s.product,i.selection,a.capabilities):null;if(!q)return Promise.reject(new m("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let f=An(a.document.screen,q,i.selection,a.capabilities),p=E!==i.requestId&&(o.selectionGeneration??0)>0?{operationId:o.quote?.operationId??null,generation:o.selectionGeneration??0}:void 0,F=t.view?.parameters.commerce;if(F&&typeof F=="object"&&!Array.isArray(F)&&F.intent==="subscription_change"&&!i.subscriptionChange)return Promise.reject(new m("INVALID_REQUEST","Choose the existing membership for this subscription change"));if(i.subscriptionChange&&i.nativeOffer)return Promise.reject(new m("INVALID_REQUEST","A web membership change cannot include a store offer"));if(p&&o.canReselect!==!0)return Promise.reject(new m("COMMAND_PENDING","Original purchase requires authoritative termination"));let y;try{y=he(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:q,...Object.keys(f).length?{featureQuantities:f}:{},...p?{predecessor:p}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{},...i.subscriptionChange?{subscriptionChange:i.subscriptionChange}:{}})}catch(j){return Promise.reject(j)}if(E===i.requestId&&re)return re;E!==i.requestId&&S++;let Y=S;E=i.requestId;let X=(async()=>{if(await we(y,Y),!o.quote)throw new m("INVALID_RESPONSE","The accepted quote is missing");return Hn(o.quote,{productVersionId:q,featureQuantities:f,subscriptionChange:i.subscriptionChange},"The selected purchase changed"),structuredClone(o.quote)})();return re=X,X.then(()=>{re===X&&(re=null)},j=>{re===X&&(re=null),E===i.requestId&&t.pendingCommand?.requestId!==i.requestId&&j instanceof m&&j.status!==void 0&&j.status<500&&![401,425].includes(j.status)&&(E=null)}),X},confirm:()=>W("confirm"),cancel:()=>W("cancel"),async read(){if(I(),!o.quote)throw new m("INVALID_REQUEST","A quoted purchase is required");let i=o.quote.operationId,a=S,s=t.pendingCommands?.find(y=>y.operation==="submit"&&(y.input.type==="paywall_confirm"||y.input.type==="paywall_cancel")&&y.input.operationId===i)??t.pendingCommand;s?.operation==="submit"&&(s.input.type==="paywall_confirm"||s.input.type==="paywall_cancel")&&s.input.operationId===i&&await t.settle?.(s.requestId);let q=await t.get(void 0,{receiptId:P,operationId:i});I();let f=Q(q);if(f?.quote&&f.quote.operationId!==i||f?.operation&&f.operation.operationId!==i)throw new m("INVALID_RESPONSE","Purchase operation changed");let p=Z(q,a,i),F=p?o.operation:f?.operation;if(!F)throw new m("INVALID_RESPONSE","The current purchase result is missing");return p&&U.size===0&&!(t.pendingCommands?.length??(t.pendingCommand?1:0))&&(M=null),structuredClone(F)},destroy(){R=!0,L(),x.clear(),l.abort(),z.clear()}},L=t.subscribe(i=>{R||i.nodeId!==n||i.visit!==g||i.paywall?.receiptId!==P||(i.paywall.selectionGeneration??0)<(o.selectionGeneration??0)||(C(i.paywall.resolution),o={...o,resolution:i.paywall.resolution},w())});return{session:le,load:_}}function nt(t){let b=new Set,P=new Set,n=null;async function g(u,C){let R=!1;for(;!t.stopped&&t.key===u&&t.client.pendingCommand?.requestId===C;){if(!t.client.settle)throw new m("COMMAND_PENDING","The original display acknowledgement is still pending");await t.client.settle(C),R=!0,t.client.pendingCommand?.requestId===C&&await new Promise(x=>setTimeout(x,1500))}t.stopped||t.key!==u||(R&&await t.client.get(),!(t.stopped||t.key!==u)&&b.add(u))}function A(u,C){n=C;let R=()=>{n===C&&(n=null),P.delete(u)};return C.then(R,x=>{R(),t.busy||t.fail(x)}),C}function o(u){if(t.reviewing||b.has(u)||P.has(u)||t.stopped)return;P.add(u);let C=async()=>{if(t.reviewing||t.stopped||t.key!==u||b.has(u)){P.delete(u);return}if(t.busy||t.client.pendingCommand){setTimeout(()=>{C()},250);return}let R=(async()=>{if(t.staleRead){if(await t.staleRead,t.stopped||t.key!==u)return;if(t.client.pendingCommand){setTimeout(()=>{C()},250);return}}let x=t.client.view,ie=t.expected(),w=ie.requestId;try{await t.client.submit({operation:"shown",...ie})}catch(_){if(!(_ instanceof m)||_.code!=="CONFLICT"||_.status!==409||t.client.pendingCommand)throw _;await t.client.get();let l=t.client.view;if(t.stopped||t.reviewing||t.key!==u||!l||!x||l.id!==x.id||l.source.versionId!==x.source.versionId||l.nodeId!==ie.nodeId||l.visit!==ie.visit||l.revision<=ie.revision||l.stopped||!l.screen&&(!l.paywall||l.paywall.receiptId!==x.paywall?.receiptId)||!["running","waiting"].includes(l.status)||t.client.pendingCommand)throw _;let c=t.expected();w=c.requestId,await t.client.submit({operation:"shown",...c})}await g(u,w)})();A(u,R)};C()}function O(){if(n)return n;let u=t.client.pendingCommand;if(u?.operation!=="shown")return null;let C=t.key;return P.add(C),A(C,(async()=>{await t.client.retry(),await g(C,u.requestId)})())}return{report:o,settled:O,get inFlight(){return n}}}function tt(t){let b={},P=new Map;async function n(g){let A=t.client.view,o=A?.screen,O=o?.customerData.nodes[g.nodeId];if(t.stopped||t.busy||!A||!o||!O)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(g.action)){let _=t.document,l=_?Tn(_,g.nodeId):null,c=l?.type==="customer_data"?l.data.outputs?.[g.action]:void 0;c&&o.outputs.includes(c)?await t.perform(()=>t.client.submit({operation:"submit",...t.expected(),input:{type:"screen",output:c,answers:t.answers,selection:g.value?{[g.nodeId]:g.value}:{}}})):await t.onIntent?.(g,A);return}let C=g.action.startsWith("sources_")?O.resources.find(_=>_.key===g.value):null;if(g.action.startsWith("sources_")&&!C)throw new m("INVALID_REQUEST","Choose a current resource");let R=`${A.visit}:${g.nodeId}:${C?.key??""}`,x=P.get(R)??[null],w=b[g.nodeId]??{page:1,after:null,filter:"all",...C?{resourceKey:C.key}:{}};if(g.action==="filter"){let _=g.value;if(!_||!(O.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(_))throw new m("INVALID_REQUEST","Unknown data filter");w={page:1,after:null,filter:_},x.splice(0,x.length,null)}else if(g.action==="next"||g.action==="sources_next"){let _=C?.sources.at(-1),l=C?_?{kind:"ledger",cursor:{at:_.detail[0],id:_.id,type:"source"}}:null:o.dataCursors[g.nodeId];if(!l||!C&&!O.hasNext)return;x[w.page]=l,w={...w,page:w.page+1,after:l}}else if(g.action==="previous"||g.action==="sources_previous"){if(w.page<=1)return;w={...w,page:w.page-1,after:x[w.page-2]??null}}P.set(R,x),b={...b,[g.nodeId]:w},await t.perform(()=>t.client.get({nodeId:A.nodeId,visit:A.visit,revision:A.revision,components:b}))}return{get queries(){return b},intent:n,reset(){b={},P.clear()}}}function it(t){let{doc:b,holder:P,reviewHolder:n,mountScreenPreview:g}=t,A=!1,o,O=0,u=null,C="",R,x=new Map,ie=l=>l?`${l.id}:${l.nodeId}:${l.visit}:${l.revision}:${l.paywall?.quote?.operationId??""}`:"";async function w(l){if(t.stopped||!t.client.review||A&&l===o&&R?.active)return;let c=!A||l!==o;A||(C=ie(t.client.view),x.set(C,structuredClone(t.answers))),A=!0,o=l,P.hidden=!0,t.suspend(!0),n.hidden=!1;let E=++O;c&&(R?.finish("dismissed"),u?.destroy(),u=null,n.replaceChildren(),R=tn(n,t.loadingOptions,"funnel",()=>{_()}));let S=c?R:void 0;try{if(S?.start(!1,t.client.view?.locale),E!==O||t.stopped)return;let re=t.client.review(l),U=await(S?.wait(re,_e)??re);if(t.stopped||E!==O||!A)return;if(!U.review)throw new m("INVALID_RESPONSE","Historical projection is missing");u?.destroy(),u=null,S||n.replaceChildren();let M=b.createElement("div"),z=S?rn(M,n):()=>{};n.append(M);let Q=U.run.locale.startsWith("zh"),I=t.chrome;M.style.cssText=I.history;let Z=b.createElement("p");Z.textContent=Q?"只读回看":"Read-only history",Z.style.cssText=I.historyTitle,M.append(Z);let N=b.createElement("p");N.style.cssText=I.historyNote,N.textContent=U.review.pages.length?Q?"选择一页查看当时的内容,回看不会改动任何信息。":"Choose a page to see it as it was. Nothing here can be changed.":Q?"还没有可回看的页面。":"There are no earlier pages yet.",M.append(N);let qe=U.review.page?.receiptId,he=b.createElement("div");he.style.cssText=I.historyPages;for(let[le,L]of U.review.pages.entries()){let i=b.createElement("button");i.type="button",i.textContent=Q?`第 ${le+1} 页`:`Page ${le+1}`;let a=qe!==void 0&&L.receiptId===qe;i.style.cssText=a?I.primary:I.secondary,a&&i.setAttribute("aria-current","page"),$e(i,()=>t.chrome.focus),i.onclick=()=>{w(L.receiptId)},he.append(i)}if(he.childElementCount&&M.append(he),U.review.page){let le=U.review.page,L=b.createElement("div");L.inert=!0,L.style.cssText=I.historyPage,M.append(L),u=g(L,{mode:"live",rendererUrl:t.client.webViewUrl,title:le.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{E===O&&!t.stopped&&S?.present(z)},onError:a=>{if(E!==O||t.stopped)return;let s=new Error(a);S?.finish("error",s),u?.destroy(),u=null,M.remove(),t.fail(s)},onEscape:()=>{_()}});let i=u;if(i.update(le.document,U.run.locale,{serverInput:{bindings:le.inputs,answers:le.answers,values:le.values}}),await i.ready,t.stopped||E!==O||!A)return}let we=Q?{issued:"已领取",reserved:"已预留",redeemed:"已使用",expired:"已过期",revoked:"已撤销",unknown:"状态待确认"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},W=b.createElement("div");W.style.cssText=I.historyRecords;for(let le of[...U.review.coupons.map((L,i)=>`${Q?"优惠券":"Coupon"} ${i+1}: ${we[L.status]}`),...U.review.purchases.map((L,i)=>`${Q?"购买":"Purchase"} ${i+1}: ${Zn(L.status,Q)}`)]){let L=b.createElement("p");L.textContent=le,L.style.margin="0",W.append(L)}W.childElementCount&&M.append(W),U.review.page||S?.present(z),t.client.view&&await t.enqueue(t.client.view)}catch(re){if(E!==O||t.stopped)return;S?.finish("error",re),u?.destroy(),u=null,n.replaceChildren(),t.fail(re)}}async function _(){if(!A||t.stopped||!t.client.review)return;let l=++O;R?.finish("dismissed");try{if(await t.client.review(),t.stopped||l!==O)return;A=!1,O++,R?.finish("dismissed"),u?.destroy(),u=null,n.replaceChildren(),n.hidden=!0,P.hidden=!1;let c=t.client.view;ie(c)!==C?(x.set(C,structuredClone(t.answers)),t.resetScreen()):(x.delete(C),t.suspend(!1)),c&&await t.enqueue(c)}catch(c){if(l!==O||t.stopped)return;u?.destroy(),u=null,n.replaceChildren(),t.fail(c)}}return{get active(){return A},get receipt(){return o},open:w,exit:_,get drafts(){return new Map([...x].map(([l,c])=>[l,structuredClone(c)]))},stop(){A=!1,O++,R?.finish("dismissed"),u?.destroy(),u=null,n.replaceChildren(),n.hidden=!0,P.hidden=!1}}}var hn=5e3;async function dt(t,b,P){let n=b,g=n.prepared&&Kn(n.prepared),A=()=>{};function o(){n.prepared&&n.prepared.state!=="adopted"&&g?.release()}let O=()=>n.prepared?.state==="shown"&&!!g?.modal,u=n.client.identitySignal,C;try{C=await Promise.all([import("./screen-renderer-HOIWGE5V.js"),import("./paywall-QGZNK5QL.js")]),n.signal?.throwIfAborted(),u?.throwIfAborted()}catch(e){throw o(),e}let[{mountScreenPreview:R},{showPaywall:x}]=C,ie=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.appManifestRelease?et({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;ie?.start();let w=t.ownerDocument,_=Qn(w),l=!1,c=w.createElement("section"),E=w.createElement("div"),S=w.createElement("div"),re=w.createElement("div"),U=w.createElement("button");re.hidden=!0,U.type="button";let M=w.createElement("p"),z=w.createElement("p"),Q=w.createElement("button"),I=w.createElement("button"),Z=w.createElement("button"),N=w.createElement("dialog"),qe,he=!1;c.dataset.indianaFunnel="",c.dataset.longplayCloseOwner="sdk",c.setAttribute("aria-busy","false"),M.setAttribute("role","status"),z.setAttribute("role","alert"),z.hidden=!0,Q.type=I.type=Z.type="button",S.append(Q,U,M,z,Z,I),c.append(E,re,S),t.append(c);let we=jn,W=mn(we),le="",L=(w.documentElement.lang||"").startsWith("zh"),i,a="",s;for(let e of[Q,U,Z,I])$e(e,()=>W.focus);function q(){let e=L?"关闭":"Close";I.parentElement===N?(I.textContent="×",I.setAttribute("aria-label",e),Gn(I,we)):(I.textContent=e,I.removeAttribute("aria-label"),I.style.cssText=W.link+";margin-inline-start:auto")}function f(e){let r=e?.screen?.content.document.theme??we,d=JSON.stringify([r.primary,r.background,r.text,r.radius,r.font,I.parentElement===N]);if(d===le)return;le=d,we=r;let H=I.parentElement===N;W=mn(we,H),c.style.cssText=W.root+";min-width:0"+(H?";display:flex;flex-direction:column;min-height:100%":""),S.style.cssText=W.bar+(H?";margin-top:auto":""),S.hidden&&(S.style.display="none"),Q.style.cssText=U.style.cssText=W.secondary,Z.style.cssText=W.primary,M.style.cssText=W.status,z.style.cssText=W.alert,q(),wn(Q)}function p(){S.hidden=Q.hidden&&U.hidden&&Z.hidden&&z.hidden&&!M.textContent&&(I.hidden||I.parentElement!==S),S.style.display=S.hidden?"none":"flex",i?.responsive&&s!==void 0&&i.setContentHeight(s+S.getBoundingClientRect().height)}f();let F=null,y=null,Y=null,X="",j="",ge=!1,xe="",on="",Ge="",h=!1,ue=0,Qe=!1,gn="",sn=null,an=Promise.resolve(),vn=!n.client.view,J=P,Ae,Le,ze="",Je,pe=!1,De=null,ve=!1,je=()=>n.client.pendingCommand?.operation==="close",fe=null,K=null,ln=Mn({document:w,run:async()=>{(!y?.observing||n.client.pendingCommand)&&await dn()},delay:()=>{if(!me.pending&&!(h||!Y||!["running","waiting"].includes(Y.status)&&!n.client.pendingCommand)&&!(y?.observing&&!n.client.pendingCommand))return Y.pendingRequest||n.client.pendingCommand?1500:hn},hiddenDelay:()=>!h&&!me.pending&&n.client.pendingCommand?15e3:void 0}),ne=null;function un(){return K&&n.client.hasDurableJournal===!0&&ne?.acknowledged===!0&&ne.operationId===K.operationId&&n.client.view?.id===ne.runId&&n.client.view?.status==="closed"&&n.client.view.revision===ne.revision+1&&!(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0))&&!n.client.pendingPurchase?K:null}function In(e){let r=e.run.paywall;if(ne&&e.settlement?.requestId===ne.requestId&&e.settlement.state==="settled"&&e.settlement.operationId===null&&e.run.id===ne.runId&&e.run.status==="closed"&&!e.run.pendingRequest&&e.run.revision===ne.revision+1&&e.run.nodeId===ne.nodeId&&e.run.visit===ne.visit&&r?.receiptId===ne.receiptId&&r.selectionGeneration===ne.selectionGeneration&&(r.quote?.operationId??null)===ne.operationId&&(r.operation?.operationId??r.quote?.operationId??null)===ne.operationId){let d=ne.operationId===null&&r.selectionGeneration===0&&!r.quote&&!r.operation&&!r.purchaseRequestId,H=Me({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect});(d||r.canReselect===!0&&H.type==="native")&&(ne.acknowledged=!0)}}let Te=null,Be=new Set,Ie={},Se=!1,de=(e,r=null)=>{h||(e instanceof m&&e.status===409&&e.reason==="STATE_CHANGED"&&e.recovery==="recover_operation"&&ln.destroy(),Te=r,Se=!1,z.textContent=Bn(e,L),z.hidden=!1,Z.hidden=n.client.pendingCommand===null,p(),Ee(n.onError,e))},me=Fn({client:n.client,document:w,conceal(){h||(be(),J?.finish("dismissed"),c.hidden=!0,l||(l=!0,_()))},async receive(e){h||await ye(n.client.view??e.run)},failed(e){if(!h){if(!me.pending){ve=!1;let r=n.client.view;r&&ye(r).then(()=>de(e),de);return}Ze(),c.parentElement!==t&&t.append(c),c.hidden=!1,Q.hidden=U.hidden=I.hidden=!0,M.textContent="",f(),de(e,n.client.pendingCommand?.requestId??null)}}}),bn=()=>{h||(Te=null,z.textContent=Yn(L),z.hidden=!1,Z.hidden=!0,p())};function ke(){let e=n.client.view;if(!e)throw new m("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}let k=it({client:n.client,doc:w,holder:E,reviewHolder:re,mountScreenPreview:R,loadingOptions:n,get chrome(){return W},get stopped(){return h},get answers(){return Ie},suspend(e){y?.setSuspended(e)},resetScreen(){X="",j="",xe=""},enqueue:ye,fail:de}),He=nt({client:n.client,expected:ke,fail:de,get stopped(){return h},get reviewing(){return k.active},get key(){return X},get busy(){return ue},get staleRead(){return sn}}),We=tt({client:n.client,expected:ke,perform:Ne,onIntent:n.onCustomerDataIntent,get stopped(){return h},get busy(){return ue},get document(){return F?.document},get answers(){return Ie}}),Ye=e=>`${e.id}:${e.nodeId}:${e.visit}`,Fe=e=>e&&(e.screen||e.paywall)?Ye(e):"";function Pe(){let e=n.client.view;Q.disabled=!k.active&&(ue>0||!!n.client.pendingCommand||!e?.canBack||e.stopped||!["running","waiting"].includes(e.status)||!Fe(e)||j!==Fe(e)),Q.hidden=!k.active&&!e?.canBack,wn(Q);let r=!!y&&!k.active;I.hidden=r&&!J?.active||he&&!k.active,U.hidden=!n.client.review||!k.active&&!e?.canBack;let d=e?.locale.startsWith("zh");M.textContent=r?"":ue>0||e?.pendingRequest?d?"正在处理":"Processing":e?.instruction?.type==="wait"?d?"等待中":"Waiting":"",p()}async function Cn(e){if(!e)return;let r=n.client.view;await e;let d=n.client.view;if(!r||!d||d.id!==r.id||d.nodeId!==r.nodeId||d.visit!==r.visit||d.stopped||!["running","waiting"].includes(d.status))throw new m("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Ne(e,r=!1,d){if(!((ue||ve||fe||K)&&!r||h||k.active&&!r)){ue++,c.setAttribute("aria-busy","true"),z.hidden=!0,Te=null,Se=!1,Pe();try{if(r||await Cn(He.inFlight),h)return;let H=await e();h||await ye(n.client.view??H.run)}catch(H){d?.(H)&&n.client.pendingCommand===null?bn():me.pending||de(H,n.client.pendingCommand?.requestId??null)}finally{ue=Math.max(0,ue-1),c.setAttribute("aria-busy",String(ue>0)),h||(Z.hidden=n.client.pendingCommand===null,Pe())}}}function Ve(){ln.schedule()}async function dn(){if(!(h||Qe||ue)&&!me.pending){if(k.active){await k.open(k.receipt);return}Qe=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let r=n.client.view,d=We.queries,H=await n.client.get(r?.screen&&Object.keys(d).length?{nodeId:r.nodeId,visit:r.visit,revision:r.revision,components:d}:void 0);Se&&!h&&(Se=!1,z.hidden=!0,p()),!h&&d===We.queries&&await ye(n.client.view??H.run)}catch(e){de(e),Se=!h}finally{Qe=!1}}}function Xe(e,r,d){if(J?.active){let ce=J;return ce.setDismissHandler(()=>Pn(ce)),ce}let H=tn(t,n,"funnel",()=>Pn(H),Jn);return J=H,H.start(e,r,d),H}function Pn(e){h||pe||(pe=!0,e.finish("dismissed"),be(),c.hidden=!0,n.client.view?Re().finally(oe):oe())}function cn(){clearTimeout(Je?.timeout),Je=void 0}function be(){he=!1,cn(),Ae?.abort(),Ae=void 0,F?.destroy(),F=null,y?.destroy(),y=null,Le?.(),Le=void 0,N.open&&N.close(),E.replaceChildren(),E.style.cssText="",s=void 0,X="",j="",ge=!1,xe="",Ge=""}function Rn(){let e=w.defaultView;i?.responsive&&e&&F?.resizeViewport?.(e.innerHeight,e.innerWidth)}function Ze(){i?.destroy(),i=void 0,a=""}function Ke(e){let r=e.screen?.presentation;if(!r||r.type==="inline"){N.open&&N.close(),Ze(),I.parentElement!==S&&S.append(I),c.parentElement!==t&&t.append(c);for(let ce of["flex","display","flex-direction","justify-content"])E.style.removeProperty(ce);f(e),p();return}c.parentElement!==N&&(N.append(I,c),t.append(N)),E.style.flex="1 0 auto",E.style.display="flex",E.style.flexDirection="column",E.style.justifyContent="center",f(e);let d=e.screen.content.document,H=JSON.stringify([r,le]);if(H!==a){Ze(),a=H;let ce={sm:420,md:640,lg:900},Ce="size"in r&&!r.backdrop?",0 0 0 100vmax #16142566":"";N.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${we.background};color:${we.text};`+(r.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ce[r.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${Ce};`+(r.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),i=$n(N,{presentation:r,theme:d.theme,pages:d.pages},Rn),i.latch()}p(),N.setAttribute("aria-label",(qe?.screen===e.screen?.content.document.name?qe?.label:void 0)??F?.document?.name??e.screen?.content.document.name??"Funnel")}async function rt(e){if(h||pe)return;if(me.observe(),me.pending){Y=e;return}if(ve&&(je()||["running","waiting"].includes(e.status))||(Y=e,Te&&n.client.pendingCommand?.requestId!==Te&&(z.hidden=!0,Te=null),L=e.locale.startsWith("zh"),U.textContent=L?"回看":"History",Q.textContent=k.active?L?"返回当前":"Return to current":L?"返回":"Back",q(),Z.textContent=L?"重试":"Retry",Z.hidden=n.client.pendingCommand===null,Pe(),gn!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(gn=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,Ee(n.onState,structuredClone(e))),h||pe))return;if((!e.pendingRequest||ve&&e.status==="closed")&&["closed","ineligible","failed"].includes(e.status)){oe();return}if(e.stopped&&O()){oe();return}if(e.stopped||n.client.configurationReady===!1){k.stop(),o(),be(),J?.finish("skipped"),c.hidden=!0,Ve();return}if(c.hidden=!1,k.active){Ve();return}let r=Fe(e),d=n.client.view;if(d&&d.revision>e.revision&&Fe(d)!==r)return;let H=!e.instruction&&!e.pendingRequest&&e.nodeType==="screen"&&["running","waiting"].includes(e.status);r!==X&&(X&&J?.finish("dismissed"),be(),X=r,Ie={...e.answers},We.reset());let ce=Ye(e);if(ze===ce){c.hidden=!0;return}if(H&&!r){c.hidden=!0;let $=n.prepared?.state==="shown"?null:Xe(!0,e.locale);!h&&!pe&&Je?.key!==ce&&(cn(),Je={key:ce,timeout:setTimeout(()=>{let v=n.client.view;if(h||!$?.active&&n.prepared?.state!=="shown"||!v||Ye(v)!==ce)return;ze=ce;let B=new Error("Funnel screen preparation timed out");$?.finish("error",B),o(),be(),de(B)},_e)}),Ve();return}cn();let ee=$=>{let v=n.client.view;return!h&&!pe&&!De&&!$.aborted&&n.client.configurationReady!==!1&&!!v&&!v.stopped&&!["closed","ineligible","failed"].includes(v.status)&&Fe(v)===r},Ce=($,v)=>{ee(v)&&(ze=r,J?.finish("error",$),be(),c.hidden=!0,de($))};if(r||((e.instruction&&e.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(e.status))&&o(),Ke(e),e.instruction?.type!=="event"&&e.instruction?.type!=="open_url"&&J?.finish("skipped")),e.screen){o();let $=e.screen.content;if(!F){let ae=e.screen.presentation.type!=="inline",G=Xe(ae,e.locale);if(h||pe)return;let te=(Ae=new AbortController).signal;Ke(e),Le=ae?zn(N):rn(c,t),F=R(E,{mode:"live",closeActions:Array.from(new Set([...n.closeActions??[],...$.document.actions.filter(V=>V.type==="event"&&V.close).map(V=>V.id)])),onAuthoredClose(V){ee(te)&&(he=V,Pe())},rendererUrl:n.client.webViewUrl,title:$.document.name,...ae?{hostPresentation:()=>i?.type??e.screen.presentation.type}:{},onResize:V=>{s=V,i?.responsive&&i.setContentHeight(V+S.getBoundingClientRect().height)},onAction(V,T={},Ue={}){if(k.active||!ee(te)||j!==r)return;Ie={...Ie,...Ue};let pn=e.screen?.inputs??[],qn=Object.fromEntries(pn.filter(({variable:Oe})=>Object.hasOwn(Ie,Oe)).map(({variable:Oe})=>[Oe,Ie[Oe]]));if(Xn(pn,qn).length){bn();return}Ne(()=>n.client.submit({operation:"submit",...ke(),input:{type:"screen",output:V,answers:qn,selection:T}}),!1,Oe=>Wn(Oe,pn))},onAnswers:V=>{k.active||!ee(te)||j!==r||(Ie={...Ie,...V})},onCustomerDataIntent:V=>{k.active||!ee(te)||j!==r||We.intent(V).catch(de)},onEscape:()=>{!ee(te)||j!==r||k.active||fe||K||Re()},onError:V=>{let T=new Error(V);j===r?de(T):Ce(T,te)},onRendered:V=>{if(!(!ee(te)||j===r))try{G.present(T=>{Le?.(),Le=void 0,V&&(qe={screen:$.document.name,label:V},N.setAttribute("aria-label",V)),ae&&(N.showModal(),l=!1,i?.responsive&&N.focus({preventScroll:!0}),!T&&n.loading!=="host"&&xn(N,i?.type??e.screen.presentation.type,i?.responsive)),j=r,ge=ae,Pe()}),ee(te)&&He.report(r)}catch(T){Ce(T,te)}}}),Rn()}let v={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:Ie,values:e.screen.values}},B=JSON.stringify([$,e.locale,v.parameters,e.screen.inputs,e.screen.values]);if(B!==xe)F.update($.document,e.locale,v),xe=B,on=JSON.stringify(v.capabilities),Ge=JSON.stringify(v.customerData);else{let ae=JSON.stringify(v.capabilities);ae!==on&&(F.updateCapabilities(v.capabilities),on=ae),JSON.stringify(v.customerData)!==Ge&&(F.updateCustomerData(v.customerData),Ge=JSON.stringify(v.customerData))}let se=F;if(se)try{await(J?.wait(se.ready)??se.ready)}catch(ae){Ae&&Ce(ae,Ae.signal)}}else if(e.paywall&&!y){let $=e.paywall.resolution,v="document"in $?$.document:null,B=g,se=n.mountPaywallControls,ae=null,G=(Ae=new AbortController).signal,te={loading:"host",signal:G,...se&&{mountControls:T=>se(T,e)},canInteract:()=>ee(G)&&!k.active&&!fe&&!K,beforeAction:async()=>{ue++;try{await Cn(He.settled()),z.hidden=!0,Te=null,Se=!1,p()}finally{ue=Math.max(0,ue-1)}},start:()=>yn(n.client),onObservationChange:Ve,onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resumeCheckout:n.resumeCheckout,allowNewPurchase:n.allowNewPurchase,checkoutNavigation:n.checkoutNavigation,terminateCheckout:n.terminateCheckout,purchaseConfirmation:n.purchaseConfirmation,confirmOnHostedCheckout:n.confirmOnHostedCheckout,resolveOfferId:n.resolveOfferId,resolveSubscriptionChange:n.resolveSubscriptionChange,claimCoupon:n.claimCoupon,onEvent:n.onEvent,onOpenUrl:T=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:T,openIn:"same_window"}):w.defaultView?.location.assign(T),onAction:async T=>{if(k.active)return;let Ue=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:T,answers:{}}});await ye(n.client.view??Ue.run)},onError:T=>{j===r?de(T):Ce(T,G)}},V={quoteError:T=>Ee(n.onError,T),present(T){ee(G)&&(ae?.present(()=>{T(),j=r,ge=!!E.querySelector("dialog[open]"),ge&&(l=!1),Pe()}),ee(G)&&He.report(r))},async closeAction(T){h||k.active||await me.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:T,answers:{}}})},async dismiss(){if(!(h||G.aborted||k.active||fe||K||!ve&&!ee(G))){if(ve=!0,(n.resumeCheckout||n.terminateCheckout)&&lt()){Y=n.client.view,oe();return}await Re()}}};if(B&&se)o();else if(B){let T=await B.adopt(e,{options:te,handoff:V,start:()=>yn(n.client)});T&&ee(G)&&!h?(Ke(e),y=T,J?.active&&J.present(()=>{}),j=r,ge=B.modal,ge&&(l=!1),Pe(),He.report(r),k.active&&y.setSuspended(!0)):(T?.destroy(),o())}if(h||pe)return;if(!y){if(ae=Xe(!0,e.locale,v),h||pe)return;Ke(e);let T=await x(E,te,V).catch(Ue=>(Ce(Ue,G),null));!ee(G)&&!(ve&&!h&&!G.aborted)?T?.host?.destroy():T&&(y=T.host,y?.setSuspended(k.active))}}if(h||pe)return;Pe();let D=e.instruction;if(D&&(D.type==="open_url"||D.type==="event")&&!Be.has(D.receiptId)){let $=w.createElement("button");$.type="button",$.style.cssText=W.primary,$e($,()=>W.focus),E.style.cssText=W.stage,$.textContent=D.type==="open_url"?`${L?"前往":"Continue to"} ${new URL(D.url).host}`:L?"继续":"Continue",$.onclick=()=>{let v=ke(),B=D.type==="open_url"&&!n.onOpenUrl&&D.openIn==="new_window"?ot(D.url):null;Ne(async()=>{let se="success";if(D.type==="open_url")if(n.onOpenUrl)try{se=await n.onOpenUrl({receiptId:D.receiptId,url:D.url,openIn:D.openIn})===!1?"failed":"opened"}catch(G){Ee(n.onError,G),se="failed"}else se=D.openIn==="new_window"&&!B?"failed":"opened";if(D.type==="event"){if(!n.onEvent)throw new m("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(D.event)}if(h||n.client.view?.nodeId!==v.nodeId||n.client.view.visit!==v.visit)throw new m("PRECONDITION_FAILED","The client action visit changed");let ae=await n.client.submit({operation:"submit",...v,input:{type:"client_action",receiptId:D.receiptId,outcome:se}});return Be.add(D.receiptId),D.type==="open_url"&&!n.onOpenUrl&&D.openIn==="same_window"&&w.defaultView?.location.assign(D.url),ae})},J?.active?J.present(()=>E.replaceChildren($)):E.replaceChildren($)}!e.pendingRequest&&e.status==="completed"&&!Be.has(`complete:${e.id}`)&&(Be.add(`complete:${e.id}`),Ee(n.onComplete,structuredClone(e))),Ve()}function ot(e){let r=w.defaultView?.open(e,"_blank")??null;return r&&(r.opener=null),r}function ye(e){return Pe(),an=an.catch(()=>{}).then(async()=>{try{await rt(e)}catch(r){throw J?.active&&(ze=Ye(e),J.finish("error",r),be(),c.hidden=!0),r}}),an}let st=n.client.subscribe(e=>{if(!vn){if(e.stopped&&(ge||O())&&!ve){Y=e,oe();return}!ve&&(e.stopped||n.client.configurationReady===!1||X&&j!==X&&(Fe(e)!==X||["closed","ineligible","failed"].includes(e.status)))&&(be(),J?.finish("dismissed"),c.hidden=!0),ye(e).catch(de)}}),at=n.client.subscribeError?.(e=>{me.pending||de(e)});function lt(){let e=n.client.view,r=e?.paywall;return!!r?.operation&&!!e&&["running","waiting"].includes(e.status)&&Nn(Me({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect}))}function Re(e){if(De)return De;if(h||!e&&(fe||K))return Promise.resolve();let r=!e&&je();return!r&&n.client.view&&!["running","waiting"].includes(n.client.view.status)?(Y=n.client.view,oe(),Promise.resolve()):(De=Ne(async()=>{let d=r?await n.client.retry():await(e?n.client.submit.bind(n.client):me.submit)({operation:"close",...e??ke()});return e&&In(d),d},!0).then(()=>{let d=n.client.view;d?.status==="closed"&&!je()&&(Y=d,oe())}).finally(()=>{De=null}),De)}function oe(){ie?.destroy(),!h&&(h=!0,me.destroy(),A(),o(),n.signal?.removeEventListener("abort",oe),u?.removeEventListener("abort",oe),J?.finish("dismissed"),ln.destroy(),st(),at?.(),be(),Ze(),k.stop(),N.remove(),c.remove(),l||_(),Ee(n.onDismiss,Y?structuredClone(Y):null))}Q.onclick=()=>{if(!Q.disabled){if(k.active){k.exit();return}Ne(()=>n.client.submit({operation:"back",...ke()}))}},U.onclick=()=>{k.open()},I.onclick=()=>{J?.active?J.dismiss():fe||Re()},Z.onclick=()=>{me.pending?me.retry().catch(()=>{}):je()?Re():Ne(()=>n.client.retry())},N.addEventListener("cancel",e=>{e.preventDefault(),J?.active?J.dismiss():fe||Re()}),n.signal?.addEventListener("abort",oe,{once:!0}),u?.addEventListener("abort",oe,{once:!0});let en=!1;g&&(A=g.onClose(()=>{h||pe||(pe=!0,J?.finish("dismissed"),be(),c.hidden=!0,n.client.view?Re().finally(oe):en=!0)}));let En={destroy:oe,refresh:dn,get recovery(){let e=un();if(e)return e;if(!h&&!ue&&!ve&&!fe&&y){let r=y.recovery;if(r.type!=="native")return r}return{type:"recover",operationId:n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??K?.operationId??null,requestId:n.client.pendingCommand?.requestId??null}},prepareFallback(){if(fe)return fe;let e=un();if(e)return Promise.resolve(e);let r=n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??K?.operationId??null,d=()=>({type:"recover",operationId:r,requestId:n.client.pendingCommand?.requestId??null});if(n.client.hasDurableJournal!==!0){let D=y?.recovery;return Promise.resolve(D&&D.type!=="native"&&D.type!=="cancel"?D:d())}let H=(n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[])).some(D=>D.operation==="close");if(h&&!(H||K&&n.client.view?.status==="closed")||ue||Qe||De||k.active||!y&&!K&&!H)return Promise.resolve(d());let ce=y,ee=(async()=>{try{if(!K&&H){let v=await n.client.retry();return await ye(n.client.view??v.run),d()}if(!K){let v=await ce.prepareFallback();if(v.type!=="native")return v;if(n.client.hasDurableJournal!==!0)return d();K=v}let D=n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[]);if(D.length){let v=D.find(se=>se.operation==="close");if(!v||!ne||v.requestId!==ne.requestId)return d();let B=await n.client.retry();In(B),await ye(n.client.view??B.run)}else{let v=n.client.view,B=v?.paywall;if(!v||!B||B.selectionGeneration===void 0||(B.quote?.operationId??null)!==K.operationId||K.operationId!==null&&B.canReselect!==!0)return d();let se=B.selectionGeneration,ae=await n.client.get();await ye(n.client.view??ae.run);let G=n.client.view,te=G?.paywall;if(!G||!te||!["running","waiting"].includes(G.status)||G.stopped||G.id!==v.id||G.nodeId!==v.nodeId||G.visit!==v.visit||te.receiptId!==B.receiptId||te.selectionGeneration!==se||(te.quote?.operationId??null)!==K.operationId||K.operationId!==null&&te.canReselect!==!0||n.client.pendingPurchase||(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0)))return d();let V=ke();ne={runId:G.id,operationId:K.operationId,revision:V.revision,requestId:V.requestId,nodeId:G.nodeId,visit:G.visit,receiptId:te.receiptId,selectionGeneration:se,acknowledged:!1},await Re(V)}let $=un();return $?(oe(),$):d()}catch(D){return de(D),d()}})();fe=ee;let Ce=()=>{fe===ee&&(fe=null)};return ee.then(Ce,Ce),ee},review:k.open,exitReview:k.exit,get unappliedDrafts(){return k.drafts}};try{let e=n.client.view;if(e)((n.client.viewAgeMs??hn)>=hn||e.instruction?.type==="evaluate_segment")&&(sn=dn().finally(()=>{sn=null})),await ye(e);else{if(c.hidden=!0,h)throw new DOMException("Presentation cancelled","AbortError");let r=en||n.prepared?.state==="shown"?null:Xe(n.client.view?.screen?.presentation.type!=="inline",n.client.view?.locale);if(h||pe&&!en)throw new DOMException("Presentation cancelled","AbortError");let d=n.client.get(),H=await(r?r.wait(d,_e):ct(d,_e));if(vn=!1,en)return h||await Re().finally(oe),En;await ye(n.client.view??H.run)}}catch(e){throw J?.finish("error",e),oe(),e}return En}function ct(t,b){let P;return Promise.race([t,new Promise((n,g)=>{P=setTimeout(()=>g(new Error("Presentation data timed out")),b)})]).finally(()=>clearTimeout(P))}function Zt(t,b,P){return dt(t,b,P)}export{dt as a,Zt as b};
1
+ import{b as Kn}from"./chunk-FEEBBJEK.js";import{a as Jn,b as jn,c as mn,d as wn,e as $e,f as Bn,h as Wn,i as Yn,j as Xn,k as Zn}from"./chunk-L7C5TKKV.js";import{b as Sn,c as et}from"./chunk-IA66JXF6.js";import{a as Mn}from"./chunk-W32FI2A2.js";import{c as $n,e as xn,f as Gn,h as Qn,i as _e,j as tn,k as zn,l as rn}from"./chunk-2UXX62Y4.js";import{b as Fn}from"./chunk-W3B4GT74.js";import{K as nn}from"./chunk-LE32WTZ7.js";import{a as Me,d as Nn}from"./chunk-LSHIR6QM.js";import{c as On,e as _n,f as Ln,g as Hn,h as Vn,i as Un}from"./chunk-OPUIFAQS.js";import{b as Tn}from"./chunk-HYX3EDZS.js";import{B as fn}from"./chunk-EGFVGCDG.js";import{x as Dn}from"./chunk-YFLVGOCJ.js";import{t as An}from"./chunk-MQ5LJEWV.js";import{C as kn}from"./chunk-JDIFYMSA.js";import{a as m}from"./chunk-ZDIWOE4Q.js";import{a as Ee}from"./chunk-DSPLGTQI.js";async function yn(t){let{session:b,load:P}=ut(t);try{return await P(),b}catch(n){throw b.destroy(),n}}function ut(t){let b=t.view;if(!b?.paywall)throw new m("INVALID_REQUEST","The current node is not a Paywall");let P=b.paywall.receiptId,n=b.nodeId,g=b.visit,A=b.paywall.resolution,o=b.paywall,O="document"in A?{document:A.document,offering:A.offering,capabilities:A.capabilities}:null;function u(){let i=o.resolution;return"document"in i?i:O&&{...i,document:O.document,offering:O.offering,capabilities:On(i.capabilities,O.capabilities)}}function C(i){if(!_n(i,A))throw new m("INVALID_RESPONSE","The pinned Paywall binding changed")}let R=!1,x=new Set,ie=null;function w(){let i=u();if(i&&!R)for(let a of x)Ee(a,structuredClone(i))}async function _(){I();let i=u();if(i)return structuredClone(i);if(!ie){let a=(async()=>{if("document"in o.resolution||!t.resolvePaywall)throw new m("INVALID_RESPONSE","Public Paywall reader is unavailable");let q=await Sn(t,o.resolution);return I(),C(q),O={document:q.document,offering:q.offering,capabilities:q.capabilities},w(),u()})();ie=a;let s=()=>{ie===a&&(ie=null)};a.then(s,s)}return ie.then(a=>structuredClone(a))}let l=new AbortController,E=(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===n&&i.visit===g&&i.input.type==="paywall_quote")?.requestId??b.paywall.purchaseRequestId,S=0,re=null,U=new Set,M=null,z=new Map;function Q(i){if(i.purchase&&i.purchase.receiptId!==P)throw new m("INVALID_RESPONSE","Purchase receipt changed");let a=i.run.paywall;return i.purchase??(a?.receiptId===P?a:null)}function I(){if(R)throw new m("IDENTITY_CHANGED","Paywall presentation has closed")}function Z(i,a,s){if(I(),a!==S||s!==void 0&&o.quote?.operationId!==s)return!1;let q=o.selectionGeneration??0,f=i.run.paywall;if(f?.receiptId===P){if((f.selectionGeneration??0)<(o.selectionGeneration??0))return!1;C(f.resolution)}let p=Q(i),F=f?.receiptId===P&&(f.selectionGeneration??0)>q,y=F?p?.quote??null:p?.quote??o.quote,Y=p?.operation??(y?.operationId===o.quote?.operationId?o.operation:null);return o.quote&&y&&Vn(o.quote,y),y&&Y&&Ln(Y,{operationId:y.operationId,membershipId:fn(y)?y.membershipId:null,...fn(y)?{featureQuantities:y.featureQuantities??{}}:{}},"Purchase operation changed"),(F||y?.operationId!==o.quote?.operationId)&&(S++,f?.receiptId===P&&(E=f.purchaseRequestId)),f?.canReselect===!0&&f.purchaseRequestId===M&&!(t.pendingCommands??[t.pendingCommand]).some(X=>X?.requestId===M)&&(M=null),o={...o,...f?.receiptId===P?f:{},...s!==void 0&&!F&&p?.canReselect!==void 0?{canReselect:p.canReselect}:{},quote:y,operation:Un(o.operation,Y,!0)},w(),!0}function N(i,a,s){return new Promise((q,f)=>{let p=!1,F=()=>{clearTimeout(j),l.signal.removeEventListener("abort",X)},y=ge=>{p||(p=!0,F(),q(ge))},Y=ge=>{p||(p=!0,F(),f(ge))},X=()=>Y(new m("IDENTITY_CHANGED","Paywall presentation has closed")),j=setTimeout(()=>Y(new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,s)),Math.max(0,a-Date.now()));l.signal.addEventListener("abort",X,{once:!0}),l.signal.aborted&&X(),i.then(y,Y)})}function qe(i){return new Promise(a=>{let s=()=>{clearTimeout(q),l.signal.removeEventListener("abort",s),a()},q=setTimeout(s,i);l.signal.addEventListener("abort",s,{once:!0}),l.signal.aborted&&s()})}function he(i,a){I();let s=z.get(i)??t.pendingCommands?.find(p=>p.requestId===i)??t.pendingCommand;if(s?.operation==="submit"&&s.requestId===i&&s.nodeId===n&&s.visit===g){a.type==="paywall_quote"&&s.input.type==="paywall_quote"&&s.input.predecessor&&!a.predecessor&&(a={...a,predecessor:s.input.predecessor});let p=nn.parse(s),F=nn.parse({...s,input:a});if(p.operation!=="submit"||F.operation!=="submit"||JSON.stringify(p.input)!==JSON.stringify(F.input))throw new m("CONFLICT","A purchase request cannot change its input");return z.set(i,p),p}let q=t.view;if(!q||q.nodeId!==n||q.visit!==g||q.paywall?.receiptId!==P)throw new m("PRECONDITION_FAILED","The Paywall visit has changed");let f=nn.parse({operation:"submit",requestId:i,nodeId:n,visit:g,revision:q.revision,input:structuredClone(a)});if(f.operation!=="submit")throw new m("INVALID_REQUEST","A purchase submission is required");return z.set(i,f),f}async function we(i,a){I();let{requestId:s,input:q}=i,f=Date.now()+3e4;U.add(s);try{let p=await N(t.submit(i),f,s);for(;p.run.pendingRequest?.requestId===s&&Date.now()<f&&!R&&(await qe(Math.min(1e3,f-Date.now())),!(R||Date.now()>=f));)p=await N(t.resume(s),f,s);if(R)throw new m("IDENTITY_CHANGED","Paywall presentation has closed");if(p.run.pendingRequest?.requestId===s)throw new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,s);if(!Z(p,a,q.type==="paywall_confirm"||q.type==="paywall_cancel"?q.operationId:void 0))throw new m("PRECONDITION_FAILED","The purchase selection has changed");M===s&&(M=null)}catch(p){if(M=s,q.type==="paywall_quote"&&t.settle&&!R&&p instanceof m&&p.status!==void 0&&![401,425].includes(p.status)&&!p.retryable&&p.recovery!=="recover_operation")try{if((await N(t.settle(s),f,s)).settlement?.state==="settled"){let y=await N(t.get(),f,s);Z(y,a)&&y.run.paywall?.purchaseRequestId===s&&o.canReselect===!0&&z.delete(s)}}catch{}throw p instanceof m&&p.code==="COMMAND_PENDING"&&p.status===void 0&&z.delete(s),p}finally{U.delete(s)}}async function W(i){if(!o.quote)throw new m("INVALID_REQUEST","A quoted purchase is required");let a=i==="confirm"?"paywall_confirm":"paywall_cancel",s=[...z.values(),...t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])].find(f=>f.operation==="submit"&&f.input.type===a&&"operationId"in f.input&&f.input.operationId===o.quote.operationId),q=s?.operation==="submit"&&s.input.type===a&&"operationId"in s.input&&s.input.operationId===o.quote.operationId?s.requestId:crypto.randomUUID();if(await we(he(q,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.quote.operationId,...i==="confirm"&&o.quote.merchantTerms?{merchantConfirmation:Dn(o.quote.merchantTerms)}:{}}),S),!o.operation)throw new m("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(o.operation)}let le={get view(){return structuredClone(u())},get quote(){return o.quote?structuredClone(o.quote):null},get operation(){return o.operation?structuredClone(o.operation):null},get webViewUrl(){return t.webViewUrl},get locale(){return t.view?.locale??b.locale},get canReselect(){return o.canReselect===!0&&M===null},get recovery(){let i=t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[]),a=t.pendingPurchase;if(a&&(a.receiptId!==P||a.operationId!==o.quote?.operationId))return{type:"recover",operationId:a.operationId,requestId:i[0]?.requestId??null};let s=Me({quote:o.quote,operation:o.operation,requestId:i[0]?.requestId??M??E,pending:U.size>0||i.length>0||M!==null,destroyed:R,canReselect:o.canReselect});return s.type==="recover"&&s.requestId===null&&!R&&t.hasDurableJournal===!0&&!o.quote&&!o.operation&&(o.selectionGeneration??0)===0&&!a&&!i.length&&!U.size&&!E?{type:"native",operationId:null}:s},get pendingCancellation(){return!R&&(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===n&&i.visit===g&&i.input.type==="paywall_cancel"&&i.input.operationId===o.quote?.operationId)},subscribe(i){return R?()=>{}:(x.add(i),()=>x.delete(i))},async refresh(){I();let i=S,a=await t.get();if(Z(a,i),a.run.paywall?.receiptId!==P)throw new m("PRECONDITION_FAILED","Paywall presentation has changed");return _()},preview(i){let a=u();if(!a)return Promise.reject(new m("PRECONDITION_FAILED","Load the Paywall presentation first"));if(E&&E!==i.requestId&&(re||o.canReselect!==!0))return Promise.reject(new m("COMMAND_PENDING","Retry the original purchase before starting another"));let s=a.document.buttons[i.actionId],q=s?.type==="checkout"?Tn(s.product,i.selection,a.capabilities):null;if(!q)return Promise.reject(new m("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let f=An(a.document.screen,q,i.selection,a.capabilities),p=E!==i.requestId&&(o.selectionGeneration??0)>0?{operationId:o.quote?.operationId??null,generation:o.selectionGeneration??0}:void 0,F=t.view?.parameters.commerce;if(F&&typeof F=="object"&&!Array.isArray(F)&&F.intent==="subscription_change"&&!i.subscriptionChange)return Promise.reject(new m("INVALID_REQUEST","Choose the existing membership for this subscription change"));if(i.subscriptionChange&&i.nativeOffer)return Promise.reject(new m("INVALID_REQUEST","A web membership change cannot include a store offer"));if(p&&o.canReselect!==!0)return Promise.reject(new m("COMMAND_PENDING","Original purchase requires authoritative termination"));let y;try{y=he(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:q,...Object.keys(f).length?{featureQuantities:f}:{},...p?{predecessor:p}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{},...i.subscriptionChange?{subscriptionChange:i.subscriptionChange}:{}})}catch(j){return Promise.reject(j)}if(E===i.requestId&&re)return re;E!==i.requestId&&S++;let Y=S;E=i.requestId;let X=(async()=>{if(await we(y,Y),!o.quote)throw new m("INVALID_RESPONSE","The accepted quote is missing");return Hn(o.quote,{productVersionId:q,featureQuantities:f,subscriptionChange:i.subscriptionChange},"The selected purchase changed"),structuredClone(o.quote)})();return re=X,X.then(()=>{re===X&&(re=null)},j=>{re===X&&(re=null),E===i.requestId&&t.pendingCommand?.requestId!==i.requestId&&j instanceof m&&j.status!==void 0&&j.status<500&&![401,425].includes(j.status)&&(E=null)}),X},confirm:()=>W("confirm"),cancel:()=>W("cancel"),async read(){if(I(),!o.quote)throw new m("INVALID_REQUEST","A quoted purchase is required");let i=o.quote.operationId,a=S,s=t.pendingCommands?.find(y=>y.operation==="submit"&&(y.input.type==="paywall_confirm"||y.input.type==="paywall_cancel")&&y.input.operationId===i)??t.pendingCommand;s?.operation==="submit"&&(s.input.type==="paywall_confirm"||s.input.type==="paywall_cancel")&&s.input.operationId===i&&await t.settle?.(s.requestId);let q=await t.get(void 0,{receiptId:P,operationId:i});I();let f=Q(q);if(f?.quote&&f.quote.operationId!==i||f?.operation&&f.operation.operationId!==i)throw new m("INVALID_RESPONSE","Purchase operation changed");let p=Z(q,a,i),F=p?o.operation:f?.operation;if(!F)throw new m("INVALID_RESPONSE","The current purchase result is missing");return p&&U.size===0&&!(t.pendingCommands?.length??(t.pendingCommand?1:0))&&(M=null),structuredClone(F)},destroy(){R=!0,L(),x.clear(),l.abort(),z.clear()}},L=t.subscribe(i=>{R||i.nodeId!==n||i.visit!==g||i.paywall?.receiptId!==P||(i.paywall.selectionGeneration??0)<(o.selectionGeneration??0)||(C(i.paywall.resolution),o={...o,resolution:i.paywall.resolution},w())});return{session:le,load:_}}function nt(t){let b=new Set,P=new Set,n=null;async function g(u,C){let R=!1;for(;!t.stopped&&t.key===u&&t.client.pendingCommand?.requestId===C;){if(!t.client.settle)throw new m("COMMAND_PENDING","The original display acknowledgement is still pending");await t.client.settle(C),R=!0,t.client.pendingCommand?.requestId===C&&await new Promise(x=>setTimeout(x,1500))}t.stopped||t.key!==u||(R&&await t.client.get(),!(t.stopped||t.key!==u)&&b.add(u))}function A(u,C){n=C;let R=()=>{n===C&&(n=null),P.delete(u)};return C.then(R,x=>{R(),t.busy||t.fail(x)}),C}function o(u){if(t.reviewing||b.has(u)||P.has(u)||t.stopped)return;P.add(u);let C=async()=>{if(t.reviewing||t.stopped||t.key!==u||b.has(u)){P.delete(u);return}if(t.busy||t.client.pendingCommand){setTimeout(()=>{C()},250);return}let R=(async()=>{if(t.staleRead){if(await t.staleRead,t.stopped||t.key!==u)return;if(t.client.pendingCommand){setTimeout(()=>{C()},250);return}}let x=t.client.view,ie=t.expected(),w=ie.requestId;try{await t.client.submit({operation:"shown",...ie})}catch(_){if(!(_ instanceof m)||_.code!=="CONFLICT"||_.status!==409||t.client.pendingCommand)throw _;await t.client.get();let l=t.client.view;if(t.stopped||t.reviewing||t.key!==u||!l||!x||l.id!==x.id||l.source.versionId!==x.source.versionId||l.nodeId!==ie.nodeId||l.visit!==ie.visit||l.revision<=ie.revision||l.stopped||!l.screen&&(!l.paywall||l.paywall.receiptId!==x.paywall?.receiptId)||!["running","waiting"].includes(l.status)||t.client.pendingCommand)throw _;let c=t.expected();w=c.requestId,await t.client.submit({operation:"shown",...c})}await g(u,w)})();A(u,R)};C()}function O(){if(n)return n;let u=t.client.pendingCommand;if(u?.operation!=="shown")return null;let C=t.key;return P.add(C),A(C,(async()=>{await t.client.retry(),await g(C,u.requestId)})())}return{report:o,settled:O,get inFlight(){return n}}}function tt(t){let b={},P=new Map;async function n(g){let A=t.client.view,o=A?.screen,O=o?.customerData.nodes[g.nodeId];if(t.stopped||t.busy||!A||!o||!O)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(g.action)){let _=t.document,l=_?kn(_,g.nodeId):null,c=l?.type==="customer_data"?l.data.outputs?.[g.action]:void 0;c&&o.outputs.includes(c)?await t.perform(()=>t.client.submit({operation:"submit",...t.expected(),input:{type:"screen",output:c,answers:t.answers,selection:g.value?{[g.nodeId]:g.value}:{}}})):await t.onIntent?.(g,A);return}let C=g.action.startsWith("sources_")?O.resources.find(_=>_.key===g.value):null;if(g.action.startsWith("sources_")&&!C)throw new m("INVALID_REQUEST","Choose a current resource");let R=`${A.visit}:${g.nodeId}:${C?.key??""}`,x=P.get(R)??[null],w=b[g.nodeId]??{page:1,after:null,filter:"all",...C?{resourceKey:C.key}:{}};if(g.action==="filter"){let _=g.value;if(!_||!(O.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(_))throw new m("INVALID_REQUEST","Unknown data filter");w={page:1,after:null,filter:_},x.splice(0,x.length,null)}else if(g.action==="next"||g.action==="sources_next"){let _=C?.sources.at(-1),l=C?_?{kind:"ledger",cursor:{at:_.detail[0],id:_.id,type:"source"}}:null:o.dataCursors[g.nodeId];if(!l||!C&&!O.hasNext)return;x[w.page]=l,w={...w,page:w.page+1,after:l}}else if(g.action==="previous"||g.action==="sources_previous"){if(w.page<=1)return;w={...w,page:w.page-1,after:x[w.page-2]??null}}P.set(R,x),b={...b,[g.nodeId]:w},await t.perform(()=>t.client.get({nodeId:A.nodeId,visit:A.visit,revision:A.revision,components:b}))}return{get queries(){return b},intent:n,reset(){b={},P.clear()}}}function it(t){let{doc:b,holder:P,reviewHolder:n,mountScreenPreview:g}=t,A=!1,o,O=0,u=null,C="",R,x=new Map,ie=l=>l?`${l.id}:${l.nodeId}:${l.visit}:${l.revision}:${l.paywall?.quote?.operationId??""}`:"";async function w(l){if(t.stopped||!t.client.review||A&&l===o&&R?.active)return;let c=!A||l!==o;A||(C=ie(t.client.view),x.set(C,structuredClone(t.answers))),A=!0,o=l,P.hidden=!0,t.suspend(!0),n.hidden=!1;let E=++O;c&&(R?.finish("dismissed"),u?.destroy(),u=null,n.replaceChildren(),R=tn(n,t.loadingOptions,"funnel",()=>{_()}));let S=c?R:void 0;try{if(S?.start(!1,t.client.view?.locale),E!==O||t.stopped)return;let re=t.client.review(l),U=await(S?.wait(re,_e)??re);if(t.stopped||E!==O||!A)return;if(!U.review)throw new m("INVALID_RESPONSE","Historical projection is missing");u?.destroy(),u=null,S||n.replaceChildren();let M=b.createElement("div"),z=S?rn(M,n):()=>{};n.append(M);let Q=U.run.locale.startsWith("zh"),I=t.chrome;M.style.cssText=I.history;let Z=b.createElement("p");Z.textContent=Q?"只读回看":"Read-only history",Z.style.cssText=I.historyTitle,M.append(Z);let N=b.createElement("p");N.style.cssText=I.historyNote,N.textContent=U.review.pages.length?Q?"选择一页查看当时的内容,回看不会改动任何信息。":"Choose a page to see it as it was. Nothing here can be changed.":Q?"还没有可回看的页面。":"There are no earlier pages yet.",M.append(N);let qe=U.review.page?.receiptId,he=b.createElement("div");he.style.cssText=I.historyPages;for(let[le,L]of U.review.pages.entries()){let i=b.createElement("button");i.type="button",i.textContent=Q?`第 ${le+1} 页`:`Page ${le+1}`;let a=qe!==void 0&&L.receiptId===qe;i.style.cssText=a?I.primary:I.secondary,a&&i.setAttribute("aria-current","page"),$e(i,()=>t.chrome.focus),i.onclick=()=>{w(L.receiptId)},he.append(i)}if(he.childElementCount&&M.append(he),U.review.page){let le=U.review.page,L=b.createElement("div");L.inert=!0,L.style.cssText=I.historyPage,M.append(L),u=g(L,{mode:"live",rendererUrl:t.client.webViewUrl,title:le.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{E===O&&!t.stopped&&S?.present(z)},onError:a=>{if(E!==O||t.stopped)return;let s=new Error(a);S?.finish("error",s),u?.destroy(),u=null,M.remove(),t.fail(s)},onEscape:()=>{_()}});let i=u;if(i.update(le.document,U.run.locale,{serverInput:{bindings:le.inputs,answers:le.answers,values:le.values}}),await i.ready,t.stopped||E!==O||!A)return}let we=Q?{issued:"已领取",reserved:"已预留",redeemed:"已使用",expired:"已过期",revoked:"已撤销",unknown:"状态待确认"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},W=b.createElement("div");W.style.cssText=I.historyRecords;for(let le of[...U.review.coupons.map((L,i)=>`${Q?"优惠券":"Coupon"} ${i+1}: ${we[L.status]}`),...U.review.purchases.map((L,i)=>`${Q?"购买":"Purchase"} ${i+1}: ${Zn(L.status,Q)}`)]){let L=b.createElement("p");L.textContent=le,L.style.margin="0",W.append(L)}W.childElementCount&&M.append(W),U.review.page||S?.present(z),t.client.view&&await t.enqueue(t.client.view)}catch(re){if(E!==O||t.stopped)return;S?.finish("error",re),u?.destroy(),u=null,n.replaceChildren(),t.fail(re)}}async function _(){if(!A||t.stopped||!t.client.review)return;let l=++O;R?.finish("dismissed");try{if(await t.client.review(),t.stopped||l!==O)return;A=!1,O++,R?.finish("dismissed"),u?.destroy(),u=null,n.replaceChildren(),n.hidden=!0,P.hidden=!1;let c=t.client.view;ie(c)!==C?(x.set(C,structuredClone(t.answers)),t.resetScreen()):(x.delete(C),t.suspend(!1)),c&&await t.enqueue(c)}catch(c){if(l!==O||t.stopped)return;u?.destroy(),u=null,n.replaceChildren(),t.fail(c)}}return{get active(){return A},get receipt(){return o},open:w,exit:_,get drafts(){return new Map([...x].map(([l,c])=>[l,structuredClone(c)]))},stop(){A=!1,O++,R?.finish("dismissed"),u?.destroy(),u=null,n.replaceChildren(),n.hidden=!0,P.hidden=!1}}}var hn=5e3;async function dt(t,b,P){let n=b,g=n.prepared&&Kn(n.prepared),A=()=>{};function o(){n.prepared&&n.prepared.state!=="adopted"&&g?.release()}let O=()=>n.prepared?.state==="shown"&&!!g?.modal,u=n.client.identitySignal,C;try{C=await Promise.all([import("./screen-renderer-HOIWGE5V.js"),import("./paywall-6OURDDMJ.js")]),n.signal?.throwIfAborted(),u?.throwIfAborted()}catch(e){throw o(),e}let[{mountScreenPreview:R},{showPaywall:x}]=C,ie=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.appManifestRelease?et({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;ie?.start();let w=t.ownerDocument,_=Qn(w),l=!1,c=w.createElement("section"),E=w.createElement("div"),S=w.createElement("div"),re=w.createElement("div"),U=w.createElement("button");re.hidden=!0,U.type="button";let M=w.createElement("p"),z=w.createElement("p"),Q=w.createElement("button"),I=w.createElement("button"),Z=w.createElement("button"),N=w.createElement("dialog"),qe,he=!1;c.dataset.indianaFunnel="",c.dataset.longplayCloseOwner="sdk",c.setAttribute("aria-busy","false"),M.setAttribute("role","status"),z.setAttribute("role","alert"),z.hidden=!0,Q.type=I.type=Z.type="button",S.append(Q,U,M,z,Z,I),c.append(E,re,S),t.append(c);let we=jn,W=mn(we),le="",L=(w.documentElement.lang||"").startsWith("zh"),i,a="",s;for(let e of[Q,U,Z,I])$e(e,()=>W.focus);function q(){let e=L?"关闭":"Close";I.parentElement===N?(I.textContent="×",I.setAttribute("aria-label",e),Gn(I,we)):(I.textContent=e,I.removeAttribute("aria-label"),I.style.cssText=W.link+";margin-inline-start:auto")}function f(e){let r=e?.screen?.content.document.theme??we,d=JSON.stringify([r.primary,r.background,r.text,r.radius,r.font,I.parentElement===N]);if(d===le)return;le=d,we=r;let H=I.parentElement===N;W=mn(we,H),c.style.cssText=W.root+";min-width:0"+(H?";display:flex;flex-direction:column;min-height:100%":""),S.style.cssText=W.bar+(H?";margin-top:auto":""),S.hidden&&(S.style.display="none"),Q.style.cssText=U.style.cssText=W.secondary,Z.style.cssText=W.primary,M.style.cssText=W.status,z.style.cssText=W.alert,q(),wn(Q)}function p(){S.hidden=Q.hidden&&U.hidden&&Z.hidden&&z.hidden&&!M.textContent&&(I.hidden||I.parentElement!==S),S.style.display=S.hidden?"none":"flex",i?.responsive&&s!==void 0&&i.setContentHeight(s+S.getBoundingClientRect().height)}f();let F=null,y=null,Y=null,X="",j="",ge=!1,xe="",on="",Ge="",h=!1,ue=0,Qe=!1,gn="",sn=null,an=Promise.resolve(),vn=!n.client.view,J=P,Ae,Le,ze="",Je,pe=!1,De=null,ve=!1,je=()=>n.client.pendingCommand?.operation==="close",fe=null,K=null,ln=Mn({document:w,run:async()=>{(!y?.observing||n.client.pendingCommand)&&await dn()},delay:()=>{if(!me.pending&&!(h||!Y||!["running","waiting"].includes(Y.status)&&!n.client.pendingCommand)&&!(y?.observing&&!n.client.pendingCommand))return Y.pendingRequest||n.client.pendingCommand?1500:hn},hiddenDelay:()=>!h&&!me.pending&&n.client.pendingCommand?15e3:void 0}),ne=null;function un(){return K&&n.client.hasDurableJournal===!0&&ne?.acknowledged===!0&&ne.operationId===K.operationId&&n.client.view?.id===ne.runId&&n.client.view?.status==="closed"&&n.client.view.revision===ne.revision+1&&!(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0))&&!n.client.pendingPurchase?K:null}function In(e){let r=e.run.paywall;if(ne&&e.settlement?.requestId===ne.requestId&&e.settlement.state==="settled"&&e.settlement.operationId===null&&e.run.id===ne.runId&&e.run.status==="closed"&&!e.run.pendingRequest&&e.run.revision===ne.revision+1&&e.run.nodeId===ne.nodeId&&e.run.visit===ne.visit&&r?.receiptId===ne.receiptId&&r.selectionGeneration===ne.selectionGeneration&&(r.quote?.operationId??null)===ne.operationId&&(r.operation?.operationId??r.quote?.operationId??null)===ne.operationId){let d=ne.operationId===null&&r.selectionGeneration===0&&!r.quote&&!r.operation&&!r.purchaseRequestId,H=Me({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect});(d||r.canReselect===!0&&H.type==="native")&&(ne.acknowledged=!0)}}let ke=null,Be=new Set,Ie={},Se=!1,de=(e,r=null)=>{h||(e instanceof m&&e.status===409&&e.reason==="STATE_CHANGED"&&e.recovery==="recover_operation"&&ln.destroy(),ke=r,Se=!1,z.textContent=Bn(e,L),z.hidden=!1,Z.hidden=n.client.pendingCommand===null,p(),Ee(n.onError,e))},me=Fn({client:n.client,document:w,conceal(){h||(be(),J?.finish("dismissed"),c.hidden=!0,l||(l=!0,_()))},async receive(e){h||await ye(n.client.view??e.run)},failed(e){if(!h){if(!me.pending){ve=!1;let r=n.client.view;r&&ye(r).then(()=>de(e),de);return}Ze(),c.parentElement!==t&&t.append(c),c.hidden=!1,Q.hidden=U.hidden=I.hidden=!0,M.textContent="",f(),de(e,n.client.pendingCommand?.requestId??null)}}}),bn=()=>{h||(ke=null,z.textContent=Yn(L),z.hidden=!1,Z.hidden=!0,p())};function Te(){let e=n.client.view;if(!e)throw new m("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}let T=it({client:n.client,doc:w,holder:E,reviewHolder:re,mountScreenPreview:R,loadingOptions:n,get chrome(){return W},get stopped(){return h},get answers(){return Ie},suspend(e){y?.setSuspended(e)},resetScreen(){X="",j="",xe=""},enqueue:ye,fail:de}),He=nt({client:n.client,expected:Te,fail:de,get stopped(){return h},get reviewing(){return T.active},get key(){return X},get busy(){return ue},get staleRead(){return sn}}),We=tt({client:n.client,expected:Te,perform:Ne,onIntent:n.onCustomerDataIntent,get stopped(){return h},get busy(){return ue},get document(){return F?.document},get answers(){return Ie}}),Ye=e=>`${e.id}:${e.nodeId}:${e.visit}`,Fe=e=>e&&(e.screen||e.paywall)?Ye(e):"";function Pe(){let e=n.client.view;Q.disabled=!T.active&&(ue>0||!!n.client.pendingCommand||!e?.canBack||e.stopped||!["running","waiting"].includes(e.status)||!Fe(e)||j!==Fe(e)),Q.hidden=!T.active&&!e?.canBack,wn(Q);let r=!!y&&!T.active;I.hidden=r&&!J?.active||he&&!T.active,U.hidden=!n.client.review||!T.active&&!e?.canBack;let d=e?.locale.startsWith("zh");M.textContent=r?"":ue>0||e?.pendingRequest?d?"正在处理":"Processing":e?.instruction?.type==="wait"?d?"等待中":"Waiting":"",p()}async function Cn(e){if(!e)return;let r=n.client.view;await e;let d=n.client.view;if(!r||!d||d.id!==r.id||d.nodeId!==r.nodeId||d.visit!==r.visit||d.stopped||!["running","waiting"].includes(d.status))throw new m("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Ne(e,r=!1,d){if(!((ue||ve||fe||K)&&!r||h||T.active&&!r)){ue++,c.setAttribute("aria-busy","true"),z.hidden=!0,ke=null,Se=!1,Pe();try{if(r||await Cn(He.inFlight),h)return;let H=await e();h||await ye(n.client.view??H.run)}catch(H){d?.(H)&&n.client.pendingCommand===null?bn():me.pending||de(H,n.client.pendingCommand?.requestId??null)}finally{ue=Math.max(0,ue-1),c.setAttribute("aria-busy",String(ue>0)),h||(Z.hidden=n.client.pendingCommand===null,Pe())}}}function Ve(){ln.schedule()}async function dn(){if(!(h||Qe||ue)&&!me.pending){if(T.active){await T.open(T.receipt);return}Qe=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let r=n.client.view,d=We.queries,H=await n.client.get(r?.screen&&Object.keys(d).length?{nodeId:r.nodeId,visit:r.visit,revision:r.revision,components:d}:void 0);Se&&!h&&(Se=!1,z.hidden=!0,p()),!h&&d===We.queries&&await ye(n.client.view??H.run)}catch(e){de(e),Se=!h}finally{Qe=!1}}}function Xe(e,r,d){if(J?.active){let ce=J;return ce.setDismissHandler(()=>Pn(ce)),ce}let H=tn(t,n,"funnel",()=>Pn(H),Jn);return J=H,H.start(e,r,d),H}function Pn(e){h||pe||(pe=!0,e.finish("dismissed"),be(),c.hidden=!0,n.client.view?Re().finally(oe):oe())}function cn(){clearTimeout(Je?.timeout),Je=void 0}function be(){he=!1,cn(),Ae?.abort(),Ae=void 0,F?.destroy(),F=null,y?.destroy(),y=null,Le?.(),Le=void 0,N.open&&N.close(),E.replaceChildren(),E.style.cssText="",s=void 0,X="",j="",ge=!1,xe="",Ge=""}function Rn(){let e=w.defaultView;i?.responsive&&e&&F?.resizeViewport?.(e.innerHeight,e.innerWidth)}function Ze(){i?.destroy(),i=void 0,a=""}function Ke(e){let r=e.screen?.presentation;if(!r||r.type==="inline"){N.open&&N.close(),Ze(),I.parentElement!==S&&S.append(I),c.parentElement!==t&&t.append(c);for(let ce of["flex","display","flex-direction","justify-content"])E.style.removeProperty(ce);f(e),p();return}c.parentElement!==N&&(N.append(I,c),t.append(N)),E.style.flex="1 0 auto",E.style.display="flex",E.style.flexDirection="column",E.style.justifyContent="center",f(e);let d=e.screen.content.document,H=JSON.stringify([r,le]);if(H!==a){Ze(),a=H;let ce={sm:420,md:640,lg:900},Ce="size"in r&&!r.backdrop?",0 0 0 100vmax #16142566":"";N.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${we.background};color:${we.text};`+(r.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ce[r.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${Ce};`+(r.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),i=$n(N,{presentation:r,theme:d.theme,pages:d.pages},Rn),i.latch()}p(),N.setAttribute("aria-label",(qe?.screen===e.screen?.content.document.name?qe?.label:void 0)??F?.document?.name??e.screen?.content.document.name??"Funnel")}async function rt(e){if(h||pe)return;if(me.observe(),me.pending){Y=e;return}if(ve&&(je()||["running","waiting"].includes(e.status))||(Y=e,ke&&n.client.pendingCommand?.requestId!==ke&&(z.hidden=!0,ke=null),L=e.locale.startsWith("zh"),U.textContent=L?"回看":"History",Q.textContent=T.active?L?"返回当前":"Return to current":L?"返回":"Back",q(),Z.textContent=L?"重试":"Retry",Z.hidden=n.client.pendingCommand===null,Pe(),gn!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(gn=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,Ee(n.onState,structuredClone(e))),h||pe))return;if((!e.pendingRequest||ve&&e.status==="closed")&&["closed","ineligible","failed"].includes(e.status)){oe();return}if(e.stopped&&O()){oe();return}if(e.stopped||n.client.configurationReady===!1){T.stop(),o(),be(),J?.finish("skipped"),c.hidden=!0,Ve();return}if(c.hidden=!1,T.active){Ve();return}let r=Fe(e),d=n.client.view;if(d&&d.revision>e.revision&&Fe(d)!==r)return;let H=!e.instruction&&!e.pendingRequest&&e.nodeType==="screen"&&["running","waiting"].includes(e.status);r!==X&&(X&&J?.finish("dismissed"),be(),X=r,Ie={...e.answers},We.reset());let ce=Ye(e);if(ze===ce){c.hidden=!0;return}if(H&&!r){c.hidden=!0;let $=n.prepared?.state==="shown"?null:Xe(!0,e.locale);!h&&!pe&&Je?.key!==ce&&(cn(),Je={key:ce,timeout:setTimeout(()=>{let v=n.client.view;if(h||!$?.active&&n.prepared?.state!=="shown"||!v||Ye(v)!==ce)return;ze=ce;let B=new Error("Funnel screen preparation timed out");$?.finish("error",B),o(),be(),de(B)},_e)}),Ve();return}cn();let ee=$=>{let v=n.client.view;return!h&&!pe&&!De&&!$.aborted&&n.client.configurationReady!==!1&&!!v&&!v.stopped&&!["closed","ineligible","failed"].includes(v.status)&&Fe(v)===r},Ce=($,v)=>{ee(v)&&(ze=r,J?.finish("error",$),be(),c.hidden=!0,de($))};if(r||((e.instruction&&e.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(e.status))&&o(),Ke(e),e.instruction?.type!=="event"&&e.instruction?.type!=="open_url"&&J?.finish("skipped")),e.screen){o();let $=e.screen.content;if(!F){let ae=e.screen.presentation.type!=="inline",G=Xe(ae,e.locale);if(h||pe)return;let te=(Ae=new AbortController).signal;Ke(e),Le=ae?zn(N):rn(c,t),F=R(E,{mode:"live",closeActions:Array.from(new Set([...n.closeActions??[],...$.document.actions.filter(V=>V.type==="event"&&V.close).map(V=>V.id)])),onAuthoredClose(V){ee(te)&&(he=V,Pe())},rendererUrl:n.client.webViewUrl,title:$.document.name,...ae?{hostPresentation:()=>i?.type??e.screen.presentation.type}:{},onResize:V=>{s=V,i?.responsive&&i.setContentHeight(V+S.getBoundingClientRect().height)},onAction(V,k={},Ue={}){if(T.active||!ee(te)||j!==r)return;Ie={...Ie,...Ue};let pn=e.screen?.inputs??[],qn=Object.fromEntries(pn.filter(({variable:Oe})=>Object.hasOwn(Ie,Oe)).map(({variable:Oe})=>[Oe,Ie[Oe]]));if(Xn(pn,qn).length){bn();return}Ne(()=>n.client.submit({operation:"submit",...Te(),input:{type:"screen",output:V,answers:qn,selection:k}}),!1,Oe=>Wn(Oe,pn))},onAnswers:V=>{T.active||!ee(te)||j!==r||(Ie={...Ie,...V})},onCustomerDataIntent:V=>{T.active||!ee(te)||j!==r||We.intent(V).catch(de)},onEscape:()=>{!ee(te)||j!==r||T.active||fe||K||Re()},onError:V=>{let k=new Error(V);j===r?de(k):Ce(k,te)},onRendered:V=>{if(!(!ee(te)||j===r))try{G.present(k=>{Le?.(),Le=void 0,V&&(qe={screen:$.document.name,label:V},N.setAttribute("aria-label",V)),ae&&(N.showModal(),l=!1,i?.responsive&&N.focus({preventScroll:!0}),!k&&n.loading!=="host"&&xn(N,i?.type??e.screen.presentation.type,i?.responsive)),j=r,ge=ae,Pe()}),ee(te)&&He.report(r)}catch(k){Ce(k,te)}}}),Rn()}let v={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:Ie,values:e.screen.values}},B=JSON.stringify([$,e.locale,v.parameters,e.screen.inputs,e.screen.values]);if(B!==xe)F.update($.document,e.locale,v),xe=B,on=JSON.stringify(v.capabilities),Ge=JSON.stringify(v.customerData);else{let ae=JSON.stringify(v.capabilities);ae!==on&&(F.updateCapabilities(v.capabilities),on=ae),JSON.stringify(v.customerData)!==Ge&&(F.updateCustomerData(v.customerData),Ge=JSON.stringify(v.customerData))}let se=F;if(se)try{await(J?.wait(se.ready)??se.ready)}catch(ae){Ae&&Ce(ae,Ae.signal)}}else if(e.paywall&&!y){let $=e.paywall.resolution,v="document"in $?$.document:null,B=g,se=n.mountPaywallControls,ae=null,G=(Ae=new AbortController).signal,te={loading:"host",signal:G,...se&&{mountControls:k=>se(k,e)},canInteract:()=>ee(G)&&!T.active&&!fe&&!K,beforeAction:async()=>{ue++;try{await Cn(He.settled()),z.hidden=!0,ke=null,Se=!1,p()}finally{ue=Math.max(0,ue-1)}},start:()=>yn(n.client),onObservationChange:Ve,onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resumeCheckout:n.resumeCheckout,allowNewPurchase:n.allowNewPurchase,checkoutNavigation:n.checkoutNavigation,terminateCheckout:n.terminateCheckout,beforeCheckoutReplacement:n.beforeCheckoutReplacement,purchaseConfirmation:n.purchaseConfirmation,confirmOnHostedCheckout:n.confirmOnHostedCheckout,resolveOfferId:n.resolveOfferId,resolveSubscriptionChange:n.resolveSubscriptionChange,claimCoupon:n.claimCoupon,onEvent:n.onEvent,onOpenUrl:k=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:k,openIn:"same_window"}):w.defaultView?.location.assign(k),onAction:async k=>{if(T.active)return;let Ue=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:k,answers:{}}});await ye(n.client.view??Ue.run)},onError:k=>{j===r?de(k):Ce(k,G)}},V={quoteError:k=>Ee(n.onError,k),present(k){ee(G)&&(ae?.present(()=>{k(),j=r,ge=!!E.querySelector("dialog[open]"),ge&&(l=!1),Pe()}),ee(G)&&He.report(r))},async closeAction(k){h||T.active||await me.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:k,answers:{}}})},async dismiss(){if(!(h||G.aborted||T.active||fe||K||!ve&&!ee(G))){if(ve=!0,(n.resumeCheckout||n.terminateCheckout)&&lt()){Y=n.client.view,oe();return}await Re()}}};if(B&&se)o();else if(B){let k=await B.adopt(e,{options:te,handoff:V,start:()=>yn(n.client)});k&&ee(G)&&!h?(Ke(e),y=k,J?.active&&J.present(()=>{}),j=r,ge=B.modal,ge&&(l=!1),Pe(),He.report(r),T.active&&y.setSuspended(!0)):(k?.destroy(),o())}if(h||pe)return;if(!y){if(ae=Xe(!0,e.locale,v),h||pe)return;Ke(e);let k=await x(E,te,V).catch(Ue=>(Ce(Ue,G),null));!ee(G)&&!(ve&&!h&&!G.aborted)?k?.host?.destroy():k&&(y=k.host,y?.setSuspended(T.active))}}if(h||pe)return;Pe();let D=e.instruction;if(D&&(D.type==="open_url"||D.type==="event")&&!Be.has(D.receiptId)){let $=w.createElement("button");$.type="button",$.style.cssText=W.primary,$e($,()=>W.focus),E.style.cssText=W.stage,$.textContent=D.type==="open_url"?`${L?"前往":"Continue to"} ${new URL(D.url).host}`:L?"继续":"Continue",$.onclick=()=>{let v=Te(),B=D.type==="open_url"&&!n.onOpenUrl&&D.openIn==="new_window"?ot(D.url):null;Ne(async()=>{let se="success";if(D.type==="open_url")if(n.onOpenUrl)try{se=await n.onOpenUrl({receiptId:D.receiptId,url:D.url,openIn:D.openIn})===!1?"failed":"opened"}catch(G){Ee(n.onError,G),se="failed"}else se=D.openIn==="new_window"&&!B?"failed":"opened";if(D.type==="event"){if(!n.onEvent)throw new m("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(D.event)}if(h||n.client.view?.nodeId!==v.nodeId||n.client.view.visit!==v.visit)throw new m("PRECONDITION_FAILED","The client action visit changed");let ae=await n.client.submit({operation:"submit",...v,input:{type:"client_action",receiptId:D.receiptId,outcome:se}});return Be.add(D.receiptId),D.type==="open_url"&&!n.onOpenUrl&&D.openIn==="same_window"&&w.defaultView?.location.assign(D.url),ae})},J?.active?J.present(()=>E.replaceChildren($)):E.replaceChildren($)}!e.pendingRequest&&e.status==="completed"&&!Be.has(`complete:${e.id}`)&&(Be.add(`complete:${e.id}`),Ee(n.onComplete,structuredClone(e))),Ve()}function ot(e){let r=w.defaultView?.open(e,"_blank")??null;return r&&(r.opener=null),r}function ye(e){return Pe(),an=an.catch(()=>{}).then(async()=>{try{await rt(e)}catch(r){throw J?.active&&(ze=Ye(e),J.finish("error",r),be(),c.hidden=!0),r}}),an}let st=n.client.subscribe(e=>{if(!vn){if(e.stopped&&(ge||O())&&!ve){Y=e,oe();return}!ve&&(e.stopped||n.client.configurationReady===!1||X&&j!==X&&(Fe(e)!==X||["closed","ineligible","failed"].includes(e.status)))&&(be(),J?.finish("dismissed"),c.hidden=!0),ye(e).catch(de)}}),at=n.client.subscribeError?.(e=>{me.pending||de(e)});function lt(){let e=n.client.view,r=e?.paywall;return!!r?.operation&&!!e&&["running","waiting"].includes(e.status)&&Nn(Me({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect}))}function Re(e){if(De)return De;if(h||!e&&(fe||K))return Promise.resolve();let r=!e&&je();return!r&&n.client.view&&!["running","waiting"].includes(n.client.view.status)?(Y=n.client.view,oe(),Promise.resolve()):(De=Ne(async()=>{let d=r?await n.client.retry():await(e?n.client.submit.bind(n.client):me.submit)({operation:"close",...e??Te()});return e&&In(d),d},!0).then(()=>{let d=n.client.view;d?.status==="closed"&&!je()&&(Y=d,oe())}).finally(()=>{De=null}),De)}function oe(){ie?.destroy(),!h&&(h=!0,me.destroy(),A(),o(),n.signal?.removeEventListener("abort",oe),u?.removeEventListener("abort",oe),J?.finish("dismissed"),ln.destroy(),st(),at?.(),be(),Ze(),T.stop(),N.remove(),c.remove(),l||_(),Ee(n.onDismiss,Y?structuredClone(Y):null))}Q.onclick=()=>{if(!Q.disabled){if(T.active){T.exit();return}Ne(()=>n.client.submit({operation:"back",...Te()}))}},U.onclick=()=>{T.open()},I.onclick=()=>{J?.active?J.dismiss():fe||Re()},Z.onclick=()=>{me.pending?me.retry().catch(()=>{}):je()?Re():Ne(()=>n.client.retry())},N.addEventListener("cancel",e=>{e.preventDefault(),J?.active?J.dismiss():fe||Re()}),n.signal?.addEventListener("abort",oe,{once:!0}),u?.addEventListener("abort",oe,{once:!0});let en=!1;g&&(A=g.onClose(()=>{h||pe||(pe=!0,J?.finish("dismissed"),be(),c.hidden=!0,n.client.view?Re().finally(oe):en=!0)}));let En={destroy:oe,refresh:dn,get recovery(){let e=un();if(e)return e;if(!h&&!ue&&!ve&&!fe&&y){let r=y.recovery;if(r.type!=="native")return r}return{type:"recover",operationId:n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??K?.operationId??null,requestId:n.client.pendingCommand?.requestId??null}},prepareFallback(){if(fe)return fe;let e=un();if(e)return Promise.resolve(e);let r=n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??K?.operationId??null,d=()=>({type:"recover",operationId:r,requestId:n.client.pendingCommand?.requestId??null});if(n.client.hasDurableJournal!==!0){let D=y?.recovery;return Promise.resolve(D&&D.type!=="native"&&D.type!=="cancel"?D:d())}let H=(n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[])).some(D=>D.operation==="close");if(h&&!(H||K&&n.client.view?.status==="closed")||ue||Qe||De||T.active||!y&&!K&&!H)return Promise.resolve(d());let ce=y,ee=(async()=>{try{if(!K&&H){let v=await n.client.retry();return await ye(n.client.view??v.run),d()}if(!K){let v=await ce.prepareFallback();if(v.type!=="native")return v;if(n.client.hasDurableJournal!==!0)return d();K=v}let D=n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[]);if(D.length){let v=D.find(se=>se.operation==="close");if(!v||!ne||v.requestId!==ne.requestId)return d();let B=await n.client.retry();In(B),await ye(n.client.view??B.run)}else{let v=n.client.view,B=v?.paywall;if(!v||!B||B.selectionGeneration===void 0||(B.quote?.operationId??null)!==K.operationId||K.operationId!==null&&B.canReselect!==!0)return d();let se=B.selectionGeneration,ae=await n.client.get();await ye(n.client.view??ae.run);let G=n.client.view,te=G?.paywall;if(!G||!te||!["running","waiting"].includes(G.status)||G.stopped||G.id!==v.id||G.nodeId!==v.nodeId||G.visit!==v.visit||te.receiptId!==B.receiptId||te.selectionGeneration!==se||(te.quote?.operationId??null)!==K.operationId||K.operationId!==null&&te.canReselect!==!0||n.client.pendingPurchase||(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0)))return d();let V=Te();ne={runId:G.id,operationId:K.operationId,revision:V.revision,requestId:V.requestId,nodeId:G.nodeId,visit:G.visit,receiptId:te.receiptId,selectionGeneration:se,acknowledged:!1},await Re(V)}let $=un();return $?(oe(),$):d()}catch(D){return de(D),d()}})();fe=ee;let Ce=()=>{fe===ee&&(fe=null)};return ee.then(Ce,Ce),ee},review:T.open,exitReview:T.exit,get unappliedDrafts(){return T.drafts}};try{let e=n.client.view;if(e)((n.client.viewAgeMs??hn)>=hn||e.instruction?.type==="evaluate_segment")&&(sn=dn().finally(()=>{sn=null})),await ye(e);else{if(c.hidden=!0,h)throw new DOMException("Presentation cancelled","AbortError");let r=en||n.prepared?.state==="shown"?null:Xe(n.client.view?.screen?.presentation.type!=="inline",n.client.view?.locale);if(h||pe&&!en)throw new DOMException("Presentation cancelled","AbortError");let d=n.client.get(),H=await(r?r.wait(d,_e):ct(d,_e));if(vn=!1,en)return h||await Re().finally(oe),En;await ye(n.client.view??H.run)}}catch(e){throw J?.finish("error",e),oe(),e}return En}function ct(t,b){let P;return Promise.race([t,new Promise((n,g)=>{P=setTimeout(()=>g(new Error("Presentation data timed out")),b)})]).finally(()=>clearTimeout(P))}function Zt(t,b,P){return dt(t,b,P)}export{dt as a,Zt as b};