@tinkerlandai/longplay-sdk 0.10.27 → 0.10.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/dist/chunk-2AKQWIK6.js +1 -0
- package/dist/chunk-3JQPCIKN.js +1 -0
- package/dist/{chunk-FB7X4MFC.js → chunk-4GZKK2RE.js} +1 -1
- package/dist/{chunk-WU4SDY27.js → chunk-5KB452HB.js} +1 -1
- package/dist/{chunk-VTZHKUZO.js → chunk-5SL2JQU3.js} +1 -1
- package/dist/{chunk-2GMWNOOE.js → chunk-6KAADDQL.js} +1 -1
- package/dist/{chunk-LI4B43FT.js → chunk-6O4IBSE3.js} +1 -1
- package/dist/{chunk-D4CDG535.js → chunk-6YJ3CFPM.js} +1 -1
- package/dist/{chunk-5M536ISX.js → chunk-ARIVUZUH.js} +1 -1
- package/dist/{chunk-67JOPO63.js → chunk-BSBHQVHH.js} +1 -1
- package/dist/{chunk-LHXRT32T.js → chunk-CK4QMCWN.js} +1 -1
- package/dist/{chunk-WKH23DZE.js → chunk-CTSSHAV7.js} +1 -1
- package/dist/{chunk-TJMODHSS.js → chunk-DVOYXRVB.js} +1 -1
- package/dist/{chunk-S4X6YX5D.js → chunk-FCBTTR5W.js} +1 -1
- package/dist/{chunk-26YREQNF.js → chunk-FKDUXXGT.js} +1 -1
- package/dist/{chunk-2TQEJ6GM.js → chunk-FODM46LT.js} +1 -1
- package/dist/{chunk-AEERSTTW.js → chunk-FVM4JJBA.js} +1 -1
- package/dist/{chunk-MTKM26F7.js → chunk-GRNHBOSS.js} +1 -1
- package/dist/{chunk-SYQMGS6O.js → chunk-IVDXTPNR.js} +2 -2
- package/dist/{chunk-XZMM34BS.js → chunk-JOI5ZUBO.js} +1 -1
- package/dist/{chunk-VRCN5YLM.js → chunk-JPBLMVZR.js} +1 -1
- package/dist/{chunk-EBXWLW4D.js → chunk-LS4XNIXR.js} +1 -1
- package/dist/{chunk-DC7UHEC6.js → chunk-NROHBY3P.js} +1 -1
- package/dist/{chunk-5OJVM7Q4.js → chunk-O4KXODTJ.js} +1 -1
- package/dist/{chunk-MBLWCMAI.js → chunk-O7HHYO3I.js} +1 -1
- package/dist/{chunk-G2QO6ZWP.js → chunk-P3PXFIMG.js} +1 -1
- package/dist/{chunk-S67P7ZQ6.js → chunk-QE6T6NX6.js} +1 -1
- package/dist/chunk-QONPVFRV.js +1 -0
- package/dist/{chunk-COMWJEMO.js → chunk-QQ43HZVT.js} +1 -1
- package/dist/{chunk-7CFSTOTX.js → chunk-RCUBJJ7K.js} +1 -1
- package/dist/{chunk-WCKOWAIL.js → chunk-TEMI3X5X.js} +1 -1
- package/dist/{chunk-HWQVZL7I.js → chunk-UIYOW47V.js} +1 -1
- package/dist/{chunk-LHOSUSTZ.js → chunk-VGLBSYPV.js} +1 -1
- package/dist/{chunk-2ZPCWVFU.js → chunk-W5KG2IWX.js} +1 -1
- package/dist/{chunk-ANZB6OLR.js → chunk-WYMP6O5B.js} +1 -1
- package/dist/{content-4V7YBP3O.js → content-VNX6YOVO.js} +1 -1
- package/dist/{funnel-host-purchase-LJYQF6AX.js → funnel-host-purchase-WRJIUARR.js} +1 -1
- package/dist/funnel-runtime-host-CHE2WGKE.js +1 -0
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-M3V6MBVB.js +1 -0
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-ROG5DVKX.js +1 -0
- package/dist/page.js +1 -1
- package/dist/paywall-OATK5XFF.js +1 -0
- package/dist/paywall-session-ABEEADOM.js +1 -0
- package/dist/popup.d.ts +2 -0
- package/dist/popup.js +1 -1
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-EHGDVWEV.js +1 -0
- package/dist/server.js +1 -1
- package/dist/{visual-dom-CAOVBSVC.js → visual-dom-5LUN4AHO.js} +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-WPLSGFYT.js +0 -1
- package/dist/chunk-XBVJHXSP.js +0 -1
- package/dist/chunk-Z6RZQ5KJ.js +0 -1
- package/dist/funnel-runtime-host-XWXG4SIU.js +0 -1
- package/dist/merchant-bridge-contracts-OL3ME2AL.js +0 -1
- package/dist/operation-contracts-NJPUHGUM.js +0 -1
- package/dist/paywall-INF4ZZ7J.js +0 -1
- package/dist/paywall-session-3JV2JMUI.js +0 -1
- package/dist/screen-renderer-ZRSVFBLQ.js +0 -1
- /package/dist/{chunk-QENDBHBQ.js → chunk-CILM5XMH.js} +0 -0
- /package/dist/{chunk-D6SDVDXZ.js → chunk-OJM6ORHE.js} +0 -0
- /package/dist/{chunk-ZGBSTK22.js → chunk-Z43N7U4U.js} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.28
|
|
4
|
+
|
|
5
|
+
- The Web Funnel host shows a control only while it can act: Back while the Run can go back, Close and History when the presented page does not provide them, and status or error text when there is any. A Funnel whose first page is a Paywall shows no host controls, and the host no longer paints its own background.
|
|
6
|
+
- The Web Paywall footer takes space only while it has a message, a Retry or a needed Close. Inline content that carries its own Close gets no second one.
|
|
7
|
+
- Paywall dialogs reserve visible space for purchase status and actions. Continue checkout shows the original plan and quote, including when tax is confirmed at Checkout.
|
|
8
|
+
- A cancelled or failed purchase says the Customer can choose a plan again, and opening hosted Checkout says so instead of still preparing a price.
|
|
9
|
+
- While a Paywall request is in flight, the content's purchase controls are unavailable. Responsive dialogs show quote errors in the footer without scrolling the dialog.
|
|
10
|
+
- Wire protocol remains `0.10`; public APIs are unchanged.
|
|
11
|
+
|
|
3
12
|
## 0.10.27
|
|
4
13
|
|
|
5
14
|
- Web Paywall and Funnel hosts can opt into confirmation in hosted Checkout for new merchant subscriptions without a trial or separate consent. The original quote, offer and purchase recovery still apply.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{p as n,s as t}from"./chunk-6YJ3CFPM.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as $e,c as cn}from"./chunk-JGG4R75K.js";import{d as ln,f as De,g as Me,h as un,i as Ue,k as dn}from"./chunk-CTSSHAV7.js";import{$ as Le}from"./chunk-JOI5ZUBO.js";import{a as Ve,e as tn,f as rn,g as on,h as sn,i as an}from"./chunk-FKDUXXGT.js";import{b as en}from"./chunk-WYMP6O5B.js";import{R as Xe,qa as nn}from"./chunk-DVOYXRVB.js";import{a as C}from"./chunk-FCBTTR5W.js";import{b as pn,e as mn}from"./chunk-SLUA7ABW.js";import{d as fn}from"./chunk-RCUBJJ7K.js";import{a as oe}from"./chunk-DSPLGTQI.js";import{b as Ze}from"./chunk-O4KXODTJ.js";var qe=new WeakMap;function Fn(n){let v=n.view,m=v?.paywall?.resolution;if(!v||!["running","waiting"].includes(v.status)||v.stopped||!m||"document"in m||!n.resolvePaywall||n.identitySignal?.aborted)return;let e=JSON.stringify(m);if(qe.get(n)?.key===e)return;let p=JSON.parse(e),P=n.identitySignal,r=Promise.resolve().then(async()=>{P?.throwIfAborted();let o=await n.resolvePaywall(p);return P?.throwIfAborted(),o}),R={key:e,content:r};return qe.set(n,R),r.catch(()=>{}),()=>{qe.get(n)===R&&qe.delete(n)}}function wn(n,v){let m=qe.get(n);return qe.delete(n),m?.key===JSON.stringify(v)?m.content:n.resolvePaywall(v)}async function yn(n){let{session:v,load:m}=kn(n);try{return await m(),v}catch(e){throw v.destroy(),e}}function kn(n){let v=n.view;if(!v?.paywall)throw new C("INVALID_REQUEST","The current node is not a Paywall");let m=v.paywall.receiptId,e=v.nodeId,p=v.visit,P=v.paywall.resolution,r=v.paywall,R="document"in P?{document:P.document,offering:P.offering,capabilities:P.capabilities}:null;function o(){let i=r.resolution;return"document"in i?i:R&&{...i,document:R.document,offering:R.offering,capabilities:tn(i.capabilities,R.capabilities)}}function y(i){if(!rn(i,P))throw new C("INVALID_RESPONSE","The pinned Paywall binding changed")}let u=!1,k=new Set,T=null;function _(){let i=o();if(i&&!u)for(let f of k)oe(f,structuredClone(i))}async function E(){O();let i=o();if(i)return structuredClone(i);if(!T){let f=(async()=>{if("document"in r.resolution||!n.resolvePaywall)throw new C("INVALID_RESPONSE","Public Paywall reader is unavailable");let b=await wn(n,r.resolution);return O(),y(b),R={document:b.document,offering:b.offering,capabilities:b.capabilities},_(),o()})();T=f;let l=()=>{T===f&&(T=null)};f.then(l,l)}return T.then(f=>structuredClone(f))}let c=new AbortController,F=(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===p&&i.input.type==="paywall_quote")?.requestId??v.paywall.purchaseRequestId,U=0,$=null,D=new Set,j=null,I=new Map;function V(i){if(i.purchase&&i.purchase.receiptId!==m)throw new C("INVALID_RESPONSE","Purchase receipt changed");let f=i.run.paywall;return i.purchase??(f?.receiptId===m?f:null)}function O(){if(u)throw new C("IDENTITY_CHANGED","Paywall presentation has closed")}function X(i,f,l){if(O(),f!==U||l!==void 0&&r.quote?.operationId!==l)return!1;let b=r.selectionGeneration??0,h=i.run.paywall;if(h?.receiptId===m){if((h.selectionGeneration??0)<(r.selectionGeneration??0))return!1;y(h.resolution)}let d=V(i),G=h?.receiptId===m&&(h.selectionGeneration??0)>b,Q=G?d?.quote??null:d?.quote??r.quote,Y=d?.operation??(Q?.operationId===r.quote?.operationId?r.operation:null);return Q&&Y&&on(Y,{operationId:Q.operationId},"Purchase operation changed"),(G||Q?.operationId!==r.quote?.operationId)&&(U++,h?.receiptId===m&&(F=h.purchaseRequestId)),r={...r,...h?.receiptId===m?h:{},quote:Q,operation:an(r.operation,Y,!0)},_(),!0}function A(i,f,l){return new Promise((b,h)=>{let d=!1,G=()=>{clearTimeout(se),c.signal.removeEventListener("abort",ee)},Q=ce=>{d||(d=!0,G(),b(ce))},Y=ce=>{d||(d=!0,G(),h(ce))},ee=()=>Y(new C("IDENTITY_CHANGED","Paywall presentation has closed")),se=setTimeout(()=>Y(new C("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,l)),Math.max(0,f-Date.now()));c.signal.addEventListener("abort",ee,{once:!0}),c.signal.aborted&&ee(),i.then(Q,Y)})}function N(i){return new Promise(f=>{let l=()=>{clearTimeout(b),c.signal.removeEventListener("abort",l),f()},b=setTimeout(l,i);c.signal.addEventListener("abort",l,{once:!0}),c.signal.aborted&&l()})}function M(i,f){O();let l=I.get(i)??n.pendingCommands?.find(d=>d.requestId===i)??n.pendingCommand;if(l?.operation==="submit"&&l.requestId===i&&l.nodeId===e&&l.visit===p){f.type==="paywall_quote"&&l.input.type==="paywall_quote"&&l.input.predecessor&&!f.predecessor&&(f={...f,predecessor:l.input.predecessor});let d=Le.parse(l),G=Le.parse({...l,input:f});if(d.operation!=="submit"||G.operation!=="submit"||JSON.stringify(d.input)!==JSON.stringify(G.input))throw new C("CONFLICT","A purchase request cannot change its input");return I.set(i,d),d}let b=n.view;if(!b||b.nodeId!==e||b.visit!==p||b.paywall?.receiptId!==m)throw new C("PRECONDITION_FAILED","The Paywall visit has changed");let h=Le.parse({operation:"submit",requestId:i,nodeId:e,visit:p,revision:b.revision,input:structuredClone(f)});if(h.operation!=="submit")throw new C("INVALID_REQUEST","A purchase submission is required");return I.set(i,h),h}async function de(i,f){O();let{requestId:l,input:b}=i,h=Date.now()+3e4;D.add(l);try{let d=await A(n.submit(i),h,l);for(;d.run.pendingRequest?.requestId===l&&Date.now()<h&&!u&&(await N(Math.min(1e3,h-Date.now())),!(u||Date.now()>=h));)d=await A(n.resume(l),h,l);if(u)throw new C("IDENTITY_CHANGED","Paywall presentation has closed");if(d.run.pendingRequest?.requestId===l)throw new C("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,l);if(!X(d,f,b.type==="paywall_confirm"||b.type==="paywall_cancel"?b.operationId:void 0))throw new C("PRECONDITION_FAILED","The purchase selection has changed");j===l&&(j=null)}catch(d){throw j=l,d instanceof C&&d.code==="COMMAND_PENDING"&&d.status===void 0&&I.delete(l),d}finally{D.delete(l)}}async function ie(i){if(!r.quote)throw new C("INVALID_REQUEST","A quoted purchase is required");let f=i==="confirm"?"paywall_confirm":"paywall_cancel",l=[...I.values(),...n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])].find(h=>h.operation==="submit"&&h.input.type===f&&"operationId"in h.input&&h.input.operationId===r.quote.operationId),b=l?.operation==="submit"&&l.input.type===f&&"operationId"in l.input&&l.input.operationId===r.quote.operationId?l.requestId:crypto.randomUUID();if(await de(M(b,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:r.quote.operationId}),U),!r.operation)throw new C("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(r.operation)}let w={get view(){return structuredClone(o())},get quote(){return r.quote?structuredClone(r.quote):null},get operation(){return r.operation?structuredClone(r.operation):null},get webViewUrl(){return n.webViewUrl},get canReselect(){return r.canReselect===!0},get recovery(){let i=n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[]),f=n.pendingPurchase;if(f&&(f.receiptId!==m||f.operationId!==r.quote?.operationId))return{type:"recover",operationId:f.operationId,requestId:i[0]?.requestId??null};let l=Ve({quote:r.quote,operation:r.operation,requestId:i[0]?.requestId??j??F,pending:D.size>0||i.length>0||j!==null,destroyed:u,canReselect:r.canReselect});return l.type==="recover"&&l.requestId===null&&!u&&n.hasDurableJournal===!0&&!r.quote&&!r.operation&&(r.selectionGeneration??0)===0&&!f&&!i.length&&!D.size&&!F?{type:"native",operationId:null}:l},get pendingCancellation(){return!u&&(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===p&&i.input.type==="paywall_cancel"&&i.input.operationId===r.quote?.operationId)},subscribe(i){return u?()=>{}:(k.add(i),()=>k.delete(i))},async refresh(){O();let i=U,f=await n.get();if(X(f,i),f.run.paywall?.receiptId!==m)throw new C("PRECONDITION_FAILED","Paywall presentation has changed");return E()},preview(i){let f=o();if(!f)return Promise.reject(new C("PRECONDITION_FAILED","Load the Paywall presentation first"));if(F&&F!==i.requestId&&($||r.canReselect!==!0))return Promise.reject(new C("COMMAND_PENDING","Retry the original purchase before starting another"));let l=f.document.buttons[i.actionId],b=l?.type==="checkout"?en(l.product,i.selection,f.capabilities):null;if(!b)return Promise.reject(new C("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let h=nn(f.document.screen,b,i.selection,f.capabilities),d=F!==i.requestId&&(r.selectionGeneration??0)>0?{operationId:r.quote?.operationId??null,generation:r.selectionGeneration??0}:void 0;if(d&&r.canReselect!==!0)return Promise.reject(new C("COMMAND_PENDING","Original purchase requires authoritative termination"));let G;try{G=M(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:b,...Object.keys(h).length?{featureQuantities:h}:{},...d?{predecessor:d}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}})}catch(ee){return Promise.reject(ee)}if(F===i.requestId&&$)return $;F!==i.requestId&&U++;let Q=U;F=i.requestId;let Y=(async()=>{if(await de(G,Q),!r.quote)throw new C("INVALID_RESPONSE","The accepted quote is missing");return sn(r.quote,{productVersionId:b,featureQuantities:h},"The selected purchase changed"),structuredClone(r.quote)})();return $=Y,Y.then(()=>{$===Y&&($=null)},ee=>{$===Y&&($=null),F===i.requestId&&n.pendingCommand?.requestId!==i.requestId&&ee instanceof C&&ee.status!==void 0&&ee.status<500&&![401,425].includes(ee.status)&&(F=null)}),Y},confirm:()=>ie("confirm"),cancel:()=>ie("cancel"),async read(){if(O(),!r.quote)throw new C("INVALID_REQUEST","A quoted purchase is required");let i=r.quote.operationId,f=U,l=n.pendingCommands?.find(Q=>Q.operation==="submit"&&(Q.input.type==="paywall_confirm"||Q.input.type==="paywall_cancel")&&Q.input.operationId===i)??n.pendingCommand;l?.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===i&&await n.settle?.(l.requestId);let b=await n.get(void 0,{receiptId:m,operationId:i});O();let h=V(b);if(h?.quote&&h.quote.operationId!==i||h?.operation&&h.operation.operationId!==i)throw new C("INVALID_RESPONSE","Purchase operation changed");let d=X(b,f,i),G=d?r.operation:h?.operation;if(!G)throw new C("INVALID_RESPONSE","The current purchase result is missing");return d&&D.size===0&&!(n.pendingCommands?.length??(n.pendingCommand?1:0))&&(j=null),structuredClone(G)},destroy(){u=!0,H(),k.clear(),c.abort(),I.clear()}},H=n.subscribe(i=>{u||i.nodeId!==e||i.visit!==p||i.paywall?.receiptId!==m||(i.paywall.selectionGeneration??0)<(r.selectionGeneration??0)||(y(i.paywall.resolution),r={...r,resolution:i.paywall.resolution},_())});return{session:w,load:E}}function gn(n){let v=new Set,m=new Set,e=null;async function p(o,y){let u=!1;for(;!n.stopped&&n.key===o&&n.client.pendingCommand?.requestId===y;){if(!n.client.settle)throw new C("COMMAND_PENDING","The original display acknowledgement is still pending");await n.client.settle(y),u=!0,n.client.pendingCommand?.requestId===y&&await new Promise(k=>setTimeout(k,1500))}n.stopped||n.key!==o||(u&&await n.client.get(),!(n.stopped||n.key!==o)&&v.add(o))}function P(o,y){e=y;let u=()=>{e===y&&(e=null),m.delete(o)};return y.then(u,k=>{u(),n.busy||n.fail(k)}),y}function r(o){if(n.reviewing||v.has(o)||m.has(o)||n.stopped)return;m.add(o);let y=async()=>{if(n.reviewing||n.stopped||n.key!==o||v.has(o)){m.delete(o);return}if(n.busy||n.client.pendingCommand){setTimeout(()=>{y()},250);return}let u=(async()=>{if(n.staleRead){if(await n.staleRead,n.stopped||n.key!==o)return;if(n.client.pendingCommand){setTimeout(()=>{y()},250);return}}let k=n.client.view,T=n.expected(),_=T.requestId;try{await n.client.submit({operation:"shown",...T})}catch(E){if(!(E instanceof C)||E.code!=="CONFLICT"||E.status!==409||n.client.pendingCommand)throw E;await n.client.get();let c=n.client.view;if(n.stopped||n.reviewing||n.key!==o||!c||!k||c.id!==k.id||c.source.versionId!==k.source.versionId||c.nodeId!==T.nodeId||c.visit!==T.visit||c.revision<=T.revision||c.stopped||!c.screen&&(!c.paywall||c.paywall.receiptId!==k.paywall?.receiptId)||!["running","waiting"].includes(c.status)||n.client.pendingCommand)throw E;let S=n.expected();_=S.requestId,await n.client.submit({operation:"shown",...S})}await p(o,_)})();P(o,u)};y()}function R(){if(e)return e;let o=n.client.pendingCommand;if(o?.operation!=="shown")return null;let y=n.key;return m.add(y),P(y,(async()=>{await n.client.retry(),await p(y,o.requestId)})())}return{report:r,settled:R,get inFlight(){return e}}}function vn(n){let v={},m=new Map;async function e(p){let P=n.client.view,r=P?.screen,R=r?.customerData.nodes[p.nodeId];if(n.stopped||n.busy||!P||!r||!R)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(p.action)){let E=n.document,c=E?Xe(E,p.nodeId):null,S=c?.type==="customer_data"?c.data.outputs?.[p.action]:void 0;S&&r.outputs.includes(S)?await n.perform(()=>n.client.submit({operation:"submit",...n.expected(),input:{type:"screen",output:S,answers:n.answers,selection:p.value?{[p.nodeId]:p.value}:{}}})):await n.onIntent?.(p,P);return}let y=p.action.startsWith("sources_")?R.resources.find(E=>E.key===p.value):null;if(p.action.startsWith("sources_")&&!y)throw new C("INVALID_REQUEST","Choose a current resource");let u=`${P.visit}:${p.nodeId}:${y?.key??""}`,k=m.get(u)??[null],_=v[p.nodeId]??{page:1,after:null,filter:"all",...y?{resourceKey:y.key}:{}};if(p.action==="filter"){let E=p.value;if(!E||!(R.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(E))throw new C("INVALID_REQUEST","Unknown data filter");_={page:1,after:null,filter:E},k.splice(0,k.length,null)}else if(p.action==="next"||p.action==="sources_next"){let E=y?.sources.at(-1),c=y?E?{kind:"ledger",cursor:{at:E.detail[0],id:E.id,type:"source"}}:null:r.dataCursors[p.nodeId];if(!c||!y&&!R.hasNext)return;k[_.page]=c,_={..._,page:_.page+1,after:c}}else if(p.action==="previous"||p.action==="sources_previous"){if(_.page<=1)return;_={..._,page:_.page-1,after:k[_.page-2]??null}}m.set(u,k),v={...v,[p.nodeId]:_},await n.perform(()=>n.client.get({nodeId:P.nodeId,visit:P.visit,revision:P.revision,components:v}))}return{get queries(){return v},intent:e,reset(){v={},m.clear()}}}function hn(n){let{doc:v,holder:m,reviewHolder:e,mountScreenPreview:p}=n,P=!1,r,R=0,o=null,y="",u,k=new Map,T=c=>c?`${c.id}:${c.nodeId}:${c.visit}:${c.revision}:${c.paywall?.quote?.operationId??""}`:"";async function _(c){if(n.stopped||!n.client.review||P&&c===r&&u?.active)return;let S=!P||c!==r;P||(y=T(n.client.view),k.set(y,structuredClone(n.answers))),P=!0,r=c,m.hidden=!0,n.suspend(!0),e.hidden=!1;let F=++R;S&&(u?.finish("dismissed"),o?.destroy(),o=null,e.replaceChildren(),u=Me(e,n.loadingOptions,"funnel",()=>{E()}));let U=S?u:void 0;try{if(U?.start(!1,n.client.view?.locale),F!==R||n.stopped)return;let $=n.client.review(c),D=await(U?.wait($,De)??$);if(n.stopped||F!==R||!P)return;if(!D.review)throw new C("INVALID_RESPONSE","Historical projection is missing");o?.destroy(),o=null,U||e.replaceChildren();let j=v.createElement("div"),I=U?Ue(j,e):()=>{};e.append(j);let V=D.run.locale.startsWith("zh"),O=v.createElement("p");O.textContent=V?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",j.append(O);for(let[A,N]of D.review.pages.entries()){let M=v.createElement("button");M.type="button",M.textContent=V?`\u7B2C ${A+1} \u9875`:`Page ${A+1}`,M.onclick=()=>{_(N.receiptId)},j.append(M)}if(D.review.page){let A=D.review.page,N=v.createElement("div");N.inert=!0,j.append(N),o=p(N,{mode:"live",rendererUrl:n.client.webViewUrl,title:A.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{F===R&&!n.stopped&&U?.present(I)},onError:de=>{if(F!==R||n.stopped)return;let ie=new Error(de);U?.finish("error",ie),o?.destroy(),o=null,j.remove(),n.fail(ie)},onEscape:()=>{E()}});let M=o;if(M.update(A.document,D.run.locale,{serverInput:{bindings:A.inputs,answers:A.answers,values:A.values}}),await M.ready,n.stopped||F!==R||!P)return}let X=V?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"};for(let A of[...D.review.coupons.map((N,M)=>`${V?"\u4F18\u60E0\u5238":"Coupon"} ${M+1}: ${X[N.status]}`),...D.review.purchases.map((N,M)=>`${V?"\u8D2D\u4E70":"Purchase"} ${M+1}: ${cn(N.status,V)}`)]){let N=v.createElement("p");N.textContent=A,j.append(N)}D.review.page||U?.present(I),n.client.view&&await n.enqueue(n.client.view)}catch($){if(F!==R||n.stopped)return;U?.finish("error",$),o?.destroy(),o=null,e.replaceChildren(),n.fail($)}}async function E(){if(!P||n.stopped||!n.client.review)return;let c=++R;u?.finish("dismissed");try{if(await n.client.review(),n.stopped||c!==R)return;P=!1,R++,u?.finish("dismissed"),o?.destroy(),o=null,e.replaceChildren(),e.hidden=!0,m.hidden=!1;let S=n.client.view;T(S)!==y?(k.set(y,structuredClone(n.answers)),n.resetScreen()):(k.delete(y),n.suspend(!1)),S&&await n.enqueue(S)}catch(S){if(c!==R||n.stopped)return;o?.destroy(),o=null,e.replaceChildren(),n.fail(S)}}return{get active(){return P},get receipt(){return r},open:_,exit:E,get drafts(){return new Map([...k].map(([c,S])=>[c,structuredClone(S)]))},stop(){P=!1,R++,u?.finish("dismissed"),o?.destroy(),o=null,e.replaceChildren(),e.hidden=!0,m.hidden=!1}}}function In(n){if(!n.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let v=n.client.pageExperiments.bind(n.client),m=!1,e=!1,p=0,P=!1,r=!1,R="",o=()=>{let I=n.client.view;return JSON.stringify([I?.id,I?.source.versionId,I?.visit,I?.revision,I?.status,I?.stopped])},y=new Map,u=new Set,k={},T=new Map,_=pn(n.appManifestRelease),E=()=>{for(let I of y.values())I.effect.revert();y.clear()},c=()=>{E();for(let I of T.values())I();T.clear()};function S(I){if(m||u.has(I))return;u.add(I);let V=p;v(n.appManifestRelease,[I]).catch(O=>{u.delete(I),!m&&V===p&&oe(n.onError,O)})}async function F(){if(m)return;R=o();let I=n.client.view;if(!I||I.stopped||!["running","waiting"].includes(I.status)){p++,c();return}if(document.visibilityState==="hidden")return;if(P){r=!0;return}P=!0;let V=++p,O=`${I.id}:${I.visit}:${I.revision}`,X=location.href;try{let[A,{applyVisualVariation:N}]=await Promise.all([v(n.appManifestRelease),import("./visual-dom-5LUN4AHO.js")]),M=n.client.view;if(m||V!==p||!M||M.stopped||!["running","waiting"].includes(M.status)||`${M.id}:${M.visit}:${M.revision}`!==O||location.href!==X)return;let de=new Set,ie=new Set;for(let w of A.assignments){let H=`${A.payload.environmentId}:${w.experimentKey}`;if(ie.add(H),T.has(H)||T.set(H,mn(H,k)),!!w.inExperiment)for(let i of A.payload.experiments){if(i.key!==w.experimentKey||!Ze(location.href,i.urlPatterns??[]))continue;let f=i.meta?.findIndex(Q=>Q.key===w.variationKey)??-1,l=i.variations[f];if(!l?.renderGuard)continue;let b=w.receiptId+":"+i.changeId,h=JSON.stringify([w.variationKey,l]);de.add(b);let d=y.get(b);if(d?.signature===h){d.effect.applied&&S(w.receiptId);continue}y.get(b)?.effect.revert(),y.delete(b);let G=N(l,{requireUniqueTargets:!0,boundVariations:i.variations,allowJs:!1,onApplied:()=>S(w.receiptId),onError:Q=>oe(n.onError,Q)});y.set(b,{signature:h,effect:G}),G.applied&&S(w.receiptId)}}for(let[w,H]of y)de.has(w)||(H.effect.revert(),y.delete(w));for(let[w,H]of T)ie.has(w)||(H(),T.delete(w))}catch(A){V===p&&c(),!m&&V===p&&oe(n.onError,A)}finally{P=!1,r&&!m&&(r=!1,F())}}let U=n.client.subscribe(()=>{if(o()===R)return;R=o(),p++;let I=n.client.view;(!I||I.stopped||!["running","waiting"].includes(I.status))&&c(),e&&F()}),$=fn(()=>{p++,c(),e&&F()}),D=()=>{p++,E()};document.addEventListener("visibilitychange",D);let j=$e({document,run:async()=>{e&&await F()},delay:()=>e&&!m?15e3:void 0});return{async start(){e||m||(e=!0,await j.refresh())},refresh:F,destroy(){m=!0,p++,j.destroy(),document.removeEventListener("visibilitychange",D),U(),$(),c(),_.destroy()}}}var ze=5e3;async function Dn(n,v,m){let e=v,[{mountScreenPreview:p},{showPaywall:P}]=await Promise.all([import("./screen-renderer-EHGDVWEV.js"),import("./paywall-OATK5XFF.js")]),r=e.client.identitySignal;e.signal?.throwIfAborted(),r?.throwIfAborted();let R=e.appManifestRelease?In({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;R?.start();let o=n.ownerDocument,y=dn(o),u=o.createElement("section"),k=o.createElement("div"),T=o.createElement("div"),_=o.createElement("div"),E=o.createElement("button");_.hidden=!0,E.type="button";let c=o.createElement("p"),S=o.createElement("p"),F=o.createElement("button"),U=o.createElement("button"),$=o.createElement("button"),D=o.createElement("dialog"),j;u.dataset.indianaFunnel="",u.setAttribute("aria-busy","false"),u.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033";let I="display:flex;gap:12px;align-items:center;flex-wrap:wrap";T.style.cssText=I,c.setAttribute("role","status"),S.setAttribute("role","alert"),S.hidden=!0,F.type=U.type=$.type="button",T.append(F,c,S,$,E,U),u.append(k,_,T),n.append(u);let V=null,O=null,X=null,A="",N="",M="",de="",ie="",w=!1,H=0,i=!1,f="",l=null,b=Promise.resolve(),h=!e.client.view,d=m,G,Q,Y="",ee,se=!1,ce=null,ge=!1,Fe=()=>e.client.pendingCommand?.operation==="close",re=null,B=null,je=$e({document:o,run:async()=>{(!O?.observing||e.client.pendingCommand)&&await Ge()},delay:()=>{if(!(w||!X||!["running","waiting"].includes(X.status)&&!e.client.pendingCommand)&&!(O?.observing&&!e.client.pendingCommand))return X.pendingRequest||e.client.pendingCommand?1500:ze},hiddenDelay:()=>!w&&e.client.pendingCommand?15e3:void 0}),W=null;function He(){return B&&e.client.hasDurableJournal===!0&&W?.acknowledged===!0&&W.operationId===B.operationId&&e.client.view?.id===W.runId&&e.client.view?.status==="closed"&&e.client.view.revision===W.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?B:null}function Be(t){let s=t.run.paywall;if(W&&t.settlement?.requestId===W.requestId&&t.settlement.state==="settled"&&t.settlement.operationId===null&&t.run.id===W.runId&&t.run.status==="closed"&&!t.run.pendingRequest&&t.run.revision===W.revision+1&&t.run.nodeId===W.nodeId&&t.run.visit===W.visit&&s?.receiptId===W.receiptId&&s.selectionGeneration===W.selectionGeneration&&(s.quote?.operationId??null)===W.operationId&&(s.operation?.operationId??s.quote?.operationId??null)===W.operationId){let a=W.operationId===null&&s.selectionGeneration===0&&!s.quote&&!s.operation&&!s.purchaseRequestId,ne=Ve({quote:s.quote,operation:s.operation,requestId:s.purchaseRequestId,pending:!1,destroyed:!1,canReselect:s.canReselect});(a||s.canReselect===!0&&ne.type==="native")&&(W.acknowledged=!0)}}let Pe=null,Se=new Set,fe={},ae=(t,s=null)=>{w||(Pe=s,S.textContent=t instanceof Error?t.message:"Request failed",S.hidden=!1,$.hidden=e.client.pendingCommand===null,oe(e.onError,t))};function Ie(){let t=e.client.view;if(!t)throw new C("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let L=hn({client:e.client,doc:o,holder:k,reviewHolder:_,mountScreenPreview:p,loadingOptions:e,get stopped(){return w},get answers(){return fe},suspend(t){O?.setSuspended(t)},resetScreen(){A="",N="",M=""},enqueue:me,fail:ae}),Oe=gn({client:e.client,expected:Ie,fail:ae,get stopped(){return w},get reviewing(){return L.active},get key(){return A},get busy(){return H},get staleRead(){return l}}),Ne=vn({client:e.client,expected:Ie,perform:Ee,onIntent:e.onCustomerDataIntent,get stopped(){return w},get busy(){return H},get document(){return V?.document},get answers(){return fe}}),Ae=t=>`${t.id}:${t.nodeId}:${t.visit}`,Re=t=>t&&(t.screen||t.paywall)?Ae(t):"";function be(){let t=e.client.view;F.disabled=!L.active&&(H>0||!!e.client.pendingCommand||!t?.canBack||t.stopped||!["running","waiting"].includes(t.status)||!Re(t)||N!==Re(t)),We()}function We(){let t=e.client.view;F.hidden=!L.active&&!t?.canBack;let s=!!O&&!L.active;U.hidden=s&&!d?.active,E.hidden=!e.client.review||s&&!t?.canBack,s&&(c.textContent="");let a=F.hidden&&U.hidden&&$.hidden&&E.hidden&&S.hidden&&!c.textContent;T.style.cssText=a?I:`${I};padding:12px 20px`}async function Ye(t){if(!t)return;let s=e.client.view;await t;let a=e.client.view;if(!s||!a||a.id!==s.id||a.nodeId!==s.nodeId||a.visit!==s.visit||a.stopped||!["running","waiting"].includes(a.status))throw new C("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Ee(t,s=!1){if(!((H||ge||re||B)&&!s||w||L.active&&!s)){H++,u.setAttribute("aria-busy","true"),be(),S.hidden=!0,Pe=null;try{if(s||await Ye(Oe.inFlight),w)return;let a=await t();w||await me(e.client.view??a.run)}catch(a){ae(a,e.client.pendingCommand?.requestId??null)}finally{H=Math.max(0,H-1),u.setAttribute("aria-busy",String(H>0)),w||($.hidden=e.client.pendingCommand===null,be())}}}function ke(){je.schedule()}async function Ge(){if(!(w||i||H)){if(L.active){await L.open(L.receipt);return}i=!0;try{let t=e.client.pendingCommand;t&&e.client.settle&&await e.client.settle(t.requestId);let s=e.client.view,a=Ne.queries,ne=await e.client.get(s?.screen&&Object.keys(a).length?{nodeId:s.nodeId,visit:s.visit,revision:s.revision,components:a}:void 0);!w&&a===Ne.queries&&await me(e.client.view??ne.run)}catch(t){ae(t)}finally{i=!1}}}function Te(t,s){if(d?.active){let ne=d;return ne.setDismissHandler(()=>Ke(ne)),ne}let a=Me(n,e,"funnel",()=>Ke(a));return d=a,a.start(t,s),a}function Ke(t){w||se||(se=!0,t.finish("dismissed"),ve(),u.hidden=!0,e.client.view?Ce().finally(le):le())}function Qe(){clearTimeout(ee?.timeout),ee=void 0}function ve(){Qe(),G?.abort(),G=void 0,V?.destroy(),V=null,O?.destroy(),O=null,Q?.(),Q=void 0,D.open&&D.close(),k.replaceChildren(),A="",N="",M="",ie=""}function Je(t){let s=t.screen?.presentation;if(!s||s.type==="inline"){D.open&&D.close(),u.parentElement!==n&&n.append(u);return}u.parentElement!==D&&(D.append(u),n.append(D));let a={sm:420,md:640,lg:900};D.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in s?a[s.size]+"px":"100vw"}`,D.setAttribute("aria-label",(j?.screen===t.screen?.content.document.name?j?.label:void 0)??V?.document?.name??t.screen?.content.document.name??"Funnel")}async function bn(t){if(w||se||ge&&(Fe()||["running","waiting"].includes(t.status)))return;X=t,Pe&&e.client.pendingCommand?.requestId!==Pe&&(S.hidden=!0,Pe=null);let s=t.locale.startsWith("zh");if(E.textContent=s?"\u56DE\u770B":"History",F.textContent=L.active?s?"\u8FD4\u56DE\u5F53\u524D":"Return to current":s?"\u8FD4\u56DE":"Back",U.textContent=s?"\u5173\u95ED":"Close",$.textContent=s?"\u91CD\u8BD5":"Retry",be(),$.hidden=e.client.pendingCommand===null,c.textContent=t.pendingRequest?s?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?s?"\u7B49\u5F85\u4E2D":"Waiting":"",We(),f!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(f=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,oe(e.onState,structuredClone(t))),w||se)return;if((!t.pendingRequest||ge&&t.status==="closed")&&["closed","ineligible","failed"].includes(t.status)){le();return}if(t.stopped||e.client.configurationReady===!1){L.stop(),ve(),d?.finish("skipped"),u.hidden=!0,ke();return}if(u.hidden=!1,L.active){ke();return}let a=Re(t),ne=e.client.view;if(ne&&ne.revision>t.revision&&Re(ne)!==a)return;let xe=!t.instruction&&!t.pendingRequest&&t.nodeType==="screen"&&["running","waiting"].includes(t.status);a!==A&&(A&&d?.finish("dismissed"),ve(),A=a,fe={...t.answers},Ne.reset());let we=Ae(t);if(Y===we){u.hidden=!0;return}if(xe&&!a){u.hidden=!0;let q=Te(!0,t.locale);!w&&!se&&ee?.key!==we&&(Qe(),ee={key:we,timeout:setTimeout(()=>{let g=e.client.view;if(!q.active||!g||Ae(g)!==we)return;Y=we;let Z=new Error("Funnel screen preparation timed out");q.finish("error",Z),ve(),ae(Z)},De)}),ke();return}Qe();let te=q=>{let g=e.client.view;return!w&&!se&&!ce&&!q.aborted&&e.client.configurationReady!==!1&&!!g&&!g.stopped&&!["closed","ineligible","failed"].includes(g.status)&&Re(g)===a},K=(q,g)=>{te(g)&&(Y=a,d?.finish("error",q),ve(),u.hidden=!0,ae(q))};if(a||(Je(t),t.instruction?.type!=="event"&&t.instruction?.type!=="open_url"&&d?.finish("skipped")),t.screen){let q=t.screen.content;if(!V){let z=t.screen.presentation.type!=="inline",ye=Te(z,t.locale);if(w||se)return;let ue=(G=new AbortController).signal;Je(t),Q=z?un(D):Ue(u,n),V=p(k,{mode:"live",rendererUrl:e.client.webViewUrl,title:q.document.name,onAction(pe,he={},En={}){if(L.active||!te(ue)||N!==a)return;fe={...fe,...En};let qn=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:_e})=>Object.hasOwn(fe,_e)).map(({variable:_e})=>[_e,fe[_e]]));Ee(()=>e.client.submit({operation:"submit",...Ie(),input:{type:"screen",output:pe,answers:qn,selection:he}}))},onAnswers:pe=>{L.active||!te(ue)||N!==a||(fe={...fe,...pe})},onCustomerDataIntent:pe=>{L.active||!te(ue)||N!==a||Ne.intent(pe).catch(ae)},onEscape:()=>{!te(ue)||N!==a||L.active||re||B||Ce()},onError:pe=>{let he=new Error(pe);N===a?ae(he):K(he,ue)},onRendered:pe=>{if(!(!te(ue)||N===a))try{ye.present(he=>{Q?.(),Q=void 0,pe&&(j={screen:q.document.name,label:pe},D.setAttribute("aria-label",pe)),z&&(D.showModal(),!he&&e.loading!=="host"&&ln(D,t.screen.presentation.type)),N=a,be()}),te(ue)&&Oe.report(a)}catch(he){K(he,ue)}}})}let g={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:fe,values:t.screen.values}},Z=JSON.stringify([q,t.locale,g.parameters,t.screen.inputs,t.screen.values]);if(Z!==M)V.update(q.document,t.locale,g),M=Z,de=JSON.stringify(g.capabilities),ie=JSON.stringify(g.customerData);else{let z=JSON.stringify(g.capabilities);z!==de&&(V.updateCapabilities(g.capabilities),de=z),JSON.stringify(g.customerData)!==ie&&(V.updateCustomerData(g.customerData),ie=JSON.stringify(g.customerData))}let x=V;if(x)try{await(d?.wait(x.ready)??x.ready)}catch(z){G&&K(z,G.signal)}}else if(t.paywall&&!O){let q=Te(!0,t.locale);if(w||se)return;let g=(G=new AbortController).signal;Je(t);let Z=await P(k,{loading:"host",signal:g,canInteract:()=>te(g)&&!L.active&&!re&&!B,beforeAction:async()=>{H++;try{await Ye(Oe.settled()),S.hidden=!0,Pe=null}finally{H=Math.max(0,H-1)}},start:()=>yn(e.client),onObservationChange:ke,onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,checkoutNavigation:e.checkoutNavigation,confirmOnHostedCheckout:e.confirmOnHostedCheckout,resolveOfferId:e.resolveOfferId,onEvent:e.onEvent,onOpenUrl:x=>e.onOpenUrl?e.onOpenUrl({receiptId:t.paywall.receiptId,url:x,openIn:"same_window"}):o.defaultView?.location.assign(x),onAction:async x=>{if(L.active)return;let z=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:e.client.view?.revision??t.revision,input:{type:"screen",output:x,answers:{}}});await me(e.client.view??z.run)},onError:x=>{N===a?ae(x):K(x,g)}},{quoteError:x=>oe(e.onError,x),present(x){te(g)&&(q.present(()=>{x(),N=a,be()}),te(g)&&Oe.report(a))},async dismiss(){w||g.aborted||L.active||re||B||!ge&&!te(g)||(ge=!0,await Ce())}}).catch(x=>(K(x,g),null));!te(g)&&!(ge&&!w&&!g.aborted)?Z?.host?.destroy():Z&&(O=Z.host,O?.setSuspended(L.active))}if(w||se)return;be();let J=t.instruction;if(J&&(J.type==="open_url"||J.type==="event")&&!Se.has(J.receiptId)){let q=o.createElement("button");q.type="button",q.textContent=J.type==="open_url"?`${s?"\u524D\u5F80":"Continue to"} ${new URL(J.url).host}`:s?"\u7EE7\u7EED":"Continue",q.onclick=()=>{let g=Ie(),Z=J.type==="open_url"&&!e.onOpenUrl&&J.openIn==="new_window"?Cn(J.url):null;Ee(async()=>{let x="success";if(J.type==="open_url")if(e.onOpenUrl)try{x=await e.onOpenUrl({receiptId:J.receiptId,url:J.url,openIn:J.openIn})===!1?"failed":"opened"}catch(ye){oe(e.onError,ye),x="failed"}else x=J.openIn==="new_window"&&!Z?"failed":"opened";if(J.type==="event"){if(!e.onEvent)throw new C("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(J.event)}if(w||e.client.view?.nodeId!==g.nodeId||e.client.view.visit!==g.visit)throw new C("PRECONDITION_FAILED","The client action visit changed");let z=await e.client.submit({operation:"submit",...g,input:{type:"client_action",receiptId:J.receiptId,outcome:x}});return Se.add(J.receiptId),J.type==="open_url"&&!e.onOpenUrl&&J.openIn==="same_window"&&o.defaultView?.location.assign(J.url),z})},d?.active?d.present(()=>k.replaceChildren(q)):k.replaceChildren(q)}!t.pendingRequest&&t.status==="completed"&&!Se.has(`complete:${t.id}`)&&(Se.add(`complete:${t.id}`),oe(e.onComplete,structuredClone(t))),ke()}function Cn(t){let s=o.defaultView?.open(t,"_blank")??null;return s&&(s.opener=null),s}function me(t){return be(),b=b.catch(()=>{}).then(async()=>{try{await bn(t)}catch(s){throw d?.active&&(Y=Ae(t),d.finish("error",s),ve(),u.hidden=!0),s}}),b}let Pn=e.client.subscribe(t=>{h||(!ge&&(t.stopped||e.client.configurationReady===!1||A&&N!==A&&(Re(t)!==A||["closed","ineligible","failed"].includes(t.status)))&&(ve(),d?.finish("dismissed"),u.hidden=!0),me(t).catch(ae))}),Rn=e.client.subscribeError?.(ae);function Ce(t){if(ce)return ce;if(w||!t&&(re||B))return Promise.resolve();let s=!t&&Fe();return!s&&e.client.view&&!["running","waiting"].includes(e.client.view.status)?(X=e.client.view,le(),Promise.resolve()):(ce=Ee(async()=>{let a=s?await e.client.retry():await e.client.submit({operation:"close",...t??Ie()});return t&&Be(a),a},!0).then(()=>{let a=e.client.view;a?.status==="closed"&&!Fe()&&(X=a,le())}).finally(()=>{ce=null}),ce)}function le(){R?.destroy(),!w&&(w=!0,e.signal?.removeEventListener("abort",le),r?.removeEventListener("abort",le),d?.finish("dismissed"),je.destroy(),Pn(),Rn?.(),ve(),L.stop(),D.remove(),u.remove(),y(),oe(e.onDismiss,X?structuredClone(X):null))}F.onclick=()=>{if(!F.disabled){if(L.active){L.exit();return}Ee(()=>e.client.submit({operation:"back",...Ie()}))}},E.onclick=()=>{L.open()},U.onclick=()=>{d?.active?d.dismiss():re||Ce()},$.onclick=()=>{Fe()?Ce():Ee(()=>e.client.retry())},D.addEventListener("cancel",t=>{t.preventDefault(),d?.active?d.dismiss():re||Ce()}),e.signal?.addEventListener("abort",le,{once:!0}),r?.addEventListener("abort",le,{once:!0});try{let t=e.client.view;if(t)((e.client.viewAgeMs??ze)>=ze||t.instruction?.type==="evaluate_segment")&&(l=Ge().finally(()=>{l=null})),await me(t);else{u.hidden=!0;let s=Te(e.client.view?.screen?.presentation.type!=="inline",e.client.view?.locale);if(w||se)throw new DOMException("Presentation cancelled","AbortError");let a=await s.wait(e.client.get(),De);h=!1,await me(e.client.view??a.run)}}catch(t){throw d?.finish("error",t),le(),t}return{destroy:le,refresh:Ge,get recovery(){let t=He();if(t)return t;if(!w&&!H&&!ge&&!re&&O){let s=O.recovery;if(s.type!=="native")return s}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??B?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(re)return re;let t=He();if(t)return Promise.resolve(t);let s=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??B?.operationId??null,a=()=>({type:"recover",operationId:s,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let K=O?.recovery;return Promise.resolve(K&&K.type!=="native"&&K.type!=="cancel"?K:a())}let ne=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(K=>K.operation==="close");if(w&&!(ne||B&&e.client.view?.status==="closed")||H||i||ce||L.active||!O&&!B&&!ne)return Promise.resolve(a());let xe=O,we=(async()=>{try{if(!B&&ne){let q=await e.client.retry();return await me(e.client.view??q.run),a()}if(!B){let q=await xe.prepareFallback();if(q.type!=="native")return q;if(e.client.hasDurableJournal!==!0)return a();B=q}let K=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(K.length){let q=K.find(Z=>Z.operation==="close");if(!q||!W||q.requestId!==W.requestId)return a();let g=await e.client.retry();Be(g),await me(e.client.view??g.run)}else{let q=e.client.view,g=q?.paywall;if(!q||!g||g.selectionGeneration===void 0||(g.quote?.operationId??null)!==B.operationId||B.operationId!==null&&g.canReselect!==!0)return a();let Z=g.selectionGeneration,x=await e.client.get();await me(e.client.view??x.run);let z=e.client.view,ye=z?.paywall;if(!z||!ye||!["running","waiting"].includes(z.status)||z.stopped||z.id!==q.id||z.nodeId!==q.nodeId||z.visit!==q.visit||ye.receiptId!==g.receiptId||ye.selectionGeneration!==Z||(ye.quote?.operationId??null)!==B.operationId||B.operationId!==null&&ye.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return a();let ue=Ie();W={runId:z.id,operationId:B.operationId,revision:ue.revision,requestId:ue.requestId,nodeId:z.nodeId,visit:z.visit,receiptId:ye.receiptId,selectionGeneration:Z,acknowledged:!1},await Ce(ue)}let J=He();return J?(le(),J):a()}catch(K){return ae(K),a()}})();re=we;let te=()=>{re===we&&(re=null)};return we.then(te,te),we},review:L.open,exitReview:L.exit,get unappliedDrafts(){return L.drafts}}}function yt(n,v,m){return Dn(n,v,m)}export{Fn as a,In as b,Dn as c,yt as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as G}from"./chunk-XBVJHXSP.js";import{b as Z}from"./chunk-S67P7ZQ6.js";import{a as j,b as Q,c as x}from"./chunk-G2QO6ZWP.js";import{a as L,b as F,c as H,j as l}from"./chunk-2ZPCWVFU.js";import{b as e}from"./chunk-ZGBSTK22.js";var fe=["purchase.subscription","purchase.one_time","purchase.prepaid","purchase.trial","purchase.seats","purchase.tiered","tax.automatic","discount.percent.once","discount.percent.repeating","discount.percent.forever","discount.amount.once","discount.amount.repeating","discount.amount.forever","subscription.cancel.immediate","subscription.cancel.renewal","subscription.resume","subscription.plan.immediate","subscription.plan.renewal","subscription.seats","subscription.quantity","subscription.billing_cycle","subscription.proration","refund.full","refund.partial","refund.revoke"],K=e.enum(fe),W=e.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","subscription.change.closed","invoice.paid","refund.updated"]);var o=e.string().min(1).max(200),c=e.iso.datetime({offset:!0}),i=e.number().int().nonnegative().max(1e8),y=e.string().regex(/^[A-Z]{3}$/),m=e.strictObject({priceId:e.uuid(),productVersionId:e.uuid(),productId:o,quantity:e.number().int().min(1).max(1e6),unitAmountMinor:i,totalMinor:i,interval:e.enum(["week","month","year","one_off"]),intervalCount:e.number().int().min(1).max(52),kind:e.enum(["fixed","prepaid","seat"]),tiers:e.strictObject({mode:e.enum(["graduated","volume"]),tiers:e.array(e.strictObject({upTo:e.number().int().positive().nullable(),unitAmountMinor:i,flatAmountMinor:i.optional()})).min(2).max(12)}).nullable()}),I=e.strictObject({grantId:e.uuid(),couponId:e.uuid(),amountMinor:i,applicationPolicy:G.optional(),applicableProductIds:e.array(o).min(1).max(100).optional(),terms:e.discriminatedUnion("type",[e.strictObject({type:e.literal("percent"),percentOff:e.number().gt(0).max(100)}),e.strictObject({type:e.literal("amount"),amountOffMinor:i,currency:y})]),duration:e.discriminatedUnion("type",[e.strictObject({type:e.literal("once")}),e.strictObject({type:e.literal("forever")}),e.strictObject({type:e.literal("repeating"),months:e.number().int().min(1).max(36)})])}),E={provider:e.literal("merchant"),executor:e.literal("merchant"),operationId:e.uuid(),customerId:e.uuid(),configurationRevision:e.number().int().nonnegative(),connectionRevision:e.number().int().nonnegative(),currency:y,expiresAt:c},ge=e.strictObject({...E,type:e.literal("purchase"),mode:e.enum(["payment","subscription"]),lineItems:e.array(m).min(1).max(100),catalogAmountMinor:i,nativeDiscountMinor:i.optional(),discount:I.nullable(),trialPeriodDays:e.number().int().min(1).max(730).nullable(),automaticTax:e.boolean()}).refine(t=>t.lineItems.reduce((n,r)=>n+r.totalMinor,0)===t.catalogAmountMinor&&(t.discount?.amountMinor??0)+(t.nativeDiscountMinor??0)<=t.catalogAmountMinor&&new Set(t.lineItems.map(n=>n.priceId)).size===t.lineItems.length,"Purchase lines must retain the original total and unique Price identities"),S=e.strictObject({...E,type:e.literal("subscription_change"),subscriptionId:e.uuid(),merchantSubscriptionId:o,membershipId:e.uuid(),subscriptionAction:e.enum(["update","cancel","schedule","release"]),supersedesOperationId:e.uuid().nullable(),change:e.discriminatedUnion("type",[e.strictObject({type:e.literal("cancel")}),e.strictObject({type:e.literal("uncancel")}),e.strictObject({type:e.literal("plan"),productVersionId:e.uuid()}),e.strictObject({type:e.literal("seats"),licenseKey:o,quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("quantity"),internal_feature_id:e.uuid(),quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("billing_cycle"),billingCycleAnchor:e.union([e.literal("now"),e.number().int().positive()])})]),timing:e.enum(["immediate","renewal"]),effectiveAt:c,creditMinor:i,debitMinor:i,totalMinor:i,discountMinor:i,discount:I.nullable().optional(),taxMinor:i,proration:e.enum(["none","create_prorations","always_invoice"]),lineItems:e.array(m.extend({quantity:e.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:e.array(e.uuid()).max(100),sourceLineItems:e.array(m).min(1).max(100).optional()}),xe=e.strictObject({...E,type:e.literal("refund"),invoiceId:e.uuid(),merchantInvoiceId:o,amountMinor:i.refine(t=>t>0),mode:e.enum(["full","partial"]),entitlementAction:e.enum(["retain","revoke"]),cancelSubscriptions:e.array(o).max(100)}),Y=e.discriminatedUnion("type",[ge,S,xe]);function We(t){let n=new Set;if(t.type==="purchase")n.add(t.mode==="subscription"?"purchase.subscription":"purchase.one_time"),t.lineItems.some(r=>r.kind==="prepaid")&&n.add("purchase.prepaid"),t.lineItems.some(r=>r.kind==="seat")&&n.add("purchase.seats"),t.lineItems.some(r=>r.tiers!==null)&&n.add("purchase.tiered"),t.trialPeriodDays!==null&&n.add("purchase.trial"),t.automaticTax&&n.add("tax.automatic"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`);else if(t.type==="refund")n.add(`refund.${t.mode}`),t.entitlementAction==="revoke"&&n.add("refund.revoke");else{let r=t.change.type;r==="cancel"?n.add(`subscription.cancel.${t.timing}`):r==="uncancel"?n.add("subscription.resume"):r==="plan"?n.add(`subscription.plan.${t.timing}`):n.add(`subscription.${r}`),t.proration!=="none"&&n.add("subscription.proration"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`)}return[...n].sort()}function Xe(t){return t.type==="purchase"?t.mode==="subscription"?["purchase.completed","purchase.closed","subscription.observed","invoice.paid"]:["purchase.completed","purchase.closed"]:t.type==="subscription_change"?["subscription.change.completed","subscription.change.closed","subscription.observed",...t.change.type==="cancel"||t.change.type==="uncancel"?[]:["invoice.paid"]]:["refund.updated",...t.entitlementAction==="revoke"&&t.cancelSubscriptions.length?["subscription.observed"]:[]]}var ye=e.strictObject({phase:e.enum(["execution","payment","fulfillment","recording"]),code:L,reason:H.optional(),recovery:F,retryable:e.boolean()}).refine(t=>t.reason!=="RESULT_UNKNOWN"||!t.retryable&&t.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Ie=e.strictObject({type:e.literal("redirect"),url:e.url().startsWith("https://"),expiresAt:c}),B={operationId:e.uuid(),customerId:e.uuid(),merchantExecutionId:o,fulfillmentStatus:e.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:e.enum(["not_ready","pending","accepted","failed"]),updatedAt:c,problem:ye.nullable(),pollAfterMs:e.number().int().min(1e3).max(6e4).nullable()},T=e.discriminatedUnion("type",[e.strictObject({...B,type:e.literal("purchase"),merchantOrderId:o.nullable(),paymentStatus:e.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:e.url().refine(t=>new URL(t).protocol==="https:").nullable(),checkoutExpiresAt:c.nullable()}).refine(t=>!t.checkoutUrl||["not_started","pending"].includes(t.paymentStatus)&&t.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),e.strictObject({...B,type:e.literal("subscription_change"),status:e.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:o,scheduledFor:c.nullable(),nextAction:Ie.optional()}).refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"A scheduled change retains its future effective time"),e.strictObject({...B,type:e.literal("refund"),status:e.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:o.nullable()}).refine(t=>t.status!=="succeeded"||t.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),ee=e.discriminatedUnion("lookup",[e.strictObject({lookup:e.literal("found"),operationId:e.uuid(),customerId:e.uuid(),execution:T,readAt:c}),e.strictObject({lookup:e.literal("not_received"),operationId:e.uuid(),customerId:e.uuid(),execution:e.null(),readAt:c})]).refine(t=>!t.execution||t.execution.operationId===t.operationId&&t.execution.customerId===t.customerId,"Lookup must retain the original Customer and operation"),te=e.strictObject({merchantPriceId:o,productId:o,kind:e.enum(["fixed","prepaid"]),currency:y,unitAmountMinor:i,interval:e.enum(["one_off","day","week","month","year"]),intervalCount:e.number().int().min(1).max(100)}),X={merchantItemId:o,quantity:e.number().int().positive().max(1e6)},Se=t=>t.priceId??JSON.stringify(t.nativePrice),k=e.strictObject({merchantSubscriptionId:o,revision:e.number().int().positive(),status:e.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:c,periodEndsAt:c,cancelAtPeriodEnd:e.boolean(),hasDiscounts:e.boolean(),items:e.array(e.union([e.strictObject({...X,priceId:e.uuid()}),e.strictObject({...X,nativePrice:te})])).min(1).max(100)}).refine(t=>Date.parse(t.periodEndsAt)>Date.parse(t.periodStartsAt)&&new Set(t.items.map(Se)).size===t.items.length&&new Set(t.items.map(n=>n.merchantItemId)).size===t.items.length,"Subscription periods and Price identities must be unambiguous"),J={merchantLineId:o,quantity:e.number().int().nonnegative().max(1e6),subtotalMinor:e.number().int().min(-1e8).max(1e8),discountMinor:i,taxMinor:i,totalMinor:e.number().int().min(-1e8).max(2e8),periodStartsAt:c.nullable(),periodEndsAt:c.nullable()},R=e.strictObject({merchantInvoiceId:o,reason:e.enum(["renewal","adjustment"]).optional(),currency:y,subtotalMinor:i,discountMinor:i,taxMinor:i,totalMinor:i,paidMinor:i,periodStartsAt:c.nullable(),periodEndsAt:c.nullable(),lines:e.array(e.union([e.strictObject({...J,priceId:e.uuid()}),e.strictObject({...J,nativePrice:te})]).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&(t.subtotalMinor<0?t.discountMinor===0&&t.taxMinor===0:t.discountMinor<=t.subtotalMinor),"Invoice line amounts must retain the complete debit or credit")).min(1).max(100)}).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&t.discountMinor<=t.subtotalMinor&&t.paidMinor===t.totalMinor&&new Set(t.lines.map(n=>n.merchantLineId)).size===t.lines.length&&t.lines.reduce((n,r)=>n+r.subtotalMinor,0)===t.subtotalMinor&&t.lines.reduce((n,r)=>n+r.discountMinor,0)===t.discountMinor&&t.lines.reduce((n,r)=>n+r.taxMinor,0)===t.taxMinor&&t.lines.reduce((n,r)=>n+r.totalMinor,0)===t.totalMinor,"A paid Invoice retains the complete financial amounts"),p={eventId:e.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:e.uuid(),occurredAt:c},Me=e.strictObject({...p,type:e.literal("purchase.completed"),operationId:e.uuid(),merchantOrderId:o,paymentStatus:e.enum(["paid","trialing","no_payment_required"]),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable(),subscription:k.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),_e=e.strictObject({...p,type:e.literal("purchase.closed"),operationId:e.uuid(),status:e.enum(["failed","expired","canceled"])}),Oe=e.strictObject({...p,type:e.literal("subscription.observed"),operationId:e.uuid().nullable(),subscription:k}),ve=e.strictObject({...p,type:e.literal("subscription.change.completed"),operationId:e.uuid(),status:e.enum(["scheduled","applied"]),scheduledFor:c.nullable(),subscription:k.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities"),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),Ae=e.strictObject({...p,type:e.literal("subscription.change.closed"),operationId:e.uuid(),merchantSubscriptionId:o,merchantInvoiceId:o.nullable(),status:e.enum(["failed","expired","canceled"])}),je=e.strictObject({...p,type:e.literal("invoice.paid"),merchantSubscriptionId:o.nullable(),invoice:R}),Pe=e.strictObject({...p,type:e.literal("refund.updated"),operationId:e.uuid().nullable(),merchantInvoiceId:o.optional(),merchantRefundId:o,status:e.enum(["pending","succeeded","failed"]),amountMinor:i.refine(t=>t>0),currency:y}),Je=[Me.refine(t=>t.paymentStatus!=="paid"||t.invoice!==null,"A paid purchase includes its Invoice"),_e,Oe.refine(t=>t.operationId===null||t.subscription.items.every(n=>"priceId"in n),"Native Price references cannot replace an operation's quoted Prices"),ve.refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),Ae,je,Pe.refine(t=>t.operationId!==null||t.merchantInvoiceId!==void 0,"A native refund names its Invoice")];var z=e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}),rt=e.object({...z.shape,featureAllowances:e.record(e.uuid(),e.number().int().min(0).max(1e9)),creditAmounts:e.record(e.uuid(),l)}).strict(),it=e.object({id:e.uuid(),planVersionId:e.uuid(),slot:e.string(),cardRequired:e.boolean(),status:e.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),createdAt:e.iso.datetime()}).strict();var qe=e.number().int().positive().max(2e8),ne=e.number().int().min(0).max(2e8),re=t=>t.mode==="partial"==(t.amountMinor!==void 0),P=e.strictObject({mode:e.enum(["full","partial"]),amountMinor:qe.optional(),entitlementAction:e.enum(["retain","revoke"])});var a=e.string().min(1).max(200),b=e.iso.datetime({offset:!0}),f=ne,ie=f.maxValue,C=e.number().int().min(-ie).max(ie),q=e.string().regex(/^[A-Z]{3}$/),oe=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),ae=e.array(a).max(100).refine(t=>new Set(t).size===t.length),Ce=e.strictObject({merchantProductId:a,merchantPriceId:a,productVersionId:e.uuid().optional(),quantity:l.refine(t=>/[1-9]/.test(t))}),w={subject:Q,operationId:e.uuid(),configurationRevision:oe,connectionRevision:oe,expiresAt:b},D=e.discriminatedUnion("action",[e.strictObject({...w,action:e.literal("purchase"),mode:e.enum(["payment","subscription"]),currency:q,items:e.array(Ce).min(1).max(100),offerRefs:ae}),e.strictObject({...w,action:e.literal("subscription_change"),currency:q,merchantSubscriptionId:a,change:S.shape.change,timing:S.shape.timing,proration:S.shape.proration,offerRefs:ae}),e.strictObject({...w,action:e.literal("refund"),currency:q,merchantInvoiceId:a,mode:P.shape.mode,amountMinor:P.shape.amountMinor,entitlementAction:P.shape.entitlementAction}).refine(re,"Only a partial refund chooses amountMinor")]),ht=e.strictObject({request:D,requestedAt:b,preparationAllowed:e.boolean()}).refine(t=>!t.preparationAllowed||Date.parse(t.requestedAt)<Date.parse(t.request.expiresAt),"Preparation authority must be within its original validity"),Be=e.strictObject({merchantLineId:a,merchantPriceId:a.nullable(),quantity:l.refine(t=>/[1-9]/.test(t)),subtotalMinor:C,discountMinor:f,taxMinor:f.nullable(),totalMinor:C.nullable()}).refine(t=>t.taxMinor===null==(t.totalMinor===null)&&(t.totalMinor===null||t.totalMinor===t.subtotalMinor-t.discountMinor+t.taxMinor),"A quote line retains exact known totals; unknown tax is not zero"),Ee=e.strictObject({items:e.array(e.strictObject({merchantPriceId:a,quantity:l.refine(t=>/[1-9]/.test(t)),interval:m.shape.interval.exclude(["one_off"]),intervalCount:m.shape.intervalCount,amountMinor:m.shape.totalMinor,amountAfterOfferMinor:m.shape.totalMinor.optional()})).min(1).max(100),trial:z.nullable(),discount:I.nullable().optional(),discountExpiresAt:b.nullable().optional(),initialAmountMinor:m.shape.totalMinor.optional()}),ce=e.strictObject({request:D,requestDigest:j,merchantQuoteId:a,quoteTermsDigest:j,termsVersion:a,sourceRevisions:e.array(e.strictObject({reference:a,revision:a})).max(100),observedAt:b,expiresAt:b,currency:q,automaticTax:e.boolean(),lines:e.array(Be).max(100),subscriptionTerms:Ee.nullable(),subtotalMinor:C,discountMinor:f,nativeDiscountMinor:f.optional(),discount:I.nullable().optional(),taxMinor:f.nullable(),totalMinor:C.nullable(),effectiveAt:b.nullable(),expectedEffects:e.array(e.strictObject({reference:a,kind:e.enum(["grant","revoke","change"]),description:e.string().min(1).max(1e3),quantity:l.nullable(),unit:a.nullable()}).refine(t=>t.quantity===null==(t.unit===null),"Quantified effects name their native unit")).max(100),requiredConsents:e.array(e.strictObject({reference:a,version:a,summary:e.string().min(1).max(1e3)})).max(20)}),U=ce.superRefine((t,n)=>{let{quoteTermsDigest:r,...u}=t,h=t.lines.every(s=>s.taxMinor!==null),A=t.request.action==="purchase"&&t.request.mode==="subscription"!=(t.subscriptionTerms!==null),be=t.subscriptionTerms!==null&&(t.request.action==="refund"||t.request.action==="subscription_change"&&t.request.change.type==="cancel");(t.requestDigest!==x(t.request)||t.quoteTermsDigest!==x(u)||t.currency!==t.request.currency||A||be||t.lines.length===0&&(t.request.action!=="subscription_change"||t.subtotalMinor!==0||t.discountMinor!==0||t.taxMinor!==0||t.totalMinor!==0)||Date.parse(t.observedAt)>=Date.parse(t.expiresAt)||Date.parse(t.expiresAt)>Date.parse(t.request.expiresAt)||new Set(t.lines.map(s=>s.merchantLineId)).size!==t.lines.length||new Set(t.sourceRevisions.map(s=>s.reference)).size!==t.sourceRevisions.length||new Set(t.requiredConsents.map(s=>s.reference)).size!==t.requiredConsents.length||t.subtotalMinor!==t.lines.reduce((s,g)=>s+g.subtotalMinor,0)||t.discountMinor!==t.lines.reduce((s,g)=>s+g.discountMinor,0)||t.taxMinor!==null!==h||!h&&!t.automaticTax||t.taxMinor===null!=(t.totalMinor===null)||h&&(t.taxMinor!==t.lines.reduce((s,g)=>s+g.taxMinor,0)||t.totalMinor!==t.subtotalMinor-t.discountMinor+t.taxMinor)||t.request.action!=="subscription_change"&&(t.subtotalMinor<0||t.totalMinor!==null&&t.totalMinor<0)||t.request.action==="refund"&&(t.taxMinor===null||t.totalMinor===null||t.totalMinor<=0||t.request.mode==="partial"&&t.totalMinor!==t.request.amountMinor))&&n.addIssue({code:"custom",message:"Merchant terms must retain the original selection, scope, validity, digest and totals"})});function bt(t,n,r,u){return t.request.operationId===n&&t.request.action===r&&t.currency===u}function ft(t){return x(D.parse(t))}function gt(t){return x(ce.omit({quoteTermsDigest:!0}).parse(t))}var Te=e.strictObject({quoteTermsDigest:j,consents:e.array(e.strictObject({reference:a,version:a})).max(20)});function xt(t){return{quoteTermsDigest:t.quoteTermsDigest,consents:t.requiredConsents.map(({reference:n,version:r})=>({reference:n,version:r}))}}var ke=Te.extend({operationId:e.uuid()}).refine(t=>new Set(t.consents.map(n=>n.reference)).size===t.consents.length);function yt(t,n){let r=U.parse(t),u=ke.parse(n);return u.operationId===r.request.operationId&&u.quoteTermsDigest===r.quoteTermsDigest&&u.consents.length===r.requiredConsents.length&&r.requiredConsents.every(h=>u.consents.some(A=>A.reference===h.reference&&A.version===h.version))}var M=3,Ot="/integrations/indiana",vt="X-Indiana-Merchant-Bridge-Version",Re=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],ze=e.enum(Re),At={session:{command:"session.create",authority:"merchant_user"},catalog:{command:"catalog.read",authority:"merchant_catalog_reader"},customer_commerce:{command:"customer.commerce.read",authority:"merchant_user"},presentation:{command:"presentation.resolve",authority:"merchant_user"},presentation_events:{command:"presentation.report",authority:"merchant_user"},purchases:{command:"purchase.execute",authority:"merchant_user"},operation_status:{command:"operation.read",authority:"merchant_user"},billing_records:{command:null,authority:"indiana_server_key"},subscription_changes:{command:"subscription.change",authority:"merchant_user"},refunds:{command:"refund.execute",authority:"merchant_refund_authority"}},$=e.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),ue=e.string().regex(/^[A-Za-z0-9_-]{1,64}$/),we=e.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(t=>"AEIMQUYcgkosw048".includes(t.at(-1)),"Use canonical base64url for a 32-byte key"),De=e.strictObject({keyId:ue,signingSecret:we}),Ue=e.string().max(300).superRefine((t,n)=>{try{let r=new URL(t);if(r.protocol!=="https:"||r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.port&&r.port!=="443"||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(r.hostname)||/(?:^|\.)(?:localhost|local|internal)$/.test(r.hostname))throw new Error("invalid origin")}catch{n.addIssue({code:"custom",message:"Use an exact public HTTPS origin"})}}).transform(t=>new URL(t).origin),me=e.array(ze).max(10).refine(t=>new Set(t).size===t.length,"Capabilities must be unique"),V=e.strictObject({bridgeVersion:e.literal(M),projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),capabilities:me,catalog:e.enum(["endpoint","static","none"]),billingEvents:e.array(W).max(7),profiles:e.array(K).max(32).refine(t=>new Set(t).size===t.length,"Profiles must be unique")}).superRefine((t,n)=>{let r=u=>t.capabilities.includes(u);r("catalog")!==(t.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(r("billing_records")!==t.billingEvents.length>0||new Set(t.billingEvents).size!==t.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare the unique supported billing events"})}),de=e.strictObject({origin:Ue,requiredCapabilities:me}),$e=e.strictObject({revision:e.number().int().nonnegative(),checkedAt:e.iso.datetime(),outcome:e.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:e.strictObject({ping:e.enum(["passed","failed","not_checked"]),authentication:e.enum(["passed","failed","not_checked"]),catalog:e.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:V.nullable()}).superRefine((t,n)=>{t.outcome==="valid"!=(t.manifest!==null)&&n.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),jt=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),execution:e.enum(["indiana","record_only"]),accountId:e.string().nullable(),revision:e.number().int().nonnegative(),authentication:e.strictObject({keyId:ue}).nullable(),secretStoreConfigured:e.boolean().optional(),connection:de.nullable(),check:$e.nullable()});var se=e.strictObject({projectId:e.uuid(),environmentId:e.uuid()}),Pt=e.discriminatedUnion("action",[se.extend({action:e.literal("save"),revision:e.number().int().nonnegative(),connection:de,authentication:De.optional()}),se.extend({action:e.literal("check"),revision:e.number().int().nonnegative()})]),_=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"])});function qt(t){return e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:$,scope:_,data:t})}var le=e.strictObject({nativeUserId:e.string().min(1).max(128),session:Z.strict()}),pe=e.strictObject({nativeUserId:e.string().min(1).max(128),presentation:e.strictObject({customerId:e.uuid(),decisionId:e.uuid(),offeringVersionId:e.uuid(),paywallVersionId:e.uuid(),variant:e.string().min(1).max(128)}).nullable()}),he=e.strictObject({decisionId:e.uuid(),eventId:e.uuid()}),O=e.strictObject({operationId:e.uuid(),customerId:e.uuid()}),Ct=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:e.string().min(1).max(64),scope:_,error:e.strictObject({code:e.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:e.string().min(1).max(500),retryable:e.boolean(),recovery:e.string().min(1).max(80)})});var zt=e.strictObject({scope:_,operationId:e.uuid(),customerId:e.uuid(),confirmedAt:e.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:e.boolean(),instruction:Y,merchantTerms:U.optional()}).refine(t=>t.operationId===t.instruction.operationId&&t.customerId===t.instruction.customerId&&(!t.merchantTerms||t.merchantTerms.request.operationId===t.operationId&&t.merchantTerms.request.subject.customerId===t.customerId&&t.merchantTerms.request.action===t.instruction.type&&t.merchantTerms.currency===t.instruction.currency&&Object.entries(t.scope).every(([n,r])=>t.merchantTerms.request.subject.scope[n]===r)),"Authority must refer to the original Customer and operation"),N=T,d=e.string().min(1).max(120),Ve=e.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),Ne=e.strictObject({revision:d,updatedAt:e.iso.datetime(),provider:e.literal("merchant"),items:e.array(e.strictObject({merchantProductId:d,productVersionId:e.uuid(),name:e.string().min(1).max(255),kind:e.enum(["subscription","credit_pack"]),merchantPriceId:d,currency:e.string().regex(/^[a-z]{3}$/),amountMinor:e.number().int().nonnegative().max(1e8),interval:e.enum(["one_time","month","year"]),intervalCount:e.literal(1),includedCredits:e.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:e.enum(["none","month"]),creditPolicyId:d,available:e.boolean()}).superRefine((t,n)=>{(t.kind==="credit_pack"&&(t.interval!=="one_time"||t.creditReset!=="none")||t.kind==="subscription"&&t.interval==="one_time"||t.available&&t.amountMinor===0)&&n.addIssue({code:"custom",message:"Unsupported version 1 catalog terms"})})).max(500)}),Le=e.strictObject({customerId:e.uuid(),revision:e.string().min(1).max(128),observedAt:e.iso.datetime(),subscriptions:e.array(e.strictObject({merchantSubscriptionId:d,merchantProductId:d,productVersionId:e.uuid().nullable(),status:e.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:e.iso.datetime().nullable(),currentPeriodEndsAt:e.iso.datetime().nullable(),cancelAtPeriodEnd:e.boolean(),scheduledChange:e.strictObject({effectiveAt:e.iso.datetime(),merchantProductId:d}).nullable()})).max(100),purchaseHistory:e.strictObject({complete:e.boolean(),hasPaidPurchase:e.boolean(),lastPaidAt:e.iso.datetime().nullable()}),balances:e.array(e.strictObject({bucketId:d,key:d,available:Ve,expiresAt:e.iso.datetime().nullable(),nextResetAt:e.iso.datetime().nullable()})).max(100)}),v=e.strictObject({}),Fe={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":v,"session.create":v,"catalog.read":v,"customer.commerce.read":v,"presentation.resolve":v,"presentation.report":he,"purchase.execute":O,"operation.read":O,"subscription.change":O,"refund.execute":O},wt={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":V,"session.create":le,"catalog.read":Ne,"customer.commerce.read":Le,"presentation.resolve":pe,"presentation.report":e.strictObject({queued:e.literal(!0)}),"purchase.execute":N,"operation.read":ee,"subscription.change":N,"refund.execute":N},Dt=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),scope:_,command:$,data:e.unknown()}).superRefine((t,n)=>{Fe[t.command].safeParse(t.data).success||n.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});export{ge as a,S as b,xe as c,We as d,Xe as e,ye as f,T as g,ee as h,p as i,Je as j,z as k,qe as l,ne as m,re as n,P as o,ht as p,U as q,bt as r,ft as s,gt as t,Te as u,xt as v,yt as w,M as x,Ot as y,vt as z,Re as A,At as B,De as C,Ue as D,V as E,_ as F,qt as G,le as H,pe as I,he as J,O as K,Ct as L,zt as M,N,Le as O,Fe as P,wt as Q,Dt as R};
|
|
1
|
+
import{a as G}from"./chunk-QONPVFRV.js";import{b as Z}from"./chunk-QE6T6NX6.js";import{a as j,b as Q,c as x}from"./chunk-P3PXFIMG.js";import{a as L,b as F,c as H,j as l}from"./chunk-W5KG2IWX.js";import{b as e}from"./chunk-Z43N7U4U.js";var fe=["purchase.subscription","purchase.one_time","purchase.prepaid","purchase.trial","purchase.seats","purchase.tiered","tax.automatic","discount.percent.once","discount.percent.repeating","discount.percent.forever","discount.amount.once","discount.amount.repeating","discount.amount.forever","subscription.cancel.immediate","subscription.cancel.renewal","subscription.resume","subscription.plan.immediate","subscription.plan.renewal","subscription.seats","subscription.quantity","subscription.billing_cycle","subscription.proration","refund.full","refund.partial","refund.revoke"],K=e.enum(fe),W=e.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","subscription.change.closed","invoice.paid","refund.updated"]);var o=e.string().min(1).max(200),c=e.iso.datetime({offset:!0}),i=e.number().int().nonnegative().max(1e8),y=e.string().regex(/^[A-Z]{3}$/),m=e.strictObject({priceId:e.uuid(),productVersionId:e.uuid(),productId:o,quantity:e.number().int().min(1).max(1e6),unitAmountMinor:i,totalMinor:i,interval:e.enum(["week","month","year","one_off"]),intervalCount:e.number().int().min(1).max(52),kind:e.enum(["fixed","prepaid","seat"]),tiers:e.strictObject({mode:e.enum(["graduated","volume"]),tiers:e.array(e.strictObject({upTo:e.number().int().positive().nullable(),unitAmountMinor:i,flatAmountMinor:i.optional()})).min(2).max(12)}).nullable()}),I=e.strictObject({grantId:e.uuid(),couponId:e.uuid(),amountMinor:i,applicationPolicy:G.optional(),applicableProductIds:e.array(o).min(1).max(100).optional(),terms:e.discriminatedUnion("type",[e.strictObject({type:e.literal("percent"),percentOff:e.number().gt(0).max(100)}),e.strictObject({type:e.literal("amount"),amountOffMinor:i,currency:y})]),duration:e.discriminatedUnion("type",[e.strictObject({type:e.literal("once")}),e.strictObject({type:e.literal("forever")}),e.strictObject({type:e.literal("repeating"),months:e.number().int().min(1).max(36)})])}),E={provider:e.literal("merchant"),executor:e.literal("merchant"),operationId:e.uuid(),customerId:e.uuid(),configurationRevision:e.number().int().nonnegative(),connectionRevision:e.number().int().nonnegative(),currency:y,expiresAt:c},ge=e.strictObject({...E,type:e.literal("purchase"),mode:e.enum(["payment","subscription"]),lineItems:e.array(m).min(1).max(100),catalogAmountMinor:i,nativeDiscountMinor:i.optional(),discount:I.nullable(),trialPeriodDays:e.number().int().min(1).max(730).nullable(),automaticTax:e.boolean()}).refine(t=>t.lineItems.reduce((n,r)=>n+r.totalMinor,0)===t.catalogAmountMinor&&(t.discount?.amountMinor??0)+(t.nativeDiscountMinor??0)<=t.catalogAmountMinor&&new Set(t.lineItems.map(n=>n.priceId)).size===t.lineItems.length,"Purchase lines must retain the original total and unique Price identities"),S=e.strictObject({...E,type:e.literal("subscription_change"),subscriptionId:e.uuid(),merchantSubscriptionId:o,membershipId:e.uuid(),subscriptionAction:e.enum(["update","cancel","schedule","release"]),supersedesOperationId:e.uuid().nullable(),change:e.discriminatedUnion("type",[e.strictObject({type:e.literal("cancel")}),e.strictObject({type:e.literal("uncancel")}),e.strictObject({type:e.literal("plan"),productVersionId:e.uuid()}),e.strictObject({type:e.literal("seats"),licenseKey:o,quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("quantity"),internal_feature_id:e.uuid(),quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("billing_cycle"),billingCycleAnchor:e.union([e.literal("now"),e.number().int().positive()])})]),timing:e.enum(["immediate","renewal"]),effectiveAt:c,creditMinor:i,debitMinor:i,totalMinor:i,discountMinor:i,discount:I.nullable().optional(),taxMinor:i,proration:e.enum(["none","create_prorations","always_invoice"]),lineItems:e.array(m.extend({quantity:e.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:e.array(e.uuid()).max(100),sourceLineItems:e.array(m).min(1).max(100).optional()}),xe=e.strictObject({...E,type:e.literal("refund"),invoiceId:e.uuid(),merchantInvoiceId:o,amountMinor:i.refine(t=>t>0),mode:e.enum(["full","partial"]),entitlementAction:e.enum(["retain","revoke"]),cancelSubscriptions:e.array(o).max(100)}),Y=e.discriminatedUnion("type",[ge,S,xe]);function We(t){let n=new Set;if(t.type==="purchase")n.add(t.mode==="subscription"?"purchase.subscription":"purchase.one_time"),t.lineItems.some(r=>r.kind==="prepaid")&&n.add("purchase.prepaid"),t.lineItems.some(r=>r.kind==="seat")&&n.add("purchase.seats"),t.lineItems.some(r=>r.tiers!==null)&&n.add("purchase.tiered"),t.trialPeriodDays!==null&&n.add("purchase.trial"),t.automaticTax&&n.add("tax.automatic"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`);else if(t.type==="refund")n.add(`refund.${t.mode}`),t.entitlementAction==="revoke"&&n.add("refund.revoke");else{let r=t.change.type;r==="cancel"?n.add(`subscription.cancel.${t.timing}`):r==="uncancel"?n.add("subscription.resume"):r==="plan"?n.add(`subscription.plan.${t.timing}`):n.add(`subscription.${r}`),t.proration!=="none"&&n.add("subscription.proration"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`)}return[...n].sort()}function Xe(t){return t.type==="purchase"?t.mode==="subscription"?["purchase.completed","purchase.closed","subscription.observed","invoice.paid"]:["purchase.completed","purchase.closed"]:t.type==="subscription_change"?["subscription.change.completed","subscription.change.closed","subscription.observed",...t.change.type==="cancel"||t.change.type==="uncancel"?[]:["invoice.paid"]]:["refund.updated",...t.entitlementAction==="revoke"&&t.cancelSubscriptions.length?["subscription.observed"]:[]]}var ye=e.strictObject({phase:e.enum(["execution","payment","fulfillment","recording"]),code:L,reason:H.optional(),recovery:F,retryable:e.boolean()}).refine(t=>t.reason!=="RESULT_UNKNOWN"||!t.retryable&&t.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Ie=e.strictObject({type:e.literal("redirect"),url:e.url().startsWith("https://"),expiresAt:c}),B={operationId:e.uuid(),customerId:e.uuid(),merchantExecutionId:o,fulfillmentStatus:e.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:e.enum(["not_ready","pending","accepted","failed"]),updatedAt:c,problem:ye.nullable(),pollAfterMs:e.number().int().min(1e3).max(6e4).nullable()},T=e.discriminatedUnion("type",[e.strictObject({...B,type:e.literal("purchase"),merchantOrderId:o.nullable(),paymentStatus:e.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:e.url().refine(t=>new URL(t).protocol==="https:").nullable(),checkoutExpiresAt:c.nullable()}).refine(t=>!t.checkoutUrl||["not_started","pending"].includes(t.paymentStatus)&&t.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),e.strictObject({...B,type:e.literal("subscription_change"),status:e.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:o,scheduledFor:c.nullable(),nextAction:Ie.optional()}).refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"A scheduled change retains its future effective time"),e.strictObject({...B,type:e.literal("refund"),status:e.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:o.nullable()}).refine(t=>t.status!=="succeeded"||t.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),ee=e.discriminatedUnion("lookup",[e.strictObject({lookup:e.literal("found"),operationId:e.uuid(),customerId:e.uuid(),execution:T,readAt:c}),e.strictObject({lookup:e.literal("not_received"),operationId:e.uuid(),customerId:e.uuid(),execution:e.null(),readAt:c})]).refine(t=>!t.execution||t.execution.operationId===t.operationId&&t.execution.customerId===t.customerId,"Lookup must retain the original Customer and operation"),te=e.strictObject({merchantPriceId:o,productId:o,kind:e.enum(["fixed","prepaid"]),currency:y,unitAmountMinor:i,interval:e.enum(["one_off","day","week","month","year"]),intervalCount:e.number().int().min(1).max(100)}),X={merchantItemId:o,quantity:e.number().int().positive().max(1e6)},Se=t=>t.priceId??JSON.stringify(t.nativePrice),k=e.strictObject({merchantSubscriptionId:o,revision:e.number().int().positive(),status:e.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:c,periodEndsAt:c,cancelAtPeriodEnd:e.boolean(),hasDiscounts:e.boolean(),items:e.array(e.union([e.strictObject({...X,priceId:e.uuid()}),e.strictObject({...X,nativePrice:te})])).min(1).max(100)}).refine(t=>Date.parse(t.periodEndsAt)>Date.parse(t.periodStartsAt)&&new Set(t.items.map(Se)).size===t.items.length&&new Set(t.items.map(n=>n.merchantItemId)).size===t.items.length,"Subscription periods and Price identities must be unambiguous"),J={merchantLineId:o,quantity:e.number().int().nonnegative().max(1e6),subtotalMinor:e.number().int().min(-1e8).max(1e8),discountMinor:i,taxMinor:i,totalMinor:e.number().int().min(-1e8).max(2e8),periodStartsAt:c.nullable(),periodEndsAt:c.nullable()},R=e.strictObject({merchantInvoiceId:o,reason:e.enum(["renewal","adjustment"]).optional(),currency:y,subtotalMinor:i,discountMinor:i,taxMinor:i,totalMinor:i,paidMinor:i,periodStartsAt:c.nullable(),periodEndsAt:c.nullable(),lines:e.array(e.union([e.strictObject({...J,priceId:e.uuid()}),e.strictObject({...J,nativePrice:te})]).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&(t.subtotalMinor<0?t.discountMinor===0&&t.taxMinor===0:t.discountMinor<=t.subtotalMinor),"Invoice line amounts must retain the complete debit or credit")).min(1).max(100)}).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&t.discountMinor<=t.subtotalMinor&&t.paidMinor===t.totalMinor&&new Set(t.lines.map(n=>n.merchantLineId)).size===t.lines.length&&t.lines.reduce((n,r)=>n+r.subtotalMinor,0)===t.subtotalMinor&&t.lines.reduce((n,r)=>n+r.discountMinor,0)===t.discountMinor&&t.lines.reduce((n,r)=>n+r.taxMinor,0)===t.taxMinor&&t.lines.reduce((n,r)=>n+r.totalMinor,0)===t.totalMinor,"A paid Invoice retains the complete financial amounts"),p={eventId:e.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:e.uuid(),occurredAt:c},Me=e.strictObject({...p,type:e.literal("purchase.completed"),operationId:e.uuid(),merchantOrderId:o,paymentStatus:e.enum(["paid","trialing","no_payment_required"]),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable(),subscription:k.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),_e=e.strictObject({...p,type:e.literal("purchase.closed"),operationId:e.uuid(),status:e.enum(["failed","expired","canceled"])}),Oe=e.strictObject({...p,type:e.literal("subscription.observed"),operationId:e.uuid().nullable(),subscription:k}),ve=e.strictObject({...p,type:e.literal("subscription.change.completed"),operationId:e.uuid(),status:e.enum(["scheduled","applied"]),scheduledFor:c.nullable(),subscription:k.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities"),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),Ae=e.strictObject({...p,type:e.literal("subscription.change.closed"),operationId:e.uuid(),merchantSubscriptionId:o,merchantInvoiceId:o.nullable(),status:e.enum(["failed","expired","canceled"])}),je=e.strictObject({...p,type:e.literal("invoice.paid"),merchantSubscriptionId:o.nullable(),invoice:R}),Pe=e.strictObject({...p,type:e.literal("refund.updated"),operationId:e.uuid().nullable(),merchantInvoiceId:o.optional(),merchantRefundId:o,status:e.enum(["pending","succeeded","failed"]),amountMinor:i.refine(t=>t>0),currency:y}),Je=[Me.refine(t=>t.paymentStatus!=="paid"||t.invoice!==null,"A paid purchase includes its Invoice"),_e,Oe.refine(t=>t.operationId===null||t.subscription.items.every(n=>"priceId"in n),"Native Price references cannot replace an operation's quoted Prices"),ve.refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),Ae,je,Pe.refine(t=>t.operationId!==null||t.merchantInvoiceId!==void 0,"A native refund names its Invoice")];var z=e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}),rt=e.object({...z.shape,featureAllowances:e.record(e.uuid(),e.number().int().min(0).max(1e9)),creditAmounts:e.record(e.uuid(),l)}).strict(),it=e.object({id:e.uuid(),planVersionId:e.uuid(),slot:e.string(),cardRequired:e.boolean(),status:e.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),createdAt:e.iso.datetime()}).strict();var qe=e.number().int().positive().max(2e8),ne=e.number().int().min(0).max(2e8),re=t=>t.mode==="partial"==(t.amountMinor!==void 0),P=e.strictObject({mode:e.enum(["full","partial"]),amountMinor:qe.optional(),entitlementAction:e.enum(["retain","revoke"])});var a=e.string().min(1).max(200),b=e.iso.datetime({offset:!0}),f=ne,ie=f.maxValue,C=e.number().int().min(-ie).max(ie),q=e.string().regex(/^[A-Z]{3}$/),oe=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),ae=e.array(a).max(100).refine(t=>new Set(t).size===t.length),Ce=e.strictObject({merchantProductId:a,merchantPriceId:a,productVersionId:e.uuid().optional(),quantity:l.refine(t=>/[1-9]/.test(t))}),w={subject:Q,operationId:e.uuid(),configurationRevision:oe,connectionRevision:oe,expiresAt:b},D=e.discriminatedUnion("action",[e.strictObject({...w,action:e.literal("purchase"),mode:e.enum(["payment","subscription"]),currency:q,items:e.array(Ce).min(1).max(100),offerRefs:ae}),e.strictObject({...w,action:e.literal("subscription_change"),currency:q,merchantSubscriptionId:a,change:S.shape.change,timing:S.shape.timing,proration:S.shape.proration,offerRefs:ae}),e.strictObject({...w,action:e.literal("refund"),currency:q,merchantInvoiceId:a,mode:P.shape.mode,amountMinor:P.shape.amountMinor,entitlementAction:P.shape.entitlementAction}).refine(re,"Only a partial refund chooses amountMinor")]),ht=e.strictObject({request:D,requestedAt:b,preparationAllowed:e.boolean()}).refine(t=>!t.preparationAllowed||Date.parse(t.requestedAt)<Date.parse(t.request.expiresAt),"Preparation authority must be within its original validity"),Be=e.strictObject({merchantLineId:a,merchantPriceId:a.nullable(),quantity:l.refine(t=>/[1-9]/.test(t)),subtotalMinor:C,discountMinor:f,taxMinor:f.nullable(),totalMinor:C.nullable()}).refine(t=>t.taxMinor===null==(t.totalMinor===null)&&(t.totalMinor===null||t.totalMinor===t.subtotalMinor-t.discountMinor+t.taxMinor),"A quote line retains exact known totals; unknown tax is not zero"),Ee=e.strictObject({items:e.array(e.strictObject({merchantPriceId:a,quantity:l.refine(t=>/[1-9]/.test(t)),interval:m.shape.interval.exclude(["one_off"]),intervalCount:m.shape.intervalCount,amountMinor:m.shape.totalMinor,amountAfterOfferMinor:m.shape.totalMinor.optional()})).min(1).max(100),trial:z.nullable(),discount:I.nullable().optional(),discountExpiresAt:b.nullable().optional(),initialAmountMinor:m.shape.totalMinor.optional()}),ce=e.strictObject({request:D,requestDigest:j,merchantQuoteId:a,quoteTermsDigest:j,termsVersion:a,sourceRevisions:e.array(e.strictObject({reference:a,revision:a})).max(100),observedAt:b,expiresAt:b,currency:q,automaticTax:e.boolean(),lines:e.array(Be).max(100),subscriptionTerms:Ee.nullable(),subtotalMinor:C,discountMinor:f,nativeDiscountMinor:f.optional(),discount:I.nullable().optional(),taxMinor:f.nullable(),totalMinor:C.nullable(),effectiveAt:b.nullable(),expectedEffects:e.array(e.strictObject({reference:a,kind:e.enum(["grant","revoke","change"]),description:e.string().min(1).max(1e3),quantity:l.nullable(),unit:a.nullable()}).refine(t=>t.quantity===null==(t.unit===null),"Quantified effects name their native unit")).max(100),requiredConsents:e.array(e.strictObject({reference:a,version:a,summary:e.string().min(1).max(1e3)})).max(20)}),U=ce.superRefine((t,n)=>{let{quoteTermsDigest:r,...u}=t,h=t.lines.every(s=>s.taxMinor!==null),A=t.request.action==="purchase"&&t.request.mode==="subscription"!=(t.subscriptionTerms!==null),be=t.subscriptionTerms!==null&&(t.request.action==="refund"||t.request.action==="subscription_change"&&t.request.change.type==="cancel");(t.requestDigest!==x(t.request)||t.quoteTermsDigest!==x(u)||t.currency!==t.request.currency||A||be||t.lines.length===0&&(t.request.action!=="subscription_change"||t.subtotalMinor!==0||t.discountMinor!==0||t.taxMinor!==0||t.totalMinor!==0)||Date.parse(t.observedAt)>=Date.parse(t.expiresAt)||Date.parse(t.expiresAt)>Date.parse(t.request.expiresAt)||new Set(t.lines.map(s=>s.merchantLineId)).size!==t.lines.length||new Set(t.sourceRevisions.map(s=>s.reference)).size!==t.sourceRevisions.length||new Set(t.requiredConsents.map(s=>s.reference)).size!==t.requiredConsents.length||t.subtotalMinor!==t.lines.reduce((s,g)=>s+g.subtotalMinor,0)||t.discountMinor!==t.lines.reduce((s,g)=>s+g.discountMinor,0)||t.taxMinor!==null!==h||!h&&!t.automaticTax||t.taxMinor===null!=(t.totalMinor===null)||h&&(t.taxMinor!==t.lines.reduce((s,g)=>s+g.taxMinor,0)||t.totalMinor!==t.subtotalMinor-t.discountMinor+t.taxMinor)||t.request.action!=="subscription_change"&&(t.subtotalMinor<0||t.totalMinor!==null&&t.totalMinor<0)||t.request.action==="refund"&&(t.taxMinor===null||t.totalMinor===null||t.totalMinor<=0||t.request.mode==="partial"&&t.totalMinor!==t.request.amountMinor))&&n.addIssue({code:"custom",message:"Merchant terms must retain the original selection, scope, validity, digest and totals"})});function bt(t,n,r,u){return t.request.operationId===n&&t.request.action===r&&t.currency===u}function ft(t){return x(D.parse(t))}function gt(t){return x(ce.omit({quoteTermsDigest:!0}).parse(t))}var Te=e.strictObject({quoteTermsDigest:j,consents:e.array(e.strictObject({reference:a,version:a})).max(20)});function xt(t){return{quoteTermsDigest:t.quoteTermsDigest,consents:t.requiredConsents.map(({reference:n,version:r})=>({reference:n,version:r}))}}var ke=Te.extend({operationId:e.uuid()}).refine(t=>new Set(t.consents.map(n=>n.reference)).size===t.consents.length);function yt(t,n){let r=U.parse(t),u=ke.parse(n);return u.operationId===r.request.operationId&&u.quoteTermsDigest===r.quoteTermsDigest&&u.consents.length===r.requiredConsents.length&&r.requiredConsents.every(h=>u.consents.some(A=>A.reference===h.reference&&A.version===h.version))}var M=3,Ot="/integrations/indiana",vt="X-Indiana-Merchant-Bridge-Version",Re=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],ze=e.enum(Re),At={session:{command:"session.create",authority:"merchant_user"},catalog:{command:"catalog.read",authority:"merchant_catalog_reader"},customer_commerce:{command:"customer.commerce.read",authority:"merchant_user"},presentation:{command:"presentation.resolve",authority:"merchant_user"},presentation_events:{command:"presentation.report",authority:"merchant_user"},purchases:{command:"purchase.execute",authority:"merchant_user"},operation_status:{command:"operation.read",authority:"merchant_user"},billing_records:{command:null,authority:"indiana_server_key"},subscription_changes:{command:"subscription.change",authority:"merchant_user"},refunds:{command:"refund.execute",authority:"merchant_refund_authority"}},$=e.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),ue=e.string().regex(/^[A-Za-z0-9_-]{1,64}$/),we=e.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(t=>"AEIMQUYcgkosw048".includes(t.at(-1)),"Use canonical base64url for a 32-byte key"),De=e.strictObject({keyId:ue,signingSecret:we}),Ue=e.string().max(300).superRefine((t,n)=>{try{let r=new URL(t);if(r.protocol!=="https:"||r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.port&&r.port!=="443"||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(r.hostname)||/(?:^|\.)(?:localhost|local|internal)$/.test(r.hostname))throw new Error("invalid origin")}catch{n.addIssue({code:"custom",message:"Use an exact public HTTPS origin"})}}).transform(t=>new URL(t).origin),me=e.array(ze).max(10).refine(t=>new Set(t).size===t.length,"Capabilities must be unique"),V=e.strictObject({bridgeVersion:e.literal(M),projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),capabilities:me,catalog:e.enum(["endpoint","static","none"]),billingEvents:e.array(W).max(7),profiles:e.array(K).max(32).refine(t=>new Set(t).size===t.length,"Profiles must be unique")}).superRefine((t,n)=>{let r=u=>t.capabilities.includes(u);r("catalog")!==(t.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(r("billing_records")!==t.billingEvents.length>0||new Set(t.billingEvents).size!==t.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare the unique supported billing events"})}),de=e.strictObject({origin:Ue,requiredCapabilities:me}),$e=e.strictObject({revision:e.number().int().nonnegative(),checkedAt:e.iso.datetime(),outcome:e.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:e.strictObject({ping:e.enum(["passed","failed","not_checked"]),authentication:e.enum(["passed","failed","not_checked"]),catalog:e.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:V.nullable()}).superRefine((t,n)=>{t.outcome==="valid"!=(t.manifest!==null)&&n.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),jt=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),execution:e.enum(["indiana","record_only"]),accountId:e.string().nullable(),revision:e.number().int().nonnegative(),authentication:e.strictObject({keyId:ue}).nullable(),secretStoreConfigured:e.boolean().optional(),connection:de.nullable(),check:$e.nullable()});var se=e.strictObject({projectId:e.uuid(),environmentId:e.uuid()}),Pt=e.discriminatedUnion("action",[se.extend({action:e.literal("save"),revision:e.number().int().nonnegative(),connection:de,authentication:De.optional()}),se.extend({action:e.literal("check"),revision:e.number().int().nonnegative()})]),_=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"])});function qt(t){return e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:$,scope:_,data:t})}var le=e.strictObject({nativeUserId:e.string().min(1).max(128),session:Z.strict()}),pe=e.strictObject({nativeUserId:e.string().min(1).max(128),presentation:e.strictObject({customerId:e.uuid(),decisionId:e.uuid(),offeringVersionId:e.uuid(),paywallVersionId:e.uuid(),variant:e.string().min(1).max(128)}).nullable()}),he=e.strictObject({decisionId:e.uuid(),eventId:e.uuid()}),O=e.strictObject({operationId:e.uuid(),customerId:e.uuid()}),Ct=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:e.string().min(1).max(64),scope:_,error:e.strictObject({code:e.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:e.string().min(1).max(500),retryable:e.boolean(),recovery:e.string().min(1).max(80)})});var zt=e.strictObject({scope:_,operationId:e.uuid(),customerId:e.uuid(),confirmedAt:e.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:e.boolean(),instruction:Y,merchantTerms:U.optional()}).refine(t=>t.operationId===t.instruction.operationId&&t.customerId===t.instruction.customerId&&(!t.merchantTerms||t.merchantTerms.request.operationId===t.operationId&&t.merchantTerms.request.subject.customerId===t.customerId&&t.merchantTerms.request.action===t.instruction.type&&t.merchantTerms.currency===t.instruction.currency&&Object.entries(t.scope).every(([n,r])=>t.merchantTerms.request.subject.scope[n]===r)),"Authority must refer to the original Customer and operation"),N=T,d=e.string().min(1).max(120),Ve=e.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),Ne=e.strictObject({revision:d,updatedAt:e.iso.datetime(),provider:e.literal("merchant"),items:e.array(e.strictObject({merchantProductId:d,productVersionId:e.uuid(),name:e.string().min(1).max(255),kind:e.enum(["subscription","credit_pack"]),merchantPriceId:d,currency:e.string().regex(/^[a-z]{3}$/),amountMinor:e.number().int().nonnegative().max(1e8),interval:e.enum(["one_time","month","year"]),intervalCount:e.literal(1),includedCredits:e.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:e.enum(["none","month"]),creditPolicyId:d,available:e.boolean()}).superRefine((t,n)=>{(t.kind==="credit_pack"&&(t.interval!=="one_time"||t.creditReset!=="none")||t.kind==="subscription"&&t.interval==="one_time"||t.available&&t.amountMinor===0)&&n.addIssue({code:"custom",message:"Unsupported version 1 catalog terms"})})).max(500)}),Le=e.strictObject({customerId:e.uuid(),revision:e.string().min(1).max(128),observedAt:e.iso.datetime(),subscriptions:e.array(e.strictObject({merchantSubscriptionId:d,merchantProductId:d,productVersionId:e.uuid().nullable(),status:e.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:e.iso.datetime().nullable(),currentPeriodEndsAt:e.iso.datetime().nullable(),cancelAtPeriodEnd:e.boolean(),scheduledChange:e.strictObject({effectiveAt:e.iso.datetime(),merchantProductId:d}).nullable()})).max(100),purchaseHistory:e.strictObject({complete:e.boolean(),hasPaidPurchase:e.boolean(),lastPaidAt:e.iso.datetime().nullable()}),balances:e.array(e.strictObject({bucketId:d,key:d,available:Ve,expiresAt:e.iso.datetime().nullable(),nextResetAt:e.iso.datetime().nullable()})).max(100)}),v=e.strictObject({}),Fe={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":v,"session.create":v,"catalog.read":v,"customer.commerce.read":v,"presentation.resolve":v,"presentation.report":he,"purchase.execute":O,"operation.read":O,"subscription.change":O,"refund.execute":O},wt={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":V,"session.create":le,"catalog.read":Ne,"customer.commerce.read":Le,"presentation.resolve":pe,"presentation.report":e.strictObject({queued:e.literal(!0)}),"purchase.execute":N,"operation.read":ee,"subscription.change":N,"refund.execute":N},Dt=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),scope:_,command:$,data:e.unknown()}).superRefine((t,n)=>{Fe[t.command].safeParse(t.data).success||n.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});export{ge as a,S as b,xe as c,We as d,Xe as e,ye as f,T as g,ee as h,p as i,Je as j,z as k,qe as l,ne as m,re as n,P as o,ht as p,U as q,bt as r,ft as s,gt as t,Te as u,xt as v,yt as w,M as x,Ot as y,vt as z,Re as A,At as B,De as C,Ue as D,V as E,_ as F,qt as G,le as H,pe as I,he as J,O as K,Ct as L,zt as M,N,Le as O,Fe as P,wt as Q,Dt as R};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as Ie}from"./chunk-WCKOWAIL.js";import{a as Q}from"./chunk-2TQEJ6GM.js";import{A as Se,E as z,G as Pe,d as pe,f as k,k as me,v as we,w as ge,y as ye}from"./chunk-D4CDG535.js";import{$ as N}from"./chunk-XZMM34BS.js";import{a as B,i as J}from"./chunk-26YREQNF.js";import{b as he}from"./chunk-MTKM26F7.js";import{a as c}from"./chunk-S4X6YX5D.js";import{h as G}from"./chunk-2ZPCWVFU.js";import{b as fe}from"./chunk-AEERSTTW.js";import{b as r}from"./chunk-ZGBSTK22.js";import{a as oe}from"./chunk-DSPLGTQI.js";var g=N.options,Ae=r.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}),me.omit({customerToken:!0})]),je=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),Me=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume"]),start:r.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:je}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.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(o=>!o.command||o.requestId===o.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:Ae})]),ae=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:k.shape.run.shape.status}),K={scope:G,customerId:r.uuid()},Ce=r.discriminatedUnion("outcome",[r.strictObject({...K,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...K,outcome:r.literal("resolved"),target:ae,view:k.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((o,d)=>{o.outcome==="resolved"&&(o.access.type==="customer"!=(o.view!==null)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Re=r.strictObject({...K,target:ae,view:k.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:k.shape.purchase.unwrap().nullable()}).superRefine((o,d)=>{let p=o.settlement;(p.acceptance==="accepted"!=(p.receiptPhase!==null)||p.acceptance==="accepted"&&p.basis!=="receipt"||p.acceptance==="unknown"&&(p.state!=="unknown"||p.basis!=="none")||p.acceptance!=="accepted"&&(p.operationId!==null||p.receiptId!==null)||p.acceptance==="not_accepted"&&(p.state!=="settled"||!["run_terminal","position_advanced"].includes(p.basis))||o.purchase&&(o.purchase.receiptId!==p.receiptId||o.purchase.operation&&o.purchase.operation.operationId!==p.operationId||o.purchase.quote&&o.purchase.quote.operationId!==p.operationId)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ee=r.strictObject({...K,target:ae,purchase:k.shape.purchase.unwrap()}).superRefine((o,d)=>{(!o.purchase.operation||typeof o.purchase.canReselect!="boolean"||o.purchase.quote&&o.purchase.quote.operationId!==o.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})});var Ne=N.options[0].refine(o=>!o.customer&&!o.customerData),ke=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),ve=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:G,customerId:r.uuid(),sessionId:r.uuid(),start:Ne,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:pe.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ke).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:we.nullable()})});function be(o){return ye({...o,namespace:"purchases",identity:[o.scope.projectId,o.scope.environment,o.customerId]})}function Oe(o){let d=new URL(o.baseUrl??fe).href,p=()=>new c("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function E(){o.assertCurrent();try{let y=await o.storage.read();if(o.assertCurrent(),!Number.isSafeInteger(y.revision)||y.revision<0)throw p();let a=y.entry===null?null:ve.parse(y.entry);if(a&&(a.baseUrl!==d||a.customerId!==o.customerId||a.scope.projectId!==o.scope.projectId||a.scope.environment!==o.scope.environment))throw new c("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(a?.journal.entry&&(a.journal.entry.scope.projectId!==a.scope.projectId||a.journal.entry.scope.environment!==a.scope.environment||a.journal.entry.funnelId!==a.start.funnelId||a.journal.entry.runId!==a.run?.id||a.journal.entry.versionId!==a.run?.versionId)||a?.operationCommand&&!a.purchases.some(R=>R.operationId===a.operationCommand?.operationId))throw p();return{revision:y.revision,entry:a}}catch(y){throw y instanceof c?y:p()}}async function Y(y){for(let a=0;a<8;a++){let R=await E(),b=y(structuredClone(R.entry));if(JSON.stringify(b)===JSON.stringify(R.entry))return b;b&&ve.parse(b),o.assertCurrent();let v;try{v=await o.storage.write(R.revision,b)}catch{throw p()}if(o.assertCurrent(),v!==null){if(!Number.isSafeInteger(v)||v<=R.revision)throw p();return b}}throw new c("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:E,update:Y,baseUrl:d}}function Te(o){let d=o.purchases.find(p=>p.type==="checkout");if(!o.actions.includes("continue_checkout")||d?.type!=="checkout")throw new c("PURCHASE_PENDING","No single resumable Checkout is confirmed");return d.checkoutUrl}function pn(o){let d={...o,scope:{...o.scope},executionPolicy:structuredClone(o.executionPolicy)},p=d.session.snapshot();if(!p)throw new c("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:E,sessionId:Y}=p,y=!1,a=null,R,b=null,v=!1,q,U,D,O={mode:"idle",status:"idle",actions:["start"],purchases:[]},I=new Map,j=new Map,ie=new AbortController,H=new Set,W=he(d),se=Ie(W.request);function L(e){return{code:e instanceof c?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof c&&e.status!==void 0?{status:e.status}:{}}}function P(){if(y||d.session.snapshot()?.customerId!==E)throw new c("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Oe({...d,customerId:E,assertCurrent:P,storage:d.storage??be({baseUrl:d.baseUrl,scope:d.scope,customerId:E})}),Fe=d.session.subscribeIdentity(ue);function ue(){y||(y=!0,clearTimeout(D),ie.abort(new c("IDENTITY_CHANGED","Purchase consumer was destroyed")),Fe(),a?.reset(),a=null,b=null,W.dispose(),H.clear(),I.clear(),j.clear())}function C(e){P();let n=JSON.stringify(e)!==JSON.stringify(O);O=e,clearTimeout(D),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(D=setTimeout(()=>{T().catch(()=>{})},5e3)),n&&oe(d.onRecovery,structuredClone(e));for(let t of n?H:[]){if(y)break;oe(t,structuredClone(e))}return structuredClone(e)}function h(e){if(P(),!e||e.start.requestId!==R)throw new c("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function F(e){let n=[...e.purchases],t=e.journal.entry?.purchase;return t&&!n.some(u=>u.operationId===t.operationId)&&n.push({receiptId:t.receiptId,operationId:t.operationId,terminal:null}),n}function M(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&F(e).every(n=>n.terminal!==null)}function _(e,n){let t=e.journal.entry?.command??e.journal.entry?.closeCommand,u=F(e).map(S=>{let re=I.get(S.operationId);return S.terminal&&!re?{type:S.terminal,operationId:S.operationId}:B({quote:re?.quote??null,operation:re??null,requestId:t?.requestId??null,pending:!1,destroyed:!1,canReselect:j.get(S.operationId)===!0})}),l=u.filter(S=>!["complete","native"].includes(S.type)),i=l[0],s=l.length===1&&i?.operationId?I.get(i.operationId):void 0;if(s&&(i?.type==="checkout"||i?.type==="cancel"))try{z({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote)}catch(S){return{mode:n,status:"blocked",actions:["refresh",...n==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:u,error:L(S)}}let m;if(n==="operation"&&!t&&i?.type==="cancel"&&s?.quote&&!s.problem&&!s.confirmedAt)try{z({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote),Date.parse(s.quote.expiresAt)>Date.now()&&(m={operationId:s.operationId,quote:s.quote})}catch{}let f=u.length>0&&l.length===0,x=M(e)||n==="operation"&&f&&!t&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":t||e.operationCommand||i&&i.type!=="cancel"||n==="operation"&&!m?"waiting_result":"ready";return{mode:n,status:x,purchases:u,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...M(e)?["start"]:[],...n==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...l.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function $(e){let n=B({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&j.get(e.operationId)===!0});return n.type==="complete"||n.type==="native"?n.type:null}function X(e){if(!e.operation)return;let n={...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}};if(n.merchantExecution&&n.merchantExecution.customerId!==E)throw new c("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let t=J(I.get(n.operationId)??null,n);I.set(n.operationId,t),t===n&&j.set(n.operationId,e.canReselect===!0)}async function qe(e){P();for(let t of[e.purchase,e.run.paywall])t&&X(t);let n=await w.update(t=>{if(h(t),t.run&&(t.run.id!==e.run.id||t.run.versionId!==e.run.source.versionId))throw new c("SCOPE_MISMATCH","The original purchase Run changed");let u=F(t);for(let l of[e.purchase,e.run.paywall]){let i=l?.operation?.operationId??l?.quote?.operationId;if(!l||!i)continue;let s=u.find(f=>f.operationId===i);if(s&&s.receiptId!==l.receiptId)throw new c("INVALID_RESPONSE","The original purchase Receipt changed");let m=$(I.get(i));s?s.terminal??=m:u.push({receiptId:l.receiptId,operationId:i,terminal:m})}return{...t,purchases:u,run:t.run&&(t.run.revision>e.run.revision||!["running","waiting"].includes(t.run.status)&&["running","waiting"].includes(e.run.status))?t.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});h(n),n.run&&!["running","waiting"].includes(n.run.status)&&F(n).some(t=>!t.terminal)&&(n=await Z(n,!n.journal.entry?.command&&!n.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(t=>!!t)))),h(n),C(_(n,"run"))}function _e(){return{async read(){let{entry:e}=await w.read();return h(e),structuredClone(e.journal)},async write(e,n){let t=null;return await w.update(u=>{if(h(u),u.operationCommand&&n?.command&&n.command.operation!=="close")throw new c("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return t=null,u.journal.revision!==e?u:(t=e+1,{...u,journal:{revision:t,entry:n}})}),t}}}async function Z(e,n=!1,t=new Set){h(e);let u=F(e);for(let i of u){if(i.terminal)continue;let s=t.has(i.operationId)?I.get(i.operationId):void 0;if(s??=await ce(e,i),P(),s.operationId!==i.operationId)throw new c("INVALID_RESPONSE","Original Operation changed");if(s.merchantExecution&&s.merchantExecution.customerId!==E)throw new c("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(n&&!e.operationCommand&&B({quote:s.quote??null,operation:s,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){if({operation:s}=await se.attach({operationId:i.operationId,intent:"cancel"}),P(),s.operationId!==i.operationId)throw new c("INVALID_RESPONSE","Original cancellation Operation changed");s=await ce(e,i)}I.set(i.operationId,J(I.get(i.operationId)??null,s))}let l=await w.update(i=>{h(i);let s=i.operationCommand&&I.get(i.operationCommand.operationId);return{...i,...s&&(s.confirmedAt||s.merchantExecution||s.status!=="pending")?{operationCommand:void 0}:{},purchases:F(i).map(m=>({...m,terminal:m.terminal??$(I.get(m.operationId))}))}});return h(l),l}async function ee(e){P();let n=await W.request("funnels",e);return P(),n}async function ce(e,n){let t=Q(Ee,await ee({operation:"recover_purchase",runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:n.receiptId,operationId:n.operationId}}));if(ne(e,t),t.purchase.receiptId!==n.receiptId||t.purchase.operation?.operationId!==n.operationId)throw new c("INVALID_RESPONSE","Original purchase reference changed");return X(t.purchase),I.get(n.operationId)}async function le(e){for(let n of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!n)continue;let t=Q(Re,await ee({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:n.requestId,...n.operation==="resume"?{}:{command:n}}));if(ne(e,t),t.settlement.requestId!==n.requestId)throw new c("INVALID_RESPONSE","Original command settlement changed");t.purchase&&X(t.purchase);let u=await w.update(l=>{h(l);let i=F(l),{receiptId:s,operationId:m}=t.settlement;if(s&&m){let x=i.find(S=>S.operationId===m);if(x&&x.receiptId!==s)throw new c("INVALID_RESPONSE","Original Receipt changed");x||i.push({receiptId:s,operationId:m,terminal:$(I.get(m))})}let f=t.settlement.state==="settled"?ge(l.journal.entry,n.requestId):l.journal.entry;return{...l,purchases:i,journal:f===l.journal.entry?l.journal:{revision:l.journal.revision+1,entry:f}}});h(u),e=u}return e}function ne(e,n){if(n.customerId!==E||n.scope.projectId!==d.scope.projectId||n.scope.environment!==d.scope.environment||n.target.funnelId!==e.start.funnelId||n.target.startRequestId!==e.start.requestId||e.run&&(n.target.runId!==e.run.id||n.target.versionId!==e.run.versionId))throw new c("SCOPE_MISMATCH","The original recovery binding changed")}async function te(e,n){if(h(e),e.run&&(e=await le(e)),!F(e).length&&M(e))return C(_(e,"operation"));if(!F(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(n)});v=!0;let t=await Z(e);return C(_(t,"operation"))}async function V(e,n=!1,t=!0){if(R=e.start.requestId,b=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!a){let u=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:n?"resume":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},l;try{l=await ee(u)}catch(f){if(!e.run&&f instanceof c&&(f.status===void 0||f.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:O.purchases,error:L(f)});throw f}let i=Q(Ce,l);if(i.customerId!==E||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new c("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:O.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});ne(e,i);let s=await w.update(f=>(h(f),{...f,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??f.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(h(s),e=s,i.access.type==="operation_only")return te(e,new c("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await le(e);let m=i.view;if(m.locale!==e.start.locale||!Se(m.parameters,e.start.parameters))throw new c("INVALID_RESPONSE","The original Start input changed");a=Pe({...d,customerRun:{runId:i.target.runId,customerId:E,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(f=>d.executionPolicy.allowed.includes(f))},funnelCommandStorage:_e(),onAcceptedResponse:qe},{scope:i.scope,run:m})}try{await a.get(),a.view?.pendingRequest?.requestId===e.start.requestId&&!a.pendingCommands?.length&&await a.resume(a.view.pendingRequest.requestId);for(let l of a.pendingCommands??[])l.operation!=="close"&&await a.settle?.(l.requestId);a.pendingCommands?.length&&await a.retry(),P();let u=(await w.read()).entry;return h(u),C(_(u,"run"))}catch(u){if(P(),t&&u instanceof c&&(u.status===401||u.status===409&&u.reason==="STATE_CHANGED")){a.reset(),a=null;let l=(await w.read()).entry;return h(l),V(l,!1,!1)}throw u}}function A(e,n="read"){if(P(),q)return n==="read"||n===U?q:q.then(()=>A(e,n),()=>A(e,n));clearTimeout(D);let t=e().catch(u=>{throw y||C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:O.purchases,error:L(u)}),u});return q=t,U=n,t.then(()=>{q===t&&(q=void 0,U=void 0)},()=>{q===t&&(q=void 0,U=void 0)}),t}function T(){return A(async()=>{let{entry:e}=await w.read();return e?(R&&e.start.requestId!==R&&(a?.reset(),a=null,I.clear(),j.clear()),v&&R===e.start.requestId?te(e,O.error):V(e)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}async function de(){let e=await T();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:A(async()=>{let n=(await w.read()).entry;if(h(n),!v){if(!a?.view?.paywall?.quote)throw new c("PURCHASE_PENDING","Read the original quote before confirming");let s=a.view.paywall.operation;if(s?.confirmedAt||s?.merchantExecution||s&&s.status!=="pending")return C(_(n,"run"));if(a.pendingCommands?.length)await a.retry();else{let f=a.view;await a.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:f.nodeId,visit:f.visit,revision:f.revision,input:{type:"paywall_confirm",operationId:f.paywall.quote.operationId}})}let m=(await w.read()).entry;return h(m),C(_(m,"run"))}let t=n.operationCommand?.operationId??O.confirmation?.operationId,u=t&&I.get(t);if(!t||!u||n.journal.entry?.command||n.journal.entry?.closeCommand)throw new c("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");z({allowed:n.allowed.filter(s=>d.executionPolicy.allowed.includes(s))},u.quote),await w.update(s=>{if(h(s),s.journal.entry?.command||s.journal.entry?.closeCommand||s.operationCommand&&s.operationCommand.operationId!==t)throw new c("PURCHASE_PENDING","Another original command is pending");return{...s,operationCommand:{operationId:t,intent:"confirm"}}});let l=await se.attach({operationId:t,intent:"confirm"});if(P(),l.operation.operationId!==t)throw new c("INVALID_RESPONSE","Original confirmation Operation changed");I.set(t,J(u,l.operation));let i=(await w.read()).entry;return h(i),C(_(await Z(i,!1,new Set([t])),"operation"))},"confirm")}return{get controller(){return a},get recovery(){return structuredClone(O)},get attempt(){return P(),structuredClone(b)},get identitySignal(){return ie.signal},start(e){let n=N.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(n.operation!=="start"||n.customer||n.customerData)throw new c("INVALID_REQUEST","A Customer-owned Funnel start is required");return A(async()=>{let t=await w.update(u=>{if(u&&!M(u)){if(u.start.funnelId!==n.funnelId)throw new c("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return u}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:E,sessionId:Y,start:n,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!t)throw new c("PURCHASE_STORAGE_INVALID","Original start was not retained");return R!==t.start.requestId&&(a?.reset(),a=null,I.clear(),j.clear(),v=!1),v?te(t,O.error):V(t,!0)},`start:${n.funnelId}`)},refresh:T,confirm:de,retry:()=>v?de():A(async()=>{let{entry:e}=await w.read();return e?V(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return a?.view?A(async()=>{if(!a?.view)throw new c("PURCHASE_PENDING","Recover the original Run before closing");if(a.pendingCommands?.find(t=>t.operation==="close"))await a.retry();else if(["running","waiting"].includes(a.view.status)){let t=a.view;await a.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision})}let n=(await w.read()).entry;return h(n),C(_(n,"run"))},"close"):T()},async continueCheckout(e){let n=await T();P(),await e(Te(n))},subscribe(e){return H.add(e),()=>{H.delete(e)}},destroy:ue}}export{be as a,Te as b,pn as c};
|
|
1
|
+
import{b as Ie}from"./chunk-TEMI3X5X.js";import{a as Q}from"./chunk-FODM46LT.js";import{A as Se,E as z,G as Pe,d as pe,f as k,k as me,v as we,w as ge,y as ye}from"./chunk-6YJ3CFPM.js";import{$ as N}from"./chunk-JOI5ZUBO.js";import{a as B,i as J}from"./chunk-FKDUXXGT.js";import{b as he}from"./chunk-GRNHBOSS.js";import{a as c}from"./chunk-FCBTTR5W.js";import{h as G}from"./chunk-W5KG2IWX.js";import{b as fe}from"./chunk-FVM4JJBA.js";import{b as r}from"./chunk-Z43N7U4U.js";import{a as oe}from"./chunk-DSPLGTQI.js";var g=N.options,Ae=r.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}),me.omit({customerToken:!0})]),je=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),Me=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume"]),start:r.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:je}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.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(o=>!o.command||o.requestId===o.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:Ae})]),ae=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:k.shape.run.shape.status}),K={scope:G,customerId:r.uuid()},Ce=r.discriminatedUnion("outcome",[r.strictObject({...K,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...K,outcome:r.literal("resolved"),target:ae,view:k.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((o,d)=>{o.outcome==="resolved"&&(o.access.type==="customer"!=(o.view!==null)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Re=r.strictObject({...K,target:ae,view:k.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:k.shape.purchase.unwrap().nullable()}).superRefine((o,d)=>{let p=o.settlement;(p.acceptance==="accepted"!=(p.receiptPhase!==null)||p.acceptance==="accepted"&&p.basis!=="receipt"||p.acceptance==="unknown"&&(p.state!=="unknown"||p.basis!=="none")||p.acceptance!=="accepted"&&(p.operationId!==null||p.receiptId!==null)||p.acceptance==="not_accepted"&&(p.state!=="settled"||!["run_terminal","position_advanced"].includes(p.basis))||o.purchase&&(o.purchase.receiptId!==p.receiptId||o.purchase.operation&&o.purchase.operation.operationId!==p.operationId||o.purchase.quote&&o.purchase.quote.operationId!==p.operationId)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ee=r.strictObject({...K,target:ae,purchase:k.shape.purchase.unwrap()}).superRefine((o,d)=>{(!o.purchase.operation||typeof o.purchase.canReselect!="boolean"||o.purchase.quote&&o.purchase.quote.operationId!==o.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})});var Ne=N.options[0].refine(o=>!o.customer&&!o.customerData),ke=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),ve=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:G,customerId:r.uuid(),sessionId:r.uuid(),start:Ne,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:pe.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ke).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:we.nullable()})});function be(o){return ye({...o,namespace:"purchases",identity:[o.scope.projectId,o.scope.environment,o.customerId]})}function Oe(o){let d=new URL(o.baseUrl??fe).href,p=()=>new c("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function E(){o.assertCurrent();try{let y=await o.storage.read();if(o.assertCurrent(),!Number.isSafeInteger(y.revision)||y.revision<0)throw p();let a=y.entry===null?null:ve.parse(y.entry);if(a&&(a.baseUrl!==d||a.customerId!==o.customerId||a.scope.projectId!==o.scope.projectId||a.scope.environment!==o.scope.environment))throw new c("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(a?.journal.entry&&(a.journal.entry.scope.projectId!==a.scope.projectId||a.journal.entry.scope.environment!==a.scope.environment||a.journal.entry.funnelId!==a.start.funnelId||a.journal.entry.runId!==a.run?.id||a.journal.entry.versionId!==a.run?.versionId)||a?.operationCommand&&!a.purchases.some(R=>R.operationId===a.operationCommand?.operationId))throw p();return{revision:y.revision,entry:a}}catch(y){throw y instanceof c?y:p()}}async function Y(y){for(let a=0;a<8;a++){let R=await E(),b=y(structuredClone(R.entry));if(JSON.stringify(b)===JSON.stringify(R.entry))return b;b&&ve.parse(b),o.assertCurrent();let v;try{v=await o.storage.write(R.revision,b)}catch{throw p()}if(o.assertCurrent(),v!==null){if(!Number.isSafeInteger(v)||v<=R.revision)throw p();return b}}throw new c("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:E,update:Y,baseUrl:d}}function Te(o){let d=o.purchases.find(p=>p.type==="checkout");if(!o.actions.includes("continue_checkout")||d?.type!=="checkout")throw new c("PURCHASE_PENDING","No single resumable Checkout is confirmed");return d.checkoutUrl}function pn(o){let d={...o,scope:{...o.scope},executionPolicy:structuredClone(o.executionPolicy)},p=d.session.snapshot();if(!p)throw new c("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:E,sessionId:Y}=p,y=!1,a=null,R,b=null,v=!1,q,U,D,O={mode:"idle",status:"idle",actions:["start"],purchases:[]},I=new Map,j=new Map,ie=new AbortController,H=new Set,W=he(d),se=Ie(W.request);function L(e){return{code:e instanceof c?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof c&&e.status!==void 0?{status:e.status}:{}}}function P(){if(y||d.session.snapshot()?.customerId!==E)throw new c("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Oe({...d,customerId:E,assertCurrent:P,storage:d.storage??be({baseUrl:d.baseUrl,scope:d.scope,customerId:E})}),Fe=d.session.subscribeIdentity(ue);function ue(){y||(y=!0,clearTimeout(D),ie.abort(new c("IDENTITY_CHANGED","Purchase consumer was destroyed")),Fe(),a?.reset(),a=null,b=null,W.dispose(),H.clear(),I.clear(),j.clear())}function C(e){P();let n=JSON.stringify(e)!==JSON.stringify(O);O=e,clearTimeout(D),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(D=setTimeout(()=>{T().catch(()=>{})},5e3)),n&&oe(d.onRecovery,structuredClone(e));for(let t of n?H:[]){if(y)break;oe(t,structuredClone(e))}return structuredClone(e)}function h(e){if(P(),!e||e.start.requestId!==R)throw new c("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function F(e){let n=[...e.purchases],t=e.journal.entry?.purchase;return t&&!n.some(u=>u.operationId===t.operationId)&&n.push({receiptId:t.receiptId,operationId:t.operationId,terminal:null}),n}function M(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&F(e).every(n=>n.terminal!==null)}function _(e,n){let t=e.journal.entry?.command??e.journal.entry?.closeCommand,u=F(e).map(S=>{let re=I.get(S.operationId);return S.terminal&&!re?{type:S.terminal,operationId:S.operationId}:B({quote:re?.quote??null,operation:re??null,requestId:t?.requestId??null,pending:!1,destroyed:!1,canReselect:j.get(S.operationId)===!0})}),l=u.filter(S=>!["complete","native"].includes(S.type)),i=l[0],s=l.length===1&&i?.operationId?I.get(i.operationId):void 0;if(s&&(i?.type==="checkout"||i?.type==="cancel"))try{z({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote)}catch(S){return{mode:n,status:"blocked",actions:["refresh",...n==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:u,error:L(S)}}let m;if(n==="operation"&&!t&&i?.type==="cancel"&&s?.quote&&!s.problem&&!s.confirmedAt)try{z({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote),Date.parse(s.quote.expiresAt)>Date.now()&&(m={operationId:s.operationId,quote:s.quote})}catch{}let f=u.length>0&&l.length===0,x=M(e)||n==="operation"&&f&&!t&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":t||e.operationCommand||i&&i.type!=="cancel"||n==="operation"&&!m?"waiting_result":"ready";return{mode:n,status:x,purchases:u,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...M(e)?["start"]:[],...n==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...l.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function $(e){let n=B({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&j.get(e.operationId)===!0});return n.type==="complete"||n.type==="native"?n.type:null}function X(e){if(!e.operation)return;let n={...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}};if(n.merchantExecution&&n.merchantExecution.customerId!==E)throw new c("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let t=J(I.get(n.operationId)??null,n);I.set(n.operationId,t),t===n&&j.set(n.operationId,e.canReselect===!0)}async function qe(e){P();for(let t of[e.purchase,e.run.paywall])t&&X(t);let n=await w.update(t=>{if(h(t),t.run&&(t.run.id!==e.run.id||t.run.versionId!==e.run.source.versionId))throw new c("SCOPE_MISMATCH","The original purchase Run changed");let u=F(t);for(let l of[e.purchase,e.run.paywall]){let i=l?.operation?.operationId??l?.quote?.operationId;if(!l||!i)continue;let s=u.find(f=>f.operationId===i);if(s&&s.receiptId!==l.receiptId)throw new c("INVALID_RESPONSE","The original purchase Receipt changed");let m=$(I.get(i));s?s.terminal??=m:u.push({receiptId:l.receiptId,operationId:i,terminal:m})}return{...t,purchases:u,run:t.run&&(t.run.revision>e.run.revision||!["running","waiting"].includes(t.run.status)&&["running","waiting"].includes(e.run.status))?t.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});h(n),n.run&&!["running","waiting"].includes(n.run.status)&&F(n).some(t=>!t.terminal)&&(n=await Z(n,!n.journal.entry?.command&&!n.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(t=>!!t)))),h(n),C(_(n,"run"))}function _e(){return{async read(){let{entry:e}=await w.read();return h(e),structuredClone(e.journal)},async write(e,n){let t=null;return await w.update(u=>{if(h(u),u.operationCommand&&n?.command&&n.command.operation!=="close")throw new c("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return t=null,u.journal.revision!==e?u:(t=e+1,{...u,journal:{revision:t,entry:n}})}),t}}}async function Z(e,n=!1,t=new Set){h(e);let u=F(e);for(let i of u){if(i.terminal)continue;let s=t.has(i.operationId)?I.get(i.operationId):void 0;if(s??=await ce(e,i),P(),s.operationId!==i.operationId)throw new c("INVALID_RESPONSE","Original Operation changed");if(s.merchantExecution&&s.merchantExecution.customerId!==E)throw new c("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(n&&!e.operationCommand&&B({quote:s.quote??null,operation:s,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){if({operation:s}=await se.attach({operationId:i.operationId,intent:"cancel"}),P(),s.operationId!==i.operationId)throw new c("INVALID_RESPONSE","Original cancellation Operation changed");s=await ce(e,i)}I.set(i.operationId,J(I.get(i.operationId)??null,s))}let l=await w.update(i=>{h(i);let s=i.operationCommand&&I.get(i.operationCommand.operationId);return{...i,...s&&(s.confirmedAt||s.merchantExecution||s.status!=="pending")?{operationCommand:void 0}:{},purchases:F(i).map(m=>({...m,terminal:m.terminal??$(I.get(m.operationId))}))}});return h(l),l}async function ee(e){P();let n=await W.request("funnels",e);return P(),n}async function ce(e,n){let t=Q(Ee,await ee({operation:"recover_purchase",runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:n.receiptId,operationId:n.operationId}}));if(ne(e,t),t.purchase.receiptId!==n.receiptId||t.purchase.operation?.operationId!==n.operationId)throw new c("INVALID_RESPONSE","Original purchase reference changed");return X(t.purchase),I.get(n.operationId)}async function le(e){for(let n of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!n)continue;let t=Q(Re,await ee({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:n.requestId,...n.operation==="resume"?{}:{command:n}}));if(ne(e,t),t.settlement.requestId!==n.requestId)throw new c("INVALID_RESPONSE","Original command settlement changed");t.purchase&&X(t.purchase);let u=await w.update(l=>{h(l);let i=F(l),{receiptId:s,operationId:m}=t.settlement;if(s&&m){let x=i.find(S=>S.operationId===m);if(x&&x.receiptId!==s)throw new c("INVALID_RESPONSE","Original Receipt changed");x||i.push({receiptId:s,operationId:m,terminal:$(I.get(m))})}let f=t.settlement.state==="settled"?ge(l.journal.entry,n.requestId):l.journal.entry;return{...l,purchases:i,journal:f===l.journal.entry?l.journal:{revision:l.journal.revision+1,entry:f}}});h(u),e=u}return e}function ne(e,n){if(n.customerId!==E||n.scope.projectId!==d.scope.projectId||n.scope.environment!==d.scope.environment||n.target.funnelId!==e.start.funnelId||n.target.startRequestId!==e.start.requestId||e.run&&(n.target.runId!==e.run.id||n.target.versionId!==e.run.versionId))throw new c("SCOPE_MISMATCH","The original recovery binding changed")}async function te(e,n){if(h(e),e.run&&(e=await le(e)),!F(e).length&&M(e))return C(_(e,"operation"));if(!F(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(n)});v=!0;let t=await Z(e);return C(_(t,"operation"))}async function V(e,n=!1,t=!0){if(R=e.start.requestId,b=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!a){let u=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:n?"resume":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},l;try{l=await ee(u)}catch(f){if(!e.run&&f instanceof c&&(f.status===void 0||f.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:O.purchases,error:L(f)});throw f}let i=Q(Ce,l);if(i.customerId!==E||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new c("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:O.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});ne(e,i);let s=await w.update(f=>(h(f),{...f,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??f.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(h(s),e=s,i.access.type==="operation_only")return te(e,new c("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await le(e);let m=i.view;if(m.locale!==e.start.locale||!Se(m.parameters,e.start.parameters))throw new c("INVALID_RESPONSE","The original Start input changed");a=Pe({...d,customerRun:{runId:i.target.runId,customerId:E,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(f=>d.executionPolicy.allowed.includes(f))},funnelCommandStorage:_e(),onAcceptedResponse:qe},{scope:i.scope,run:m})}try{await a.get(),a.view?.pendingRequest?.requestId===e.start.requestId&&!a.pendingCommands?.length&&await a.resume(a.view.pendingRequest.requestId);for(let l of a.pendingCommands??[])l.operation!=="close"&&await a.settle?.(l.requestId);a.pendingCommands?.length&&await a.retry(),P();let u=(await w.read()).entry;return h(u),C(_(u,"run"))}catch(u){if(P(),t&&u instanceof c&&(u.status===401||u.status===409&&u.reason==="STATE_CHANGED")){a.reset(),a=null;let l=(await w.read()).entry;return h(l),V(l,!1,!1)}throw u}}function A(e,n="read"){if(P(),q)return n==="read"||n===U?q:q.then(()=>A(e,n),()=>A(e,n));clearTimeout(D);let t=e().catch(u=>{throw y||C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:O.purchases,error:L(u)}),u});return q=t,U=n,t.then(()=>{q===t&&(q=void 0,U=void 0)},()=>{q===t&&(q=void 0,U=void 0)}),t}function T(){return A(async()=>{let{entry:e}=await w.read();return e?(R&&e.start.requestId!==R&&(a?.reset(),a=null,I.clear(),j.clear()),v&&R===e.start.requestId?te(e,O.error):V(e)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}async function de(){let e=await T();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:A(async()=>{let n=(await w.read()).entry;if(h(n),!v){if(!a?.view?.paywall?.quote)throw new c("PURCHASE_PENDING","Read the original quote before confirming");let s=a.view.paywall.operation;if(s?.confirmedAt||s?.merchantExecution||s&&s.status!=="pending")return C(_(n,"run"));if(a.pendingCommands?.length)await a.retry();else{let f=a.view;await a.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:f.nodeId,visit:f.visit,revision:f.revision,input:{type:"paywall_confirm",operationId:f.paywall.quote.operationId}})}let m=(await w.read()).entry;return h(m),C(_(m,"run"))}let t=n.operationCommand?.operationId??O.confirmation?.operationId,u=t&&I.get(t);if(!t||!u||n.journal.entry?.command||n.journal.entry?.closeCommand)throw new c("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");z({allowed:n.allowed.filter(s=>d.executionPolicy.allowed.includes(s))},u.quote),await w.update(s=>{if(h(s),s.journal.entry?.command||s.journal.entry?.closeCommand||s.operationCommand&&s.operationCommand.operationId!==t)throw new c("PURCHASE_PENDING","Another original command is pending");return{...s,operationCommand:{operationId:t,intent:"confirm"}}});let l=await se.attach({operationId:t,intent:"confirm"});if(P(),l.operation.operationId!==t)throw new c("INVALID_RESPONSE","Original confirmation Operation changed");I.set(t,J(u,l.operation));let i=(await w.read()).entry;return h(i),C(_(await Z(i,!1,new Set([t])),"operation"))},"confirm")}return{get controller(){return a},get recovery(){return structuredClone(O)},get attempt(){return P(),structuredClone(b)},get identitySignal(){return ie.signal},start(e){let n=N.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(n.operation!=="start"||n.customer||n.customerData)throw new c("INVALID_REQUEST","A Customer-owned Funnel start is required");return A(async()=>{let t=await w.update(u=>{if(u&&!M(u)){if(u.start.funnelId!==n.funnelId)throw new c("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return u}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:E,sessionId:Y,start:n,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!t)throw new c("PURCHASE_STORAGE_INVALID","Original start was not retained");return R!==t.start.requestId&&(a?.reset(),a=null,I.clear(),j.clear(),v=!1),v?te(t,O.error):V(t,!0)},`start:${n.funnelId}`)},refresh:T,confirm:de,retry:()=>v?de():A(async()=>{let{entry:e}=await w.read();return e?V(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return a?.view?A(async()=>{if(!a?.view)throw new c("PURCHASE_PENDING","Recover the original Run before closing");if(a.pendingCommands?.find(t=>t.operation==="close"))await a.retry();else if(["running","waiting"].includes(a.view.status)){let t=a.view;await a.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision})}let n=(await w.read()).entry;return h(n),C(_(n,"run"))},"close"):T()},async continueCheckout(e){let n=await T();P(),await e(Te(n))},subscribe(e){return H.add(e),()=>{H.delete(e)}},destroy:ue}}export{be as a,Te as b,pn as c};
|