@tinkerlandai/longplay-sdk 0.10.36 → 0.10.37
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/README.md +8 -0
- package/README.zh-CN.md +8 -0
- package/dist/check-response-N22NNTIT.js +1 -0
- package/dist/chunk-2HBIBIOF.js +1 -0
- package/dist/{chunk-VWMFR22O.js → chunk-2KJLN65C.js} +1 -1
- package/dist/{chunk-VKG6BB3Z.js → chunk-2VMEDQHT.js} +1 -1
- package/dist/{chunk-5XKFUFXK.js → chunk-4KLXQKNO.js} +1 -1
- package/dist/{chunk-IOBB6KFK.js → chunk-6F4JS3RK.js} +1 -1
- package/dist/{chunk-HVVJGLYZ.js → chunk-7XDQKZYA.js} +1 -1
- package/dist/{chunk-35VG2IYD.js → chunk-AB7GEGZ2.js} +1 -1
- package/dist/{chunk-RHF4NFCZ.js → chunk-AHUYZ6IW.js} +1 -1
- package/dist/{chunk-YQX27SBG.js → chunk-AOGDCT4T.js} +1 -1
- package/dist/{chunk-MHWPEMX7.js → chunk-CY7OKV7E.js} +1 -1
- package/dist/{chunk-2HSD2SEU.js → chunk-D3OYXTMC.js} +1 -1
- package/dist/chunk-DDLSQSWO.js +10 -0
- package/dist/{chunk-RHWZRHK7.js → chunk-E7CCHUSO.js} +1 -1
- package/dist/{chunk-U4WUX3WB.js → chunk-ECKVJGXQ.js} +1 -1
- package/dist/chunk-GH6FM44P.js +1 -0
- package/dist/{chunk-DHT3AWJQ.js → chunk-HEHLFHW7.js} +1 -1
- package/dist/chunk-HKXFCRVT.js +1 -0
- package/dist/chunk-KFIL73QY.js +1 -0
- package/dist/{chunk-UHTTCVSL.js → chunk-LC6UCDWE.js} +1 -1
- package/dist/{chunk-LAGGWYH3.js → chunk-LOLMUXHW.js} +1 -1
- package/dist/{chunk-LVG5ED52.js → chunk-OCWSWXCW.js} +1 -1
- package/dist/{chunk-BL7E4RZ2.js → chunk-OQRMAU2B.js} +1 -1
- package/dist/{chunk-5XIKN35D.js → chunk-OX2A3UD2.js} +1 -1
- package/dist/{chunk-BTPEXSNY.js → chunk-PW5PIBSO.js} +1 -1
- package/dist/chunk-Q676H74B.js +1 -0
- package/dist/{chunk-MYBUQFTC.js → chunk-RE4OLOOT.js} +1 -1
- package/dist/{chunk-2KKLY323.js → chunk-S43TYW3V.js} +1 -1
- package/dist/{chunk-XE7GU6FZ.js → chunk-T2KWLYCW.js} +1 -1
- package/dist/chunk-TASEZY5T.js +1 -0
- package/dist/{chunk-TIQS5DUF.js → chunk-U7NX5ET2.js} +1 -1
- package/dist/{chunk-XQTCEQXI.js → chunk-UV4H6VCS.js} +1 -1
- package/dist/{chunk-UVUFJO2V.js → chunk-VIBJNB5B.js} +1 -1
- package/dist/chunk-VLSP3LRH.js +1 -0
- package/dist/{chunk-R3YVDRTB.js → chunk-W74JLL2O.js} +1 -1
- package/dist/chunk-WQ3O5RXN.js +1 -0
- package/dist/{chunk-QHJWVLJC.js → chunk-WZMZMJCK.js} +1 -1
- package/dist/{chunk-I6D25FWU.js → chunk-XGNXZWZL.js} +1 -1
- package/dist/{chunk-ZYF6TRJ3.js → chunk-XJRDO3NI.js} +1 -1
- package/dist/chunk-YV6UFESO.js +1 -0
- package/dist/{chunk-M3GGR53D.js → chunk-ZYOZSUZS.js} +1 -1
- package/dist/{chunk-HS56A4IK.js → chunk-ZZIBLQCJ.js} +1 -1
- package/dist/content-QNBATPA2.js +1 -0
- package/dist/{funnel-host-purchase-M7MM33EC.js → funnel-host-purchase-FVYPBPET.js} +1 -1
- package/dist/funnel-paywall-prerender-Z7RA4YDY.js +1 -0
- package/dist/funnel-runtime-host-TJPF3FJS.js +1 -0
- package/dist/index.d.ts +23 -3
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-67AYXZFI.js +1 -0
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-EK4RCUWJ.js +1 -0
- package/dist/page.js +1 -1
- package/dist/paywall-OAVC654P.js +1 -0
- package/dist/paywall-content-75XEM7K3.js +1 -0
- package/dist/paywall-session-U6SPRJRS.js +1 -0
- package/dist/popup.d.ts +1 -1
- package/dist/popup.js +1 -1
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-YIIT742O.js +1 -0
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +10 -9
- package/dist/check-response-DHY6T5Z2.js +0 -1
- package/dist/chunk-7ZEXY4GC.js +0 -1
- package/dist/chunk-C4GBV32U.js +0 -10
- package/dist/chunk-CGXNU5BC.js +0 -1
- package/dist/chunk-DB4EO3JG.js +0 -1
- package/dist/chunk-GLYFT5WW.js +0 -1
- package/dist/chunk-HYE2YQYM.js +0 -1
- package/dist/chunk-JOIPLLHK.js +0 -1
- package/dist/chunk-OL2AI6DA.js +0 -1
- package/dist/chunk-W3K5ARMY.js +0 -1
- package/dist/chunk-WRLVPHPE.js +0 -1
- package/dist/content-RGKTEV23.js +0 -1
- package/dist/funnel-paywall-prerender-OSBI4VMY.js +0 -1
- package/dist/funnel-runtime-host-AMJXEASH.js +0 -1
- package/dist/merchant-bridge-contracts-GJQVKEAG.js +0 -1
- package/dist/operation-contracts-MFK2KORK.js +0 -1
- package/dist/paywall-ATZ2IZPS.js +0 -1
- package/dist/paywall-content-XERXGNND.js +0 -1
- package/dist/paywall-session-EMMF6IYS.js +0 -1
- package/dist/screen-renderer-B7LUTPTJ.js +0 -1
- /package/dist/{chunk-ZYN4CRHS.js → chunk-CR2XJ2CX.js} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as Mn,b as Un,c as un,d as dn,e as Me,f as $n,h as xn,i as Gn,j as Qn,k as Jn}from"./chunk-XGNXZWZL.js";import{b as zn}from"./chunk-TASEZY5T.js";import{b as qn,c as Bn}from"./chunk-2KJLN65C.js";import{a as On}from"./chunk-W32FI2A2.js";import{c as Sn,e as _n,f as Ln,h as Hn,i as Se,j as Ze,k as Vn,l as Ke}from"./chunk-AOGDCT4T.js";import{aa as Xe}from"./chunk-YV6UFESO.js";import{a as Ve,d as Dn}from"./chunk-3NCMYTNG.js";import{b as Rn}from"./chunk-AB7GEGZ2.js";import{b as kn,d as Tn,e as An,f as Nn,g as Fn}from"./chunk-Q676H74B.js";import{F as Pn,ea as En}from"./chunk-WZMZMJCK.js";import{a as y}from"./chunk-U7NX5ET2.js";import{a as Ce}from"./chunk-DSPLGTQI.js";async function cn(t){let{session:v,load:C}=it(t);try{return await C(),v}catch(e){throw v.destroy(),e}}function it(t){let v=t.view;if(!v?.paywall)throw new y("INVALID_REQUEST","The current node is not a Paywall");let C=v.paywall.receiptId,e=v.nodeId,w=v.visit,A=v.paywall.resolution,s=v.paywall,S="document"in A?{document:A.document,offering:A.offering,capabilities:A.capabilities}:null;function d(){let i=s.resolution;return"document"in i?i:S&&{...i,document:S.document,offering:S.offering,capabilities:kn(i.capabilities,S.capabilities)}}function I(i){if(!Tn(i,A))throw new y("INVALID_RESPONSE","The pinned Paywall binding changed")}let P=!1,$=new Set,ne=null;function m(){let i=d();if(i&&!P)for(let l of $)Ce(l,structuredClone(i))}async function V(){N();let i=d();if(i)return structuredClone(i);if(!ne){let l=(async()=>{if("document"in s.resolution||!t.resolvePaywall)throw new y("INVALID_RESPONSE","Public Paywall reader is unavailable");let b=await qn(t,s.resolution);return N(),I(b),S={document:b.document,offering:b.offering,capabilities:b.capabilities},m(),d()})();ne=l;let a=()=>{ne===l&&(ne=null)};l.then(a,a)}return ne.then(l=>structuredClone(l))}let o=new AbortController,_=(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===w&&i.input.type==="paywall_quote")?.requestId??v.paywall.purchaseRequestId,Y=0,J=null,Q=new Set,E=null,z=new Map;function k(i){if(i.purchase&&i.purchase.receiptId!==C)throw new y("INVALID_RESPONSE","Purchase receipt changed");let l=i.run.paywall;return i.purchase??(l?.receiptId===C?l:null)}function N(){if(P)throw new y("IDENTITY_CHANGED","Paywall presentation has closed")}function F(i,l,a){if(N(),l!==Y||a!==void 0&&s.quote?.operationId!==a)return!1;let b=s.selectionGeneration??0,c=i.run.paywall;if(c?.receiptId===C){if((c.selectionGeneration??0)<(s.selectionGeneration??0))return!1;I(c.resolution)}let u=k(i),q=c?.receiptId===C&&(c.selectionGeneration??0)>b,L=q?u?.quote??null:u?.quote??s.quote,B=u?.operation??(L?.operationId===s.quote?.operationId?s.operation:null);return L&&B&&An(B,{operationId:L.operationId},"Purchase operation changed"),(q||L?.operationId!==s.quote?.operationId)&&(Y++,c?.receiptId===C&&(_=c.purchaseRequestId)),c?.canReselect===!0&&c.purchaseRequestId===E&&!(t.pendingCommands??[t.pendingCommand]).some(M=>M?.requestId===E)&&(E=null),s={...s,...c?.receiptId===C?c:{},...a!==void 0&&!q&&u?.canReselect!==void 0?{canReselect:u.canReselect}:{},quote:L,operation:Fn(s.operation,B,!0)},m(),!0}function ce(i,l,a){return new Promise((b,c)=>{let u=!1,q=()=>{clearTimeout(Ee),o.signal.removeEventListener("abort",M)},L=Re=>{u||(u=!0,q(),b(Re))},B=Re=>{u||(u=!0,q(),c(Re))},M=()=>B(new y("IDENTITY_CHANGED","Paywall presentation has closed")),Ee=setTimeout(()=>B(new y("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a)),Math.max(0,l-Date.now()));o.signal.addEventListener("abort",M,{once:!0}),o.signal.aborted&&M(),i.then(L,B)})}function Pe(i){return new Promise(l=>{let a=()=>{clearTimeout(b),o.signal.removeEventListener("abort",a),l()},b=setTimeout(a,i);o.signal.addEventListener("abort",a,{once:!0}),o.signal.aborted&&a()})}function se(i,l){N();let a=z.get(i)??t.pendingCommands?.find(u=>u.requestId===i)??t.pendingCommand;if(a?.operation==="submit"&&a.requestId===i&&a.nodeId===e&&a.visit===w){l.type==="paywall_quote"&&a.input.type==="paywall_quote"&&a.input.predecessor&&!l.predecessor&&(l={...l,predecessor:a.input.predecessor});let u=Xe.parse(a),q=Xe.parse({...a,input:l});if(u.operation!=="submit"||q.operation!=="submit"||JSON.stringify(u.input)!==JSON.stringify(q.input))throw new y("CONFLICT","A purchase request cannot change its input");return z.set(i,u),u}let b=t.view;if(!b||b.nodeId!==e||b.visit!==w||b.paywall?.receiptId!==C)throw new y("PRECONDITION_FAILED","The Paywall visit has changed");let c=Xe.parse({operation:"submit",requestId:i,nodeId:e,visit:w,revision:b.revision,input:structuredClone(l)});if(c.operation!=="submit")throw new y("INVALID_REQUEST","A purchase submission is required");return z.set(i,c),c}async function te(i,l){N();let{requestId:a,input:b}=i,c=Date.now()+3e4;Q.add(a);try{let u=await ce(t.submit(i),c,a);for(;u.run.pendingRequest?.requestId===a&&Date.now()<c&&!P&&(await Pe(Math.min(1e3,c-Date.now())),!(P||Date.now()>=c));)u=await ce(t.resume(a),c,a);if(P)throw new y("IDENTITY_CHANGED","Paywall presentation has closed");if(u.run.pendingRequest?.requestId===a)throw new y("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a);if(!F(u,l,b.type==="paywall_confirm"||b.type==="paywall_cancel"?b.operationId:void 0))throw new y("PRECONDITION_FAILED","The purchase selection has changed");E===a&&(E=null)}catch(u){if(E=a,b.type==="paywall_quote"&&t.settle&&!P&&u instanceof y&&u.status!==void 0&&![401,425].includes(u.status)&&!u.retryable&&u.recovery!=="recover_operation")try{if((await ce(t.settle(a),c,a)).settlement?.state==="settled"){let L=await ce(t.get(),c,a);F(L,l)&&L.run.paywall?.purchaseRequestId===a&&s.canReselect===!0&&z.delete(a)}}catch{}throw u instanceof y&&u.code==="COMMAND_PENDING"&&u.status===void 0&&z.delete(a),u}finally{Q.delete(a)}}async function me(i){if(!s.quote)throw new y("INVALID_REQUEST","A quoted purchase is required");let l=i==="confirm"?"paywall_confirm":"paywall_cancel",a=[...z.values(),...t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])].find(c=>c.operation==="submit"&&c.input.type===l&&"operationId"in c.input&&c.input.operationId===s.quote.operationId),b=a?.operation==="submit"&&a.input.type===l&&"operationId"in a.input&&a.input.operationId===s.quote.operationId?a.requestId:crypto.randomUUID();if(await te(se(b,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:s.quote.operationId}),Y),!s.operation)throw new y("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(s.operation)}let G={get view(){return structuredClone(d())},get quote(){return s.quote?structuredClone(s.quote):null},get operation(){return s.operation?structuredClone(s.operation):null},get webViewUrl(){return t.webViewUrl},get locale(){return t.view?.locale??v.locale},get canReselect(){return s.canReselect===!0&&E===null},get recovery(){let i=t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[]),l=t.pendingPurchase;if(l&&(l.receiptId!==C||l.operationId!==s.quote?.operationId))return{type:"recover",operationId:l.operationId,requestId:i[0]?.requestId??null};let a=Ve({quote:s.quote,operation:s.operation,requestId:i[0]?.requestId??E??_,pending:Q.size>0||i.length>0||E!==null,destroyed:P,canReselect:s.canReselect});return a.type==="recover"&&a.requestId===null&&!P&&t.hasDurableJournal===!0&&!s.quote&&!s.operation&&(s.selectionGeneration??0)===0&&!l&&!i.length&&!Q.size&&!_?{type:"native",operationId:null}:a},get pendingCancellation(){return!P&&(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===w&&i.input.type==="paywall_cancel"&&i.input.operationId===s.quote?.operationId)},subscribe(i){return P?()=>{}:($.add(i),()=>$.delete(i))},async refresh(){N();let i=Y,l=await t.get();if(F(l,i),l.run.paywall?.receiptId!==C)throw new y("PRECONDITION_FAILED","Paywall presentation has changed");return V()},preview(i){let l=d();if(!l)return Promise.reject(new y("PRECONDITION_FAILED","Load the Paywall presentation first"));if(_&&_!==i.requestId&&(J||s.canReselect!==!0))return Promise.reject(new y("COMMAND_PENDING","Retry the original purchase before starting another"));let a=l.document.buttons[i.actionId],b=a?.type==="checkout"?Rn(a.product,i.selection,l.capabilities):null;if(!b)return Promise.reject(new y("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let c=En(l.document.screen,b,i.selection,l.capabilities),u=_!==i.requestId&&(s.selectionGeneration??0)>0?{operationId:s.quote?.operationId??null,generation:s.selectionGeneration??0}:void 0;if(u&&s.canReselect!==!0)return Promise.reject(new y("COMMAND_PENDING","Original purchase requires authoritative termination"));let q;try{q=se(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:b,...Object.keys(c).length?{featureQuantities:c}:{},...u?{predecessor:u}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}})}catch(M){return Promise.reject(M)}if(_===i.requestId&&J)return J;_!==i.requestId&&Y++;let L=Y;_=i.requestId;let B=(async()=>{if(await te(q,L),!s.quote)throw new y("INVALID_RESPONSE","The accepted quote is missing");return Nn(s.quote,{productVersionId:b,featureQuantities:c},"The selected purchase changed"),structuredClone(s.quote)})();return J=B,B.then(()=>{J===B&&(J=null)},M=>{J===B&&(J=null),_===i.requestId&&t.pendingCommand?.requestId!==i.requestId&&M instanceof y&&M.status!==void 0&&M.status<500&&![401,425].includes(M.status)&&(_=null)}),B},confirm:()=>me("confirm"),cancel:()=>me("cancel"),async read(){if(N(),!s.quote)throw new y("INVALID_REQUEST","A quoted purchase is required");let i=s.quote.operationId,l=Y,a=t.pendingCommands?.find(L=>L.operation==="submit"&&(L.input.type==="paywall_confirm"||L.input.type==="paywall_cancel")&&L.input.operationId===i)??t.pendingCommand;a?.operation==="submit"&&(a.input.type==="paywall_confirm"||a.input.type==="paywall_cancel")&&a.input.operationId===i&&await t.settle?.(a.requestId);let b=await t.get(void 0,{receiptId:C,operationId:i});N();let c=k(b);if(c?.quote&&c.quote.operationId!==i||c?.operation&&c.operation.operationId!==i)throw new y("INVALID_RESPONSE","Purchase operation changed");let u=F(b,l,i),q=u?s.operation:c?.operation;if(!q)throw new y("INVALID_RESPONSE","The current purchase result is missing");return u&&Q.size===0&&!(t.pendingCommands?.length??(t.pendingCommand?1:0))&&(E=null),structuredClone(q)},destroy(){P=!0,T(),$.clear(),o.abort(),z.clear()}},T=t.subscribe(i=>{P||i.nodeId!==e||i.visit!==w||i.paywall?.receiptId!==C||(i.paywall.selectionGeneration??0)<(s.selectionGeneration??0)||(I(i.paywall.resolution),s={...s,resolution:i.paywall.resolution},m())});return{session:G,load:V}}function jn(t){let v=new Set,C=new Set,e=null;async function w(d,I){let P=!1;for(;!t.stopped&&t.key===d&&t.client.pendingCommand?.requestId===I;){if(!t.client.settle)throw new y("COMMAND_PENDING","The original display acknowledgement is still pending");await t.client.settle(I),P=!0,t.client.pendingCommand?.requestId===I&&await new Promise($=>setTimeout($,1500))}t.stopped||t.key!==d||(P&&await t.client.get(),!(t.stopped||t.key!==d)&&v.add(d))}function A(d,I){e=I;let P=()=>{e===I&&(e=null),C.delete(d)};return I.then(P,$=>{P(),t.busy||t.fail($)}),I}function s(d){if(t.reviewing||v.has(d)||C.has(d)||t.stopped)return;C.add(d);let I=async()=>{if(t.reviewing||t.stopped||t.key!==d||v.has(d)){C.delete(d);return}if(t.busy||t.client.pendingCommand){setTimeout(()=>{I()},250);return}let P=(async()=>{if(t.staleRead){if(await t.staleRead,t.stopped||t.key!==d)return;if(t.client.pendingCommand){setTimeout(()=>{I()},250);return}}let $=t.client.view,ne=t.expected(),m=ne.requestId;try{await t.client.submit({operation:"shown",...ne})}catch(V){if(!(V instanceof y)||V.code!=="CONFLICT"||V.status!==409||t.client.pendingCommand)throw V;await t.client.get();let o=t.client.view;if(t.stopped||t.reviewing||t.key!==d||!o||!$||o.id!==$.id||o.source.versionId!==$.source.versionId||o.nodeId!==ne.nodeId||o.visit!==ne.visit||o.revision<=ne.revision||o.stopped||!o.screen&&(!o.paywall||o.paywall.receiptId!==$.paywall?.receiptId)||!["running","waiting"].includes(o.status)||t.client.pendingCommand)throw V;let R=t.expected();m=R.requestId,await t.client.submit({operation:"shown",...R})}await w(d,m)})();A(d,P)};I()}function S(){if(e)return e;let d=t.client.pendingCommand;if(d?.operation!=="shown")return null;let I=t.key;return C.add(I),A(I,(async()=>{await t.client.retry(),await w(I,d.requestId)})())}return{report:s,settled:S,get inFlight(){return e}}}function Wn(t){let v={},C=new Map;async function e(w){let A=t.client.view,s=A?.screen,S=s?.customerData.nodes[w.nodeId];if(t.stopped||t.busy||!A||!s||!S)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(w.action)){let V=t.document,o=V?Pn(V,w.nodeId):null,R=o?.type==="customer_data"?o.data.outputs?.[w.action]:void 0;R&&s.outputs.includes(R)?await t.perform(()=>t.client.submit({operation:"submit",...t.expected(),input:{type:"screen",output:R,answers:t.answers,selection:w.value?{[w.nodeId]:w.value}:{}}})):await t.onIntent?.(w,A);return}let I=w.action.startsWith("sources_")?S.resources.find(V=>V.key===w.value):null;if(w.action.startsWith("sources_")&&!I)throw new y("INVALID_REQUEST","Choose a current resource");let P=`${A.visit}:${w.nodeId}:${I?.key??""}`,$=C.get(P)??[null],m=v[w.nodeId]??{page:1,after:null,filter:"all",...I?{resourceKey:I.key}:{}};if(w.action==="filter"){let V=w.value;if(!V||!(S.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(V))throw new y("INVALID_REQUEST","Unknown data filter");m={page:1,after:null,filter:V},$.splice(0,$.length,null)}else if(w.action==="next"||w.action==="sources_next"){let V=I?.sources.at(-1),o=I?V?{kind:"ledger",cursor:{at:V.detail[0],id:V.id,type:"source"}}:null:s.dataCursors[w.nodeId];if(!o||!I&&!S.hasNext)return;$[m.page]=o,m={...m,page:m.page+1,after:o}}else if(w.action==="previous"||w.action==="sources_previous"){if(m.page<=1)return;m={...m,page:m.page-1,after:$[m.page-2]??null}}C.set(P,$),v={...v,[w.nodeId]:m},await t.perform(()=>t.client.get({nodeId:A.nodeId,visit:A.visit,revision:A.revision,components:v}))}return{get queries(){return v},intent:e,reset(){v={},C.clear()}}}function Yn(t){let{doc:v,holder:C,reviewHolder:e,mountScreenPreview:w}=t,A=!1,s,S=0,d=null,I="",P,$=new Map,ne=o=>o?`${o.id}:${o.nodeId}:${o.visit}:${o.revision}:${o.paywall?.quote?.operationId??""}`:"";async function m(o){if(t.stopped||!t.client.review||A&&o===s&&P?.active)return;let R=!A||o!==s;A||(I=ne(t.client.view),$.set(I,structuredClone(t.answers))),A=!0,s=o,C.hidden=!0,t.suspend(!0),e.hidden=!1;let _=++S;R&&(P?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),P=Ze(e,t.loadingOptions,"funnel",()=>{V()}));let Y=R?P:void 0;try{if(Y?.start(!1,t.client.view?.locale),_!==S||t.stopped)return;let J=t.client.review(o),Q=await(Y?.wait(J,Se)??J);if(t.stopped||_!==S||!A)return;if(!Q.review)throw new y("INVALID_RESPONSE","Historical projection is missing");d?.destroy(),d=null,Y||e.replaceChildren();let E=v.createElement("div"),z=Y?Ke(E,e):()=>{};e.append(E);let k=Q.run.locale.startsWith("zh"),N=t.chrome;E.style.cssText=N.history;let F=v.createElement("p");F.textContent=k?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",F.style.cssText=N.historyTitle,E.append(F);let ce=v.createElement("p");ce.style.cssText=N.historyNote,ce.textContent=Q.review.pages.length?k?"\u9009\u62E9\u4E00\u9875\u67E5\u770B\u5F53\u65F6\u7684\u5185\u5BB9\uFF0C\u56DE\u770B\u4E0D\u4F1A\u6539\u52A8\u4EFB\u4F55\u4FE1\u606F\u3002":"Choose a page to see it as it was. Nothing here can be changed.":k?"\u8FD8\u6CA1\u6709\u53EF\u56DE\u770B\u7684\u9875\u9762\u3002":"There are no earlier pages yet.",E.append(ce);let Pe=Q.review.page?.receiptId,se=v.createElement("div");se.style.cssText=N.historyPages;for(let[G,T]of Q.review.pages.entries()){let i=v.createElement("button");i.type="button",i.textContent=k?`\u7B2C ${G+1} \u9875`:`Page ${G+1}`;let l=Pe!==void 0&&T.receiptId===Pe;i.style.cssText=l?N.primary:N.secondary,l&&i.setAttribute("aria-current","page"),Me(i,()=>t.chrome.focus),i.onclick=()=>{m(T.receiptId)},se.append(i)}if(se.childElementCount&&E.append(se),Q.review.page){let G=Q.review.page,T=v.createElement("div");T.inert=!0,T.style.cssText=N.historyPage,E.append(T),d=w(T,{mode:"live",rendererUrl:t.client.webViewUrl,title:G.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{_===S&&!t.stopped&&Y?.present(z)},onError:l=>{if(_!==S||t.stopped)return;let a=new Error(l);Y?.finish("error",a),d?.destroy(),d=null,E.remove(),t.fail(a)},onEscape:()=>{V()}});let i=d;if(i.update(G.document,Q.run.locale,{serverInput:{bindings:G.inputs,answers:G.answers,values:G.values}}),await i.ready,t.stopped||_!==S||!A)return}let te=k?{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"},me=v.createElement("div");me.style.cssText=N.historyRecords;for(let G of[...Q.review.coupons.map((T,i)=>`${k?"\u4F18\u60E0\u5238":"Coupon"} ${i+1}: ${te[T.status]}`),...Q.review.purchases.map((T,i)=>`${k?"\u8D2D\u4E70":"Purchase"} ${i+1}: ${Jn(T.status,k)}`)]){let T=v.createElement("p");T.textContent=G,T.style.margin="0",me.append(T)}me.childElementCount&&E.append(me),Q.review.page||Y?.present(z),t.client.view&&await t.enqueue(t.client.view)}catch(J){if(_!==S||t.stopped)return;Y?.finish("error",J),d?.destroy(),d=null,e.replaceChildren(),t.fail(J)}}async function V(){if(!A||t.stopped||!t.client.review)return;let o=++S;P?.finish("dismissed");try{if(await t.client.review(),t.stopped||o!==S)return;A=!1,S++,P?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),e.hidden=!0,C.hidden=!1;let R=t.client.view;ne(R)!==I?($.set(I,structuredClone(t.answers)),t.resetScreen()):($.delete(I),t.suspend(!1)),R&&await t.enqueue(R)}catch(R){if(o!==S||t.stopped)return;d?.destroy(),d=null,e.replaceChildren(),t.fail(R)}}return{get active(){return A},get receipt(){return s},open:m,exit:V,get drafts(){return new Map([...$].map(([o,R])=>[o,structuredClone(R)]))},stop(){A=!1,S++,P?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),e.hidden=!0,C.hidden=!1}}}var pn=5e3;async function rt(t,v,C){let e=v,w=e.prepared&&zn(e.prepared),A=()=>{};function s(){e.prepared&&e.prepared.state!=="adopted"&&w?.release()}let S=()=>e.prepared?.state==="shown"&&!!w?.modal,d=e.client.identitySignal,I;try{I=await Promise.all([import("./screen-renderer-YIIT742O.js"),import("./paywall-OAVC654P.js")]),e.signal?.throwIfAborted(),d?.throwIfAborted()}catch(n){throw s(),n}let[{mountScreenPreview:P},{showPaywall:$}]=I,ne=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&e.appManifestRelease?Bn({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;ne?.start();let m=t.ownerDocument,V=Hn(m),o=m.createElement("section"),R=m.createElement("div"),_=m.createElement("div"),Y=m.createElement("div"),J=m.createElement("button");Y.hidden=!0,J.type="button";let Q=m.createElement("p"),E=m.createElement("p"),z=m.createElement("button"),k=m.createElement("button"),N=m.createElement("button"),F=m.createElement("dialog"),ce,Pe=!1;o.dataset.indianaFunnel="",o.dataset.longplayCloseOwner="sdk",o.setAttribute("aria-busy","false"),Q.setAttribute("role","status"),E.setAttribute("role","alert"),E.hidden=!0,z.type=k.type=N.type="button",_.append(z,J,Q,E,N,k),o.append(R,Y,_),t.append(o);let se=Un,te=un(se),me="",G=(m.documentElement.lang||"").startsWith("zh"),T,i="",l;for(let n of[z,J,N,k])Me(n,()=>te.focus);function a(){let n=G?"\u5173\u95ED":"Close";k.parentElement===F?(k.textContent="\xD7",k.setAttribute("aria-label",n),Ln(k,se)):(k.textContent=n,k.removeAttribute("aria-label"),k.style.cssText=te.link+";margin-inline-start:auto")}function b(n){let r=n?.screen?.content.document.theme??se,p=JSON.stringify([r.primary,r.background,r.text,r.radius,r.font,k.parentElement===F]);if(p===me)return;me=p,se=r;let H=k.parentElement===F;te=un(se,H),o.style.cssText=te.root+";min-width:0"+(H?";display:flex;flex-direction:column;min-height:100%":""),_.style.cssText=te.bar+(H?";margin-top:auto":""),z.style.cssText=J.style.cssText=te.secondary,N.style.cssText=te.primary,Q.style.cssText=te.status,E.style.cssText=te.alert,a(),dn(z)}function c(){_.hidden=z.hidden&&J.hidden&&N.hidden&&E.hidden&&!Q.textContent&&(k.hidden||k.parentElement!==_),T?.responsive&&l!==void 0&&T.setContentHeight(l+_.getBoundingClientRect().height)}b();let u=null,q=null,L=null,B="",M="",Ee=!1,Re="",en="",Ue="",h=!1,le=0,$e=!1,fn="",nn=null,tn=Promise.resolve(),mn=!e.client.view,j=C,Te,_e,xe="",Ge,ue=!1,qe=null,he=!1,Qe=()=>e.client.pendingCommand?.operation==="close",de=null,X=null,wn=On({document:m,run:async()=>{(!q?.observing||e.client.pendingCommand)&&await on()},delay:()=>{if(!(h||!L||!["running","waiting"].includes(L.status)&&!e.client.pendingCommand)&&!(q?.observing&&!e.client.pendingCommand))return L.pendingRequest||e.client.pendingCommand?1500:pn},hiddenDelay:()=>!h&&e.client.pendingCommand?15e3:void 0}),K=null;function rn(){return X&&e.client.hasDurableJournal===!0&&K?.acknowledged===!0&&K.operationId===X.operationId&&e.client.view?.id===K.runId&&e.client.view?.status==="closed"&&e.client.view.revision===K.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?X:null}function yn(n){let r=n.run.paywall;if(K&&n.settlement?.requestId===K.requestId&&n.settlement.state==="settled"&&n.settlement.operationId===null&&n.run.id===K.runId&&n.run.status==="closed"&&!n.run.pendingRequest&&n.run.revision===K.revision+1&&n.run.nodeId===K.nodeId&&n.run.visit===K.visit&&r?.receiptId===K.receiptId&&r.selectionGeneration===K.selectionGeneration&&(r.quote?.operationId??null)===K.operationId&&(r.operation?.operationId??r.quote?.operationId??null)===K.operationId){let p=K.operationId===null&&r.selectionGeneration===0&&!r.quote&&!r.operation&&!r.purchaseRequestId,H=Ve({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect});(p||r.canReselect===!0&&H.type==="native")&&(K.acknowledged=!0)}}let De=null,Je=new Set,we={},Ae=!1,pe=(n,r=null)=>{h||(De=r,Ae=!1,E.textContent=$n(n,G),E.hidden=!1,N.hidden=e.client.pendingCommand===null,c(),Ce(e.onError,n))},gn=()=>{h||(De=null,E.textContent=Gn(G),E.hidden=!1,N.hidden=!0,c())};function ke(){let n=e.client.view;if(!n)throw new y("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision}}let O=Yn({client:e.client,doc:m,holder:R,reviewHolder:Y,mountScreenPreview:P,loadingOptions:e,get chrome(){return te},get stopped(){return h},get answers(){return we},suspend(n){q?.setSuspended(n)},resetScreen(){B="",M="",Re=""},enqueue:ye,fail:pe}),Le=jn({client:e.client,expected:ke,fail:pe,get stopped(){return h},get reviewing(){return O.active},get key(){return B},get busy(){return le},get staleRead(){return nn}}),ze=Wn({client:e.client,expected:ke,perform:Fe,onIntent:e.onCustomerDataIntent,get stopped(){return h},get busy(){return le},get document(){return u?.document},get answers(){return we}}),Be=n=>`${n.id}:${n.nodeId}:${n.visit}`,Ne=n=>n&&(n.screen||n.paywall)?Be(n):"";function ve(){let n=e.client.view;z.disabled=!O.active&&(le>0||!!e.client.pendingCommand||!n?.canBack||n.stopped||!["running","waiting"].includes(n.status)||!Ne(n)||M!==Ne(n)),z.hidden=!O.active&&!n?.canBack,dn(z);let r=!!q&&!O.active;k.hidden=r&&!j?.active||Pe&&!O.active,J.hidden=!e.client.review||r&&!n?.canBack,r&&(Q.textContent=""),c()}async function hn(n){if(!n)return;let r=e.client.view;await n;let p=e.client.view;if(!r||!p||p.id!==r.id||p.nodeId!==r.nodeId||p.visit!==r.visit||p.stopped||!["running","waiting"].includes(p.status))throw new y("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Fe(n,r=!1,p){if(!((le||he||de||X)&&!r||h||O.active&&!r)){le++,o.setAttribute("aria-busy","true"),E.hidden=!0,De=null,Ae=!1,ve();try{if(r||await hn(Le.inFlight),h)return;let H=await n();h||await ye(e.client.view??H.run)}catch(H){p?.(H)&&e.client.pendingCommand===null?gn():pe(H,e.client.pendingCommand?.requestId??null)}finally{le=Math.max(0,le-1),o.setAttribute("aria-busy",String(le>0)),h||(N.hidden=e.client.pendingCommand===null,ve())}}}function He(){wn.schedule()}async function on(){if(!(h||$e||le)){if(O.active){await O.open(O.receipt);return}$e=!0;try{let n=e.client.pendingCommand;n&&e.client.settle&&await e.client.settle(n.requestId);let r=e.client.view,p=ze.queries,H=await e.client.get(r?.screen&&Object.keys(p).length?{nodeId:r.nodeId,visit:r.visit,revision:r.revision,components:p}:void 0);Ae&&!h&&(Ae=!1,E.hidden=!0,c()),!h&&p===ze.queries&&await ye(e.client.view??H.run)}catch(n){pe(n),Ae=!h}finally{$e=!1}}}function je(n,r,p){if(j?.active){let ae=j;return ae.setDismissHandler(()=>vn(ae)),ae}let H=Ze(t,e,"funnel",()=>vn(H),Mn);return j=H,H.start(n,r,p),H}function vn(n){h||ue||(ue=!0,n.finish("dismissed"),Ie(),o.hidden=!0,e.client.view?be().finally(ie):ie())}function sn(){clearTimeout(Ge?.timeout),Ge=void 0}function Ie(){Pe=!1,sn(),Te?.abort(),Te=void 0,u?.destroy(),u=null,q?.destroy(),q=null,_e?.(),_e=void 0,F.open&&F.close(),R.replaceChildren(),R.style.cssText="",l=void 0,B="",M="",Ee=!1,Re="",Ue=""}function In(){let n=m.defaultView;T?.responsive&&n&&u?.resizeViewport?.(n.innerHeight,n.innerWidth)}function an(){T?.destroy(),T=void 0,i=""}function We(n){let r=n.screen?.presentation;if(!r||r.type==="inline"){F.open&&F.close(),an(),k.parentElement!==_&&_.append(k),o.parentElement!==t&&t.append(o);for(let ae of["flex","display","flex-direction","justify-content"])R.style.removeProperty(ae);b(n),c();return}o.parentElement!==F&&(F.append(k,o),t.append(F)),R.style.flex="1 0 auto",R.style.display="flex",R.style.flexDirection="column",R.style.justifyContent="center",b(n);let p=n.screen.content.document,H=JSON.stringify([r,me]);if(H!==i){an(),i=H;let ae={sm:420,md:640,lg:900},ge="size"in r&&!r.backdrop?",0 0 0 100vmax #16142566":"";F.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${se.background};color:${se.text};`+(r.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ae[r.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${ge};`+(r.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),T=Sn(F,{presentation:r,theme:p.theme,pages:p.pages},In),T.latch()}c(),F.setAttribute("aria-label",(ce?.screen===n.screen?.content.document.name?ce?.label:void 0)??u?.document?.name??n.screen?.content.document.name??"Funnel")}async function Xn(n){if(h||ue||he&&(Qe()||["running","waiting"].includes(n.status))||(L=n,De&&e.client.pendingCommand?.requestId!==De&&(E.hidden=!0,De=null),G=n.locale.startsWith("zh"),J.textContent=G?"\u56DE\u770B":"History",z.textContent=O.active?G?"\u8FD4\u56DE\u5F53\u524D":"Return to current":G?"\u8FD4\u56DE":"Back",a(),N.textContent=G?"\u91CD\u8BD5":"Retry",N.hidden=e.client.pendingCommand===null,Q.textContent=n.pendingRequest?G?"\u6B63\u5728\u5904\u7406":"Processing":n.instruction?.type==="wait"?G?"\u7B49\u5F85\u4E2D":"Waiting":"",ve(),fn!==`${n.revision}:${n.visit}:${n.status}:${n.stopped}`&&(fn=`${n.revision}:${n.visit}:${n.status}:${n.stopped}`,Ce(e.onState,structuredClone(n))),h||ue))return;if((!n.pendingRequest||he&&n.status==="closed")&&["closed","ineligible","failed"].includes(n.status)){ie();return}if(n.stopped&&S()){ie();return}if(n.stopped||e.client.configurationReady===!1){O.stop(),s(),Ie(),j?.finish("skipped"),o.hidden=!0,He();return}if(o.hidden=!1,O.active){He();return}let r=Ne(n),p=e.client.view;if(p&&p.revision>n.revision&&Ne(p)!==r)return;let H=!n.instruction&&!n.pendingRequest&&n.nodeType==="screen"&&["running","waiting"].includes(n.status);r!==B&&(B&&j?.finish("dismissed"),Ie(),B=r,we={...n.answers},ze.reset());let ae=Be(n);if(xe===ae){o.hidden=!0;return}if(H&&!r){o.hidden=!0;let U=e.prepared?.state==="shown"?null:je(!0,n.locale);!h&&!ue&&Ge?.key!==ae&&(sn(),Ge={key:ae,timeout:setTimeout(()=>{let g=e.client.view;if(h||!U?.active&&e.prepared?.state!=="shown"||!g||Be(g)!==ae)return;xe=ae;let W=new Error("Funnel screen preparation timed out");U?.finish("error",W),s(),Ie(),pe(W)},Se)}),He();return}sn();let Z=U=>{let g=e.client.view;return!h&&!ue&&!qe&&!U.aborted&&e.client.configurationReady!==!1&&!!g&&!g.stopped&&!["closed","ineligible","failed"].includes(g.status)&&Ne(g)===r},ge=(U,g)=>{Z(g)&&(xe=r,j?.finish("error",U),Ie(),o.hidden=!0,pe(U))};if(r||((n.instruction&&n.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(n.status))&&s(),We(n),n.instruction?.type!=="event"&&n.instruction?.type!=="open_url"&&j?.finish("skipped")),n.screen){s();let U=n.screen.content;if(!u){let x=n.screen.presentation.type!=="inline",re=je(x,n.locale);if(h||ue)return;let ee=(Te=new AbortController).signal;We(n),_e=x?Vn(F):Ke(o,t),u=P(R,{mode:"live",closeActions:Array.from(new Set([...e.closeActions??[],...U.document.actions.filter(f=>f.type==="event"&&f.close).map(f=>f.id)])),onAuthoredClose(f){Z(ee)&&(Pe=f,ve())},rendererUrl:e.client.webViewUrl,title:U.document.name,...x?{hostPresentation:()=>T?.type??n.screen.presentation.type}:{},onResize:f=>{l=f,T?.responsive&&T.setContentHeight(f+_.getBoundingClientRect().height)},onAction(f,fe={},tt={}){if(O.active||!Z(ee)||M!==r)return;we={...we,...tt};let ln=n.screen?.inputs??[],Cn=Object.fromEntries(ln.filter(({variable:Oe})=>Object.hasOwn(we,Oe)).map(({variable:Oe})=>[Oe,we[Oe]]));if(Qn(ln,Cn).length){gn();return}Fe(()=>e.client.submit({operation:"submit",...ke(),input:{type:"screen",output:f,answers:Cn,selection:fe}}),!1,Oe=>xn(Oe,ln))},onAnswers:f=>{O.active||!Z(ee)||M!==r||(we={...we,...f})},onCustomerDataIntent:f=>{O.active||!Z(ee)||M!==r||ze.intent(f).catch(pe)},onEscape:()=>{!Z(ee)||M!==r||O.active||de||X||be()},onError:f=>{let fe=new Error(f);M===r?pe(fe):ge(fe,ee)},onRendered:f=>{if(!(!Z(ee)||M===r))try{re.present(fe=>{_e?.(),_e=void 0,f&&(ce={screen:U.document.name,label:f},F.setAttribute("aria-label",f)),x&&(F.showModal(),T?.responsive&&F.focus({preventScroll:!0}),!fe&&e.loading!=="host"&&_n(F,T?.type??n.screen.presentation.type,T?.responsive)),M=r,Ee=x,ve()}),Z(ee)&&Le.report(r)}catch(fe){ge(fe,ee)}}}),In()}let g={capabilities:n.screen.capabilities,customerData:n.screen.customerData,parameters:n.parameters,serverInput:{bindings:n.screen.inputs,answers:we,values:n.screen.values}},W=JSON.stringify([U,n.locale,g.parameters,n.screen.inputs,n.screen.values]);if(W!==Re)u.update(U.document,n.locale,g),Re=W,en=JSON.stringify(g.capabilities),Ue=JSON.stringify(g.customerData);else{let x=JSON.stringify(g.capabilities);x!==en&&(u.updateCapabilities(g.capabilities),en=x),JSON.stringify(g.customerData)!==Ue&&(u.updateCustomerData(g.customerData),Ue=JSON.stringify(g.customerData))}let oe=u;if(oe)try{await(j?.wait(oe.ready)??oe.ready)}catch(x){Te&&ge(x,Te.signal)}}else if(n.paywall&&!q){let U=n.paywall.resolution,g="document"in U?U.document:null,W=w,oe=null,x=(Te=new AbortController).signal,re={loading:"host",signal:x,canInteract:()=>Z(x)&&!O.active&&!de&&!X,beforeAction:async()=>{le++;try{await hn(Le.settled()),E.hidden=!0,De=null,Ae=!1,c()}finally{le=Math.max(0,le-1)}},start:()=>cn(e.client),onObservationChange:He,onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,resumeCheckout:e.resumeCheckout,allowNewPurchase:e.allowNewPurchase,checkoutNavigation:e.checkoutNavigation,terminateCheckout:e.terminateCheckout,confirmOnHostedCheckout:e.confirmOnHostedCheckout,resolveOfferId:e.resolveOfferId,claimCoupon:e.claimCoupon,onEvent:e.onEvent,onOpenUrl:f=>e.onOpenUrl?e.onOpenUrl({receiptId:n.paywall.receiptId,url:f,openIn:"same_window"}):m.defaultView?.location.assign(f),onAction:async f=>{if(O.active)return;let fe=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:e.client.view?.revision??n.revision,input:{type:"screen",output:f,answers:{}}});await ye(e.client.view??fe.run)},onError:f=>{M===r?pe(f):ge(f,x)}},ee={quoteError:f=>Ce(e.onError,f),present(f){Z(x)&&(oe?.present(()=>{f(),M=r,Ee=!!R.querySelector("dialog[open]"),ve()}),Z(x)&&Le.report(r))},async dismiss(){if(!(h||x.aborted||O.active||de||X||!he&&!Z(x))){if(he=!0,(e.resumeCheckout||e.terminateCheckout)&&nt()){L=e.client.view,ie();return}await be()}}};if(W){let f=await W.adopt(n,{options:re,handoff:ee,start:()=>cn(e.client)});f&&Z(x)&&!h?(We(n),q=f,j?.active&&j.present(()=>{}),M=r,Ee=W.modal,ve(),Le.report(r),O.active&&q.setSuspended(!0)):(f?.destroy(),s())}if(h||ue)return;if(!q){if(oe=je(!0,n.locale,g),h||ue)return;We(n);let f=await $(R,re,ee).catch(fe=>(ge(fe,x),null));!Z(x)&&!(he&&!h&&!x.aborted)?f?.host?.destroy():f&&(q=f.host,q?.setSuspended(O.active))}}if(h||ue)return;ve();let D=n.instruction;if(D&&(D.type==="open_url"||D.type==="event")&&!Je.has(D.receiptId)){let U=m.createElement("button");U.type="button",U.style.cssText=te.primary,Me(U,()=>te.focus),R.style.cssText=te.stage,U.textContent=D.type==="open_url"?`${G?"\u524D\u5F80":"Continue to"} ${new URL(D.url).host}`:G?"\u7EE7\u7EED":"Continue",U.onclick=()=>{let g=ke(),W=D.type==="open_url"&&!e.onOpenUrl&&D.openIn==="new_window"?Zn(D.url):null;Fe(async()=>{let oe="success";if(D.type==="open_url")if(e.onOpenUrl)try{oe=await e.onOpenUrl({receiptId:D.receiptId,url:D.url,openIn:D.openIn})===!1?"failed":"opened"}catch(re){Ce(e.onError,re),oe="failed"}else oe=D.openIn==="new_window"&&!W?"failed":"opened";if(D.type==="event"){if(!e.onEvent)throw new y("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(D.event)}if(h||e.client.view?.nodeId!==g.nodeId||e.client.view.visit!==g.visit)throw new y("PRECONDITION_FAILED","The client action visit changed");let x=await e.client.submit({operation:"submit",...g,input:{type:"client_action",receiptId:D.receiptId,outcome:oe}});return Je.add(D.receiptId),D.type==="open_url"&&!e.onOpenUrl&&D.openIn==="same_window"&&m.defaultView?.location.assign(D.url),x})},j?.active?j.present(()=>R.replaceChildren(U)):R.replaceChildren(U)}!n.pendingRequest&&n.status==="completed"&&!Je.has(`complete:${n.id}`)&&(Je.add(`complete:${n.id}`),Ce(e.onComplete,structuredClone(n))),He()}function Zn(n){let r=m.defaultView?.open(n,"_blank")??null;return r&&(r.opener=null),r}function ye(n){return ve(),tn=tn.catch(()=>{}).then(async()=>{try{await Xn(n)}catch(r){throw j?.active&&(xe=Be(n),j.finish("error",r),Ie(),o.hidden=!0),r}}),tn}let Kn=e.client.subscribe(n=>{if(!mn){if(n.stopped&&(Ee||S())&&!he){L=n,ie();return}!he&&(n.stopped||e.client.configurationReady===!1||B&&M!==B&&(Ne(n)!==B||["closed","ineligible","failed"].includes(n.status)))&&(Ie(),j?.finish("dismissed"),o.hidden=!0),ye(n).catch(pe)}}),et=e.client.subscribeError?.(pe);function nt(){let n=e.client.view,r=n?.paywall;return!!r?.operation&&!!n&&["running","waiting"].includes(n.status)&&Dn(Ve({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect}))}function be(n){if(qe)return qe;if(h||!n&&(de||X))return Promise.resolve();let r=!n&&Qe();return!r&&e.client.view&&!["running","waiting"].includes(e.client.view.status)?(L=e.client.view,ie(),Promise.resolve()):(qe=Fe(async()=>{let p=r?await e.client.retry():await e.client.submit({operation:"close",...n??ke()});return n&&yn(p),p},!0).then(()=>{let p=e.client.view;p?.status==="closed"&&!Qe()&&(L=p,ie())}).finally(()=>{qe=null}),qe)}function ie(){ne?.destroy(),!h&&(h=!0,A(),s(),e.signal?.removeEventListener("abort",ie),d?.removeEventListener("abort",ie),j?.finish("dismissed"),wn.destroy(),Kn(),et?.(),Ie(),an(),O.stop(),F.remove(),o.remove(),V(),Ce(e.onDismiss,L?structuredClone(L):null))}z.onclick=()=>{if(!z.disabled){if(O.active){O.exit();return}Fe(()=>e.client.submit({operation:"back",...ke()}))}},J.onclick=()=>{O.open()},k.onclick=()=>{j?.active?j.dismiss():de||be()},N.onclick=()=>{Qe()?be():Fe(()=>e.client.retry())},F.addEventListener("cancel",n=>{n.preventDefault(),j?.active?j.dismiss():de||be()}),e.signal?.addEventListener("abort",ie,{once:!0}),d?.addEventListener("abort",ie,{once:!0});let Ye=!1;w&&(A=w.onClose(()=>{h||ue||(ue=!0,j?.finish("dismissed"),Ie(),o.hidden=!0,e.client.view?be().finally(ie):Ye=!0)}));let bn={destroy:ie,refresh:on,get recovery(){let n=rn();if(n)return n;if(!h&&!le&&!he&&!de&&q){let r=q.recovery;if(r.type!=="native")return r}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??X?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(de)return de;let n=rn();if(n)return Promise.resolve(n);let r=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??X?.operationId??null,p=()=>({type:"recover",operationId:r,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let D=q?.recovery;return Promise.resolve(D&&D.type!=="native"&&D.type!=="cancel"?D:p())}let H=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(D=>D.operation==="close");if(h&&!(H||X&&e.client.view?.status==="closed")||le||$e||qe||O.active||!q&&!X&&!H)return Promise.resolve(p());let ae=q,Z=(async()=>{try{if(!X&&H){let g=await e.client.retry();return await ye(e.client.view??g.run),p()}if(!X){let g=await ae.prepareFallback();if(g.type!=="native")return g;if(e.client.hasDurableJournal!==!0)return p();X=g}let D=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(D.length){let g=D.find(oe=>oe.operation==="close");if(!g||!K||g.requestId!==K.requestId)return p();let W=await e.client.retry();yn(W),await ye(e.client.view??W.run)}else{let g=e.client.view,W=g?.paywall;if(!g||!W||W.selectionGeneration===void 0||(W.quote?.operationId??null)!==X.operationId||X.operationId!==null&&W.canReselect!==!0)return p();let oe=W.selectionGeneration,x=await e.client.get();await ye(e.client.view??x.run);let re=e.client.view,ee=re?.paywall;if(!re||!ee||!["running","waiting"].includes(re.status)||re.stopped||re.id!==g.id||re.nodeId!==g.nodeId||re.visit!==g.visit||ee.receiptId!==W.receiptId||ee.selectionGeneration!==oe||(ee.quote?.operationId??null)!==X.operationId||X.operationId!==null&&ee.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return p();let f=ke();K={runId:re.id,operationId:X.operationId,revision:f.revision,requestId:f.requestId,nodeId:re.nodeId,visit:re.visit,receiptId:ee.receiptId,selectionGeneration:oe,acknowledged:!1},await be(f)}let U=rn();return U?(ie(),U):p()}catch(D){return pe(D),p()}})();de=Z;let ge=()=>{de===Z&&(de=null)};return Z.then(ge,ge),Z},review:O.open,exitReview:O.exit,get unappliedDrafts(){return O.drafts}};try{let n=e.client.view;if(n)((e.client.viewAgeMs??pn)>=pn||n.instruction?.type==="evaluate_segment")&&(nn=on().finally(()=>{nn=null})),await ye(n);else{if(o.hidden=!0,h)throw new DOMException("Presentation cancelled","AbortError");let r=Ye||e.prepared?.state==="shown"?null:je(e.client.view?.screen?.presentation.type!=="inline",e.client.view?.locale);if(h||ue&&!Ye)throw new DOMException("Presentation cancelled","AbortError");let p=e.client.get(),H=await(r?r.wait(p,Se):ot(p,Se));if(mn=!1,Ye)return h||await be().finally(ie),bn;await ye(e.client.view??H.run)}}catch(n){throw j?.finish("error",n),ie(),n}return bn}function ot(t,v){let C;return Promise.race([t,new Promise((e,w)=>{C=setTimeout(()=>w(new Error("Presentation data timed out")),v)})]).finally(()=>clearTimeout(C))}function Gt(t,v,C){return rt(t,v,C)}export{rt as a,Gt as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as ue,g as se}from"./chunk-4KLXQKNO.js";import{b as on}from"./chunk-W74JLL2O.js";import{d as tn,e as pe}from"./chunk-ECKVJGXQ.js";import{c as Be,d as Ke,e as J,l as nn}from"./chunk-GH6FM44P.js";import{$ as de,A as $e,E as Ye,S as Ze,X as We,Y as Xe,Z as $,_ as en,a as j,aa as U,b as qe,c as Me,d as je,e as G,f as Ge,g as Ue,i as X,w as ee,x as ze,y as Je}from"./chunk-YV6UFESO.js";import{b as an}from"./chunk-3NCMYTNG.js";import{b as ne}from"./chunk-7XDQKZYA.js";import{a as W}from"./chunk-XJRDO3NI.js";import{$ as Qe,I as L,J as De,K as Le,Z as He,_ as le,aa as ce,g as Oe,m as Ae,q as Te,z as ae}from"./chunk-WZMZMJCK.js";import{b as D}from"./chunk-HEHLFHW7.js";import{a as f}from"./chunk-U7NX5ET2.js";import{b as rn}from"./chunk-AHUYZ6IW.js";import{b as n}from"./chunk-CR2XJ2CX.js";import{c as _e,d as ke,e as Ve,f as z}from"./chunk-O4KXODTJ.js";import{a as Pe,b as Ne}from"./chunk-CILM5XMH.js";function un(e){return Cn({...e,namespace:"commands",identity:[e.runToken]})}function Cn(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let d=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??rn).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",d));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,o=>o.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function p(d){try{let a=await i;return await u.request(a,{mode:"exclusive"},()=>d(a))}catch(a){throw a instanceof f?a:r()}}function c(d){let a=t.getItem(d);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let o=JSON.parse(a);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw r();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(c),write:(d,a)=>p(o=>{if(c(o).revision!==d)return null;if(!Number.isSafeInteger(d+1))throw r();let y=JSON.stringify({revision:d+1,entry:a});if(y.length>1048576)throw r();return t.setItem(o,y),d+1})}}var sn=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var q=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Pn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Nn=n.discriminatedUnion("type",[Ye,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:q.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:We,openIn:Xe}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:q})]),On={id:q,presentation:Te,outputs:n.array(q).max(250),inputs:ce,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Oe,customerData:Ae,dataCursors:n.record(q,He.nullable())},An=n.strictObject({...On,content:n.strictObject({type:n.literal("document"),document:ae})}),me=n.strictObject({id:n.uuid(),source:sn,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:q,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Pn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:le,parameters:Qe,variables:n.record(n.string(),L),output:L.nullable(),screen:An.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([tn,pe]),quote:ue.nullable(),operation:se.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Nn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),Tn=n.strictObject({scope:D,run:me,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:ue.nullable(),operation:se.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative(),document:ae,answers:le,inputs:ce,values:n.record(n.string(),L).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),ln=Tn.extend({run:me.extend({paywall:me.shape.paywall.unwrap().extend({resolution:pe}).nullable()})});var cn="X-Indiana-Server-Key";var H=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fe(e,t,u){let r={},i,p,c,d="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let o=e.cases.findIndex(g=>ke(t.attributes??{},g.condition,t.savedGroups??{}));d=o<0?"default":`case:${o}`,a=o<0?e.default:e.cases[o].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new H("Required GB Feature is unavailable");i=z(e.featureKey,t),c=i.value,Object.assign(r,G(e,{value:c})),a=e.next;break;case"split":{let o=u[e.experimentId];if(!o)throw new H("Required GB Experiment is unavailable");if(p=Ve(o,t),c=p.value,d=p.inExperiment&&!p.passthrough&&typeof c=="string"?c:"notParticipating",a=d==="notParticipating"?e.notParticipating:e.routes[d],!a)throw new H("Experiment Variation has no published route");break}case"offering":{let o=e.configuration.source==="fixed"?e.configuration.versionId:z(e.configuration.featureKey,t).value;c={type:"offering_version",id:n.uuid().parse(o)},Object.assign(r,G(e,{value:c})),a=e.next;break}case"coupon":case"coupons":c=e.type==="coupons"?e.couponIds.map(o=>({type:"reward",id:o})):{type:"reward",id:e.couponId},Object.assign(r,G(e,{value:c})),a=e.next;break}return{port:d,target:a,projections:r,...c===void 0?{}:{value:c},...i?{feature:i}:{},...p?{experiment:p}:{}}}function dn(e,t,u){n.uuid().parse(e),n.number().int().nonnegative().parse(t);let r=Pe(Ne(new TextEncoder().encode(JSON.stringify([e,t,u])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var _n=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),kn=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(_n).max(200).default([]),iam:ze.optional(),renderGuard:ee.optional()}),ge=kn.omit({variation:!0,description:!0,iam:!0}),Vn=Be.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20)}),pn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(Vn).max(100),savedGroups:Ke});var Q=n.string().regex(/^[a-f0-9]{64}$/),jt=n.strictObject({iam:Q,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Dn=n.strictObject({release:Q,render:ee,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),Gt=n.strictObject({scope:D.extend({environmentId:n.uuid()}),release:Q,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),delivery:Je.optional(),target:Dn})).max(4e3)}),Ut=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:Q,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Bt=n.strictObject({scope:D,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Kt=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Ln=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),ye=n.strictObject({operation:n.literal("page_experiments"),release:Q,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(W).optional()}),mn=n.strictObject({scope:D,runId:n.uuid(),assignments:n.array(Ln.extend({receiptId:n.uuid()})).max(100),payload:pn});var B=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),gn=n.strictObject({entry:B,nodes:n.array(n.strictObject({id:B,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),B),writes:n.record(j,j),resources:n.strictObject({screenId:B.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),fn={scope:D,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:gn},te=n.discriminatedUnion("evaluationMode",[n.strictObject({...fn,evaluationMode:n.literal("local"),growth:J,conditions:n.record(B,n.array(n.strictObject({condition:Le,port:n.string()})))}),n.strictObject({...fn,evaluationMode:n.literal("remote")})]),qn=te.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,Me),outputSchema:qe,terminals:n.record(B,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Ze.nullable()}))})});function Mn(e){return gn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(c=>c.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,c)=>{u[`case:${c}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ve(e){let t=de.parse(e.document),u=e.evaluationMode==="local"?J.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:Mn(t)};return te.parse(e.evaluationMode==="remote"?r:{...r,growth:nn(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((p,c)=>({condition:p.condition,port:`case:${c}`}))]))})}function er(e){let t=ve(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=de.parse(e.document);return qn.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var he=32,jn=522240;function we(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var Gn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),Ie=n.record(n.string(),L),Un=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:$.shape.schemaVersion,kind:$.shape.kind,selector:$.shape.selector,contract:$.shape.contract}),context:Ie,removed:n.array(n.string()).max(100),attributes:Ie,removedAttributes:n.array(n.string()).max(100),result:en,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),ar=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:Gn,context:Ie,steps:n.array(Un).min(1).max(he)}).refine(e=>X(e)<=jn,"Segment exceeds its byte budget");var Bn=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Y(e){return Array.isArray(e)?e.some(Y):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Y(u):!Bn.test(t))}function yn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(d=>d.id===t.screenId&&d.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(d=>Y(d.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(d=>d.id===t.screenId):null]);for(let[d,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${d}`)||p.includes(JSON.stringify(d))))return"customer_required";if(t.type==="split"){let d=u.experiments?.[t.experimentId];if((d?.hashAttribute??"id")!=="funnelParticipantId"||Y(d?.condition)||d?.parentConditions?.length)return"customer_experiment_required"}let c=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return c&&u.features?.[c]?.rules?.some(d=>(d.hashAttribute??"id")!=="funnelParticipantId"||Y(d.condition)||d.parentConditions?.length)?"customer_experiment_required":null}var be=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},re=(e,t)=>new be(e,t),Kn=e=>({experiments:e.experiments,features:e.features});function xe(e,t=re){let u=new Map(e.topology.nodes.map(c=>[c.id,c])),r=_e(e.growth.savedGroups),i=Kn(e.growth);function p(c,d){if(!Object.hasOwn(e.growth.features,c))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return z(c,d).value}return{nodes:u,savedGroups:r,features:i.features,feature:p,evaluate(c,d){let a=u.get(c);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let o,g;if(a.type==="condition"){let I=e.conditions[a.id];if(!I)throw t("INVALID_RESPONSE","Local condition rules are unavailable");o=fe({id:a.id,name:a.id,type:"condition",cases:I.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},d,i.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,d),o="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=fe({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},d,i.experiments);g=h.value,o=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,d),o=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[o]??(o==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:c,port:o,target:y,...g===void 0?{}:{value:g}}}}}function hr(e,t,u,r=re){return Re(e,r)(t,u)}function Re(e,t){let u=te.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let p=xe(u,t);return(c,d)=>(i(),zn(p,c,d))}function zn(e,t,u){let r=De.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:p,onExperimentViewed:c}=u,d={attributes:r,...i?{saveStickyBucketAssignmentDoc:a=>i(structuredClone(a))}:{},...p?{onFeatureUsage:(a,o)=>p(a,structuredClone(o))}:{},...c?{onExperimentViewed:(a,o)=>c(structuredClone(a),structuredClone(o))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,d)}function wr(e,t,u,r=re){return vn(Re(e,r),t,u)}function vn(e,t,u){let r=[],i=[],p=[],c=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(d){let a=r.findIndex(y=>y.next.attributeName===d.attributeName&&y.next.attributeValue===d.attributeValue),o=d.attributeName+"||"+d.attributeValue,g={expected:u.sticky[o]??null,next:d};a<0?r.push(g):r[a]=g},onExperimentViewed(d,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&i.push(L.parse({key:d.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(d,a){p.push(L.parse({feature:d,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:c.port,...c.value===void 0?{}:{value:c.value},sticky:r,exposures:i,features:p}}function In(e,t,u,r=re){let i=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),c=structuredClone(u.variables),d=structuredClone(i.sticky),a=[],o=u.nodeId,g=u.visit,y=!1,I,h=O=>yn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),b=O=>(I??=Re(e,r),vn(I,O,{attributes:$e({declarations:t.variables,attributes:i.attributes,parameters:u.parameters,answers:u.answers,results:c,savedGroups:{}}),sticky:d}));for(let O=0;O<he;O++){let s=p.get(o);if(!s||!we(s)||h(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let m,x;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")m=b(s.id),s.type==="offering"&&(m.value={type:"offering_version",id:String(m.value)}),s.type==="condition"?x=m.port==="default"?s.default:s.cases[Number(m.port.slice(5))]?.target:s.type==="split"?x=m.port==="notParticipating"?s.notParticipating:s.routes[m.port]:(s.type==="feature"||s.type==="offering")&&(x=s.next);else if(m={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(x=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(m.value={type:"offering_version",id:s.configuration.versionId},x=s.next),s.type==="end"||s.type==="output"){let R=s.type==="end"?s.output:s.value;if(m=R?.type==="feature"?b(s.id):{...m,port:"value",value:R?.type==="literal"?R.value:R?.type==="variable"?Ue({source:"variable",key:R.key,...R.path?{path:R.path}:{}},{declarations:t.variables,answers:u.answers,results:c,parameters:u.parameters,attributes:i.attributes,savedGroups:{}}):null},R&&(m.value===void 0||!je(t.outputSchema,m.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let C=[...a,{nodeId:o,result:m}];if(X({steps:C})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:o,result:m}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let R=s.type==="coupons"?s.couponIds.map(V=>({type:"reward",id:V})):s.type==="coupon"?{type:"reward",id:s.couponId}:m.value;if(R===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=G(s,{value:R});Ge(t.variables,s,_),Object.assign(c,_)}for(let R of m.sticky)d[`${R.next.attributeName}||${R.next.attributeValue}`]=structuredClone(R.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");o=x,g++}let T=p.get(o);return{steps:a,...!y&&T&&(!we(T)||h(T))?{boundary:{nodeId:o,visit:g}}:{}}}function hn(e,t){let u=ln.safeParse(t);if(!u.success)throw new f("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new f("SCOPE_MISMATCH","Funnel scope changed");return r}var Se=(e,t)=>new f(e,t);function Cr(e){return xe(e,Se)}var Jn=3,$n=2e3;function Hn(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Qn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Jn||!Hn(u))throw u;await new Promise(r=>setTimeout(r,t*$n))}}async function Fe(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let i=null,p;if(u)try{let c=await e.funnel(t.source.id,t.source.versionId);p=c.manifest.generation,i=Yn(e,t,c)}catch{i=null}return p??=e.snapshot?.generation??(await Qn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:i}}function Yn(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:p,...c}=u.growth,d=ve({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:J.parse(c)}),a=Zn(d,u.document,{...t,...r}),o=a.steps.at(-1),g=a.boundary??(o?.result.port==="value"?{nodeId:o.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Zn(e,t,u){return In(e,t,u,Se)}var wn=U.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),bn=n.strictObject({schemaVersion:n.literal(1),scope:D,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:wn.optional(),closeCommand:wn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),A=()=>new f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),oe=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Z(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function xn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),i=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:bn.parse(a.entry)}}function c(a){let o=i.then(a);return i=o.catch(()=>{}),o}async function d(a){for(let o=0;o<4;o++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(oe(g.entry,y)){t=g.revision;return}let I=await e.write(g.revision,y);if(I!==null){if(!Number.isSafeInteger(I)||I<=g.revision)throw A();t=I;return}}throw A()}return{bind(a){let o=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==o)throw A();u=o},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let o=bn.parse(a),g=o.command;return!g||u!==null&&r(o)!==u?Promise.reject(A()):(u??=r(o),c(()=>d((y,I)=>{if(y&&!oe(r(y),r(o)))throw A();if(y&&o.processBindingIds){for(let[h,b]of Object.entries(o.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==b)throw A();y={...y,processBindingIds:{...y.processBindingIds,...o.processBindingIds}}}if(!y){if(I!==t&&g.operation!=="close")throw A();return o}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!oe(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!oe(y.command,g))throw A();return y})))},observePurchase(a,o,g,y){return c(()=>d((I,h)=>{if(!I&&h!==t||I&&r(I)!==r({...a,schemaVersion:1}))throw A();if(I?.purchase&&I.purchase.generation>o.generation)return Z(I,y);if(I?.purchase&&I.purchase.generation===o.generation&&I.purchase.operationId!==o.operationId)throw A();return g?!I?.purchase||I.purchase.operationId!==o.operationId?Z(I,y):Z(I.command?{...I,purchase:void 0}:null,y):Z({schemaVersion:1,...a,...I,purchase:o},y)}))},settle(a){return c(()=>d(o=>Z(o,a)))}}}function jr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function ie(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,p)=>ie(i,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([i,p])=>Object.hasOwn(t,i)&&ie(p,Reflect.get(t,i)))}function Rn(e,t){let u=t&&{...t},r=null,i=0,p=-1,c=0,d=new AbortController;function a(){c++,d.abort(new f("IDENTITY_CHANGED","Run identity changed")),d=new AbortController}let o=!1,g,y=0,I=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new f("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===c?r:null},get viewAgeMs(){return r&&p===c?performance.now()-i:void 0},get generation(){return c},get signal(){return d.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,b="Run identity changed during the request"){if(h!==c||o)throw new f("IDENTITY_CHANGED",b)},assertRun(h){if(r&&(h.id!==r.id||h.source.type!==r.source.type||h.source.id!==r.source.id||h.source.versionId!==r.source.versionId||h.locale!==r.locale||!ie(h.parameters,r.parameters)))throw new f("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new f("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,b,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&b.run.revision<=r.revision)&&!(r&&b.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!b.run.stopped&&["running","waiting"].includes(b.run.status)&&r&&p===c&&b.run.nodeId===r.nodeId&&b.run.visit===r.visit&&b.run.revision===r.revision&&(b.run.screen=r.screen,(r.paywall?.quote?.operationId===b.review?.activeOperationId||!r.paywall?.quote&&b.review?.activeOperationId===null)&&(b.run.paywall=r.paywall)),!(r?.paywall&&b.run.paywall&&r.paywall.receiptId===b.run.paywall.receiptId&&(b.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||b.run.revision>=r.revision)r=b.run,i=performance.now(),p=c;else if(!s)return;if(r&&p===c)for(let m of I)try{m(structuredClone(r))}catch{}}},identify(h){if(o)throw new f("IDENTITY_CHANGED","Controller was reset");if(!W.test(h))throw new f("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return I.add(h),()=>I.delete(h)},reset(){o||(o=!0,a(),g=void 0,r=null,I.clear())}}}var Ee=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function $r(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Ee.test(e))throw new f("INVALID_TOKEN",u)}function Hr(e){let t=ne(e);return t.identify(e.apiKey),t}function Sn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&["apple","google"].includes(t.provider)?"native":t?.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function M(e){let{customerToken:t,...u}=e;return u}var Wn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Fn({journal:e,state:t,call:u,processIdentity:r}){let i=null,p=null,c=!1,d={command:null,close:null},a=new Set,o,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new f("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=s.purchase,c=s.closed===!0,!s.command)return;let m=s.command;i=m.operation==="close"?null:m,p=m.operation==="close"?m:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(c=!0);for(let x of[i,p])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function I(s){e&&await y;let m=t.generation;if(e){if(!t.view||!t.scope)throw new f("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:M(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(m!==t.generation||i!==s&&p!==s)throw new f("IDENTITY_CHANGED","Run changed before command dispatch");let x=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(C){let R=s.operation==="submit"&&s.input.type==="paywall_quote",_=!x&&!Wn(C),V=!1;if(R&&_&&m===t.generation&&i===s&&C instanceof f&&C.status!==void 0){let l=await T(s.requestId).catch(()=>{});V=l?.settlement?.state==="unknown"&&l.settlement.operationId===null}throw m===t.generation&&(i===s||p===s)&&_&&(!R||!(C instanceof f)||C.status===void 0||V)&&(e&&await e.settle(s.requestId),m===t.generation&&O(s)),C}}function h(s){let m=U.parse(s);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new f("INVALID_REQUEST","Mutation required");if(c&&m.operation!=="close"){if(i?.requestId===m.requestId)return T(m.requestId);throw new f("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"){if(i?.requestId===m.requestId)throw new f("INVALID_REQUEST","Close requires its own request identity");if(c=!0,p&&JSON.stringify(M(p))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original Close");return p??=m,d.close?d.close:b(p,"close")}if(i){if(JSON.stringify(M(i))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original command before sending another");if(d.command)return d.command}else i=m;return b(i,"command")}function b(s,m){let x=I(s);d[m]=x;let C=()=>{d[m]===x&&(d[m]=null)};return x.then(C,C),x}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||i!==s&&p!==s?!1:(i===s&&(i=null),p===s&&(p=null),a.delete(s.requestId),!i&&!p&&(g=null),!0)}return{ready:y,get pending(){return i},get closing(){return p},get closeRequested(){return c},get inFlight(){return d.command},get closeFlight(){return d.close},get purchase(){return o},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new f("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,m,x,C){let R=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=R&&m.settlement?.state==="settled"&&m.run.pendingRequest?.requestId!==R&&(s.operation==="get"||!c||s.operation==="close"||!["running","waiting"].includes(m.run.status))?R:void 0,V=i?.requestId===_?i:p?.requestId===_?p:void 0;e?.bind({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId});let l=m.run.paywall,v=l??m.purchase,P=v?.operation,E=m.settlement&&(!l||l.purchaseRequestId===m.settlement.requestId)&&(!o||o.operationId===m.settlement.operationId)?m.settlement:void 0,S=P?.operationId??v?.quote?.operationId??E?.operationId,F=v?.receiptId??E?.receiptId,w=l?.selectionGeneration??o?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||m.run.revision>=t.view.revision)&&(C===void 0||C>=t.readSequence)&&(!o||w>=o.generation)){let N={receiptId:F,operationId:S,generation:w},k=an(P,v?.canReselect===!0);await e.observePurchase({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId},N,k,_),t.assertCurrent(x),(!o||N.generation>=o.generation)&&(C===void 0||C>=t.readSequence)&&(k?o?.operationId===N.operationId&&(o=void 0):o=N)}else e&&_&&await e.settle(_);return t.assertCurrent(x),_?O(V):!1},stop(){c=!0},submit:h,settle:T,reset(){c=!0,i=null,p=null,o=void 0,g=null,d.close=null,a.clear(),d.command=null}}}function Xn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Ee.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=ne({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),i=Rn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(b),c=null,d=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?un(e):void 0),a=d&&xn(d),o=Fn({journal:a,state:i,call:T,processIdentity:e.process}),g=0,y=new Map;function I(){g++,y.clear(),t=void 0}async function h(l){let v=l.operation==="resume"?o.pending?.operation==="resume"?null:o.pending:l;if(u&&l.operation==="resume"&&!v&&l.requestId!==e.customerRun?.startRequestId)throw new f("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(v?.operation==="submit"&&v.input.type==="paywall_confirm"){let N=i.view?.paywall;Sn(u,N?.quote?.operationId===v.input.operationId?N.quote:void 0)}if(e.process)return e.process.request(l);let P=i.generation;i.assertCurrent(P);let E=performance.now()+(e.timeoutMs??35e3),S=i.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let N=i.signal,k,K=()=>{},En=new Promise((et,Ce)=>{K=()=>Ce(N.reason),N.addEventListener("abort",K,{once:!0}),k=setTimeout(()=>Ce(new f("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(i.assertCurrent(P),e.session.access())),En])}finally{clearTimeout(k),N.removeEventListener("abort",K)}}i.assertCurrent(P);let F={...l,...S?{customerToken:S}:{}},w=l.operation==="page_experiments"?ye.parse(F):U.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new f("IDENTITY_CHANGED","Original recovery Customer changed");let N={...w};return"customerToken"in N&&delete N.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:N},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",w,e.runToken,{headers:e.serverKey&&!S?{[cn]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function b(){I(),p?.(),i.reset(),o.reset(),c=null,r.dispose()}async function T(l,v){let P=t;t=void 0;let E=i.generation,S=()=>i.assertCurrent(E);a&&await o.ready,S();let F=i.view,w=hn(e,P!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?P:await h(l));if(l.operation==="review"&&!w.review)throw new f("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&w.run.id!==e.customerRun.runId)throw new f("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&w.purchase&&(w.purchase.receiptId!==l.purchase.receiptId||(w.purchase.operation?.operationId??w.purchase.quote?.operationId)!==l.purchase.operationId))throw new f("INVALID_RESPONSE","The requested original purchase changed");if(S(),w.runToken&&w.runToken!==e.runToken)throw new f("INVALID_RESPONSE","Run credential changed");let N=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(N&&w.settlement?.requestId!==N)throw new f("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(w),i.assertRun(w.run),i.bindScope(w.scope);let k=await o.observe(l,w,E,v);return(!i.view||w.run.revision>=i.view.revision)&&(v===void 0||v>=i.readSequence)&&(await e.onAcceptedResponse?.(w),S()),!w.run.stopped&&["running","waiting"].includes(w.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(w.run.status)||o.stop(),i.publish(l,w,F,v,k)),w}function O(l){let v=i.generation;I();let P=l(),E=()=>{i.generation===v&&I()};return P.then(E,E),P}let s=l=>O(()=>o.submit(l)),m=null,x=new WeakMap;function C(l){let v=x.get(l);if(v)return v;let P=_(l);return x.set(l,P),P}let R=!1;async function _(l){let v=await l;if(v.run.instruction?.type!=="evaluate_segment")return v;if(m)return m;R=!0;let P=i.generation,E=(async()=>{for(let S=0;S<32&&v.run.instruction?.type==="evaluate_segment";S++){if(o.pending||o.closeRequested)return v;let F=v.run;if(v.run.instruction?.type==="evaluate_segment"){let{advance:N}=await Fe(e.configuration,F,{predict:!1});if(P!==i.generation)throw new f("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return v;if(i.view&&(i.view.revision!==F.revision||i.view.visit!==F.visit||i.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Fe(e.configuration,F).then(({prediction:K})=>{k&&P===i.generation&&!o.closeRequested&&i.view?.id===F.id&&!i.view.stopped&&i.view.nodeId===F.nodeId&&i.view.visit===F.visit&&i.view.revision===F.revision&&(c=K)}).catch(()=>{});try{v=await s({operation:"commit_segment",requestId:dn(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...N})}finally{k=!1,c=null}}}return v})();m=E;try{return await E}finally{m===E&&(m=null)}}let V={get configuration(){return R?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=i.currentView;return l?structuredClone(l):null},get viewAgeMs(){return i.viewAgeMs},get pendingCommand(){let l=o.closing??o.pending;return l?structuredClone(M(l)):null},get pendingCommands(){return[o.pending,o.closing].filter(l=>l!==null).map(l=>structuredClone(M(l)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=i.view;return c&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===c.runId&&l.nodeId===c.from.nodeId&&l.visit===c.from.visit&&l.revision===c.from.revision&&!o.closeRequested?structuredClone(c):null},settle:(...l)=>O(()=>o.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return on(e,l)},async pageExperiments(l,v=[]){let P=i.generation;i.assertCurrent(P);let E=i.view?.id;if(!E)throw new f("INVALID_REQUEST","Read the Run before its page experiments");let S=mn.parse(await h(ye.parse({operation:"page_experiments",release:l,usedReceiptIds:v})));if(i.assertCurrent(P),S.runId!==E||S.scope.projectId!==i.scope?.projectId||S.scope.environment!==i.scope?.environment)throw new f("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},i.nextRead())},async get(l,v){let P=i.generation;l=l&&structuredClone(l),v=v&&{...v},a&&await o.ready,i.assertCurrent(P),v??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let E=JSON.stringify([i.generation,g,l??null,v??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=i.nextRead(),w=C(T({operation:"get",...l?{data:l}:{},...v?{purchase:v}:{}},F));y.set(E,w);let N=()=>{y.get(E)===w&&y.delete(E)};return w.then(N,N),w.then(k=>structuredClone(k))},resume(l=i.view?.pendingRequest?.requestId){return l?o.closeRequested?V.settle(l):o.pending?.requestId===l?C(s(o.pending)):C(s({operation:"resume",requestId:l})):Promise.reject(new f("INVALID_REQUEST","No interrupted command is available"))},submit(l){return C(s(l))},async retry(){if(o.closeFlight)return o.closeFlight;if(o.closing)return s(o.closing);if(o.closeRequested&&o.pending)return V.settle(o.pending.requestId);if(o.inFlight)return C(o.inFlight);if(!o.pending)throw new f("INVALID_REQUEST","No command is pending");let l=o.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let v=i.generation;if(await V.settle(l.requestId),i.assertCurrent(v),!o.pending)return V.get();if(o.pending!==l||o.closeRequested)throw new f("COMMAND_PENDING","The original quote is being recovered")}return C(s(l))},identify(l){let v=i.customerToken?void 0:t;I(),i.identify(l),t=v,c=null,r.reset()},get identitySignal(){return i.signal},subscribe:i.subscribe,reset:b};return V}function vo(e,t){return Xn({...e,runToken:"",initialResponse:t})}export{dn as a,sn as b,Nn as c,me as d,Tn as e,ln as f,Dn as g,Gt as h,Ut as i,Bt as j,ye as k,mn as l,te as m,qn as n,er as o,hr as p,wr as q,hn as r,Se as s,Cr as t,Zn as u,bn as v,Z as w,un as x,Cn as y,jr as z,ie as A,Ee as B,$r as C,Hr as D,Sn as E,Xn as F,vo as G};
|