@tinkerlandai/longplay-sdk 0.10.34 → 0.10.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +49 -2
  3. package/README.zh-CN.md +20 -3
  4. package/dist/check-response-GZZRWBEA.js +1 -0
  5. package/dist/chunk-2FE4FTPH.js +1 -0
  6. package/dist/chunk-3NCMYTNG.js +1 -0
  7. package/dist/chunk-44U3FOBB.js +1 -0
  8. package/dist/chunk-56BYGPQ6.js +1 -0
  9. package/dist/chunk-73NP72FV.js +1 -0
  10. package/dist/{chunk-7VRZYSTR.js → chunk-BLVBUN2R.js} +1 -1
  11. package/dist/chunk-BOVN2BE3.js +1 -0
  12. package/dist/chunk-BQRS7Y4K.js +1 -0
  13. package/dist/chunk-CIP5SQ5Y.js +1 -0
  14. package/dist/chunk-CKKIB2HC.js +1 -0
  15. package/dist/chunk-EM3MGDPG.js +1 -0
  16. package/dist/chunk-ETK6GC5P.js +1 -0
  17. package/dist/chunk-EUTWY7A2.js +1 -0
  18. package/dist/{chunk-TYY3MUTF.js → chunk-FMDC6N4W.js} +1 -1
  19. package/dist/chunk-GZRRVHYK.js +1 -0
  20. package/dist/{chunk-MIBRUDIS.js → chunk-KE26KWIU.js} +1 -1
  21. package/dist/{chunk-I6TSQQ5N.js → chunk-KPDHY76A.js} +1 -1
  22. package/dist/{chunk-FYQXSGRT.js → chunk-LF2UIJYD.js} +1 -1
  23. package/dist/{chunk-UWLEGMWX.js → chunk-MSK3VZ3A.js} +1 -1
  24. package/dist/{chunk-X4W22IH6.js → chunk-OX7PA64E.js} +1 -1
  25. package/dist/chunk-PUR5CYWX.js +1 -0
  26. package/dist/{chunk-7NELM6EH.js → chunk-RML52BOR.js} +1 -1
  27. package/dist/chunk-RNEF4MZW.js +1 -0
  28. package/dist/chunk-SFHIFCXG.js +1 -0
  29. package/dist/{chunk-HQITRRHF.js → chunk-SXBM3DWK.js} +1 -1
  30. package/dist/chunk-TAFALMQN.js +1 -0
  31. package/dist/chunk-TJGIT5CU.js +1 -0
  32. package/dist/{chunk-6T575JKD.js → chunk-TLZP7BW6.js} +1 -1
  33. package/dist/chunk-TOTRALYQ.js +10 -0
  34. package/dist/chunk-U4RSRFZY.js +1 -0
  35. package/dist/chunk-UVRT4MY6.js +1 -0
  36. package/dist/chunk-V7MMTILA.js +1 -0
  37. package/dist/chunk-V7PFLFHE.js +1 -0
  38. package/dist/{chunk-BXPXJARS.js → chunk-VEX2FOFZ.js} +1 -1
  39. package/dist/chunk-W32FI2A2.js +1 -0
  40. package/dist/chunk-W6OQTXLL.js +1 -0
  41. package/dist/{chunk-EQPEUPMG.js → chunk-WZR2XCSJ.js} +1 -1
  42. package/dist/{chunk-U6UHASIB.js → chunk-XUGEOELU.js} +1 -1
  43. package/dist/chunk-YVXLCQGM.js +1 -0
  44. package/dist/content-AJDTSI7A.js +1 -0
  45. package/dist/funnel-host-purchase-Z7FCJ5CX.js +1 -0
  46. package/dist/{funnel-local-client-BeGBvi3z.d.ts → funnel-local-client-Dz1dTgES.d.ts} +22 -22
  47. package/dist/funnel-paywall-prerender-QHCUZZY3.js +1 -0
  48. package/dist/{funnel-process-client-C6QKDZun.d.ts → funnel-process-client-D6qjStm2.d.ts} +1 -1
  49. package/dist/funnel-runtime-host-UKSOOA4H.js +1 -0
  50. package/dist/index.d.ts +192 -58
  51. package/dist/index.js +1 -1
  52. package/dist/merchant-bridge-contracts-EAE4HQE4.js +1 -0
  53. package/dist/native-shell.js +1 -1
  54. package/dist/openrouter.js +1 -1
  55. package/dist/operation-contracts-HS4M2UXN.js +1 -0
  56. package/dist/page.js +1 -1
  57. package/dist/paywall-VYUBYBUI.js +1 -0
  58. package/dist/paywall-content-YQAVSO2T.js +1 -0
  59. package/dist/paywall-session-E5V42XUT.js +1 -0
  60. package/dist/popup.d.ts +18 -0
  61. package/dist/popup.js +1 -1
  62. package/dist/react-native.d.ts +4 -4
  63. package/dist/react-native.js +1 -1
  64. package/dist/screen-renderer-R5GH7XLV.js +1 -0
  65. package/dist/server.d.ts +2 -2
  66. package/dist/server.js +2 -2
  67. package/dist/visual.js +1 -1
  68. package/package.json +1 -1
  69. package/dist/chunk-3JJYWRA3.js +0 -1
  70. package/dist/chunk-4WZVC4TM.js +0 -1
  71. package/dist/chunk-5JWMP4YD.js +0 -1
  72. package/dist/chunk-EHDHWYVJ.js +0 -1
  73. package/dist/chunk-ERJP2GBD.js +0 -1
  74. package/dist/chunk-ILEDKSRQ.js +0 -1
  75. package/dist/chunk-ITGERPCJ.js +0 -1
  76. package/dist/chunk-N7YXDSQL.js +0 -1
  77. package/dist/chunk-NAZU3EEJ.js +0 -1
  78. package/dist/chunk-QBA3B4YK.js +0 -1
  79. package/dist/chunk-R23IGK5U.js +0 -1
  80. package/dist/chunk-R4FDIYMN.js +0 -1
  81. package/dist/chunk-RKPAIF6U.js +0 -1
  82. package/dist/chunk-SCC3O2RD.js +0 -1
  83. package/dist/chunk-TDSATEGE.js +0 -10
  84. package/dist/chunk-THMGTRXP.js +0 -1
  85. package/dist/chunk-WKIR2EQG.js +0 -1
  86. package/dist/chunk-WTVLNUMS.js +0 -1
  87. package/dist/content-ORU4ODJQ.js +0 -1
  88. package/dist/funnel-host-purchase-BEFE3N3E.js +0 -1
  89. package/dist/funnel-runtime-host-V6TYIDX3.js +0 -1
  90. package/dist/merchant-bridge-contracts-ZUQ6SGXZ.js +0 -1
  91. package/dist/operation-contracts-443N2P3A.js +0 -1
  92. package/dist/paywall-HO4PS472.js +0 -1
  93. package/dist/paywall-session-MZXFOPTR.js +0 -1
  94. package/dist/screen-renderer-W7ZGBFIR.js +0 -1
@@ -0,0 +1 @@
1
+ import{i as ie}from"./chunk-TOTRALYQ.js";import{a as Z,c as ee,e as te,f as ne,h as N,j as re,k as oe,l as se}from"./chunk-XUGEOELU.js";import{b as X}from"./chunk-WZR2XCSJ.js";import{r as V}from"./chunk-PUR5CYWX.js";import"./chunk-TAFALMQN.js";import"./chunk-ZGCKQWQ5.js";import"./chunk-VEX2FOFZ.js";import"./chunk-56BYGPQ6.js";import"./chunk-VYFSRHXM.js";import{$ as K,C as G,H as R,_ as Y,r as $}from"./chunk-BQRS7Y4K.js";import"./chunk-U4RSRFZY.js";import"./chunk-KE26KWIU.js";import"./chunk-TJGIT5CU.js";import{a as p}from"./chunk-OX7PA64E.js";import"./chunk-V7MMTILA.js";import"./chunk-EM3MGDPG.js";import{b as u}from"./chunk-VF6QMMEA.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import{a as h}from"./chunk-DSPLGTQI.js";import"./chunk-WOT6VMZA.js";var z=new WeakMap;function ce(s){let t={string:u.string(),number:u.number().finite(),boolean:u.boolean(),strings:u.array(u.string()),json:R}[s.type];return s.nullable?t.nullable():t}function ae(s,t){let f=u.record(u.string(),R).parse(s);if(Object.keys(f).length>40)throw new p("INVALID_REQUEST","Too many content inputs");for(let[m,r]of Object.entries(f))Y.parse({[m]:r});if(Object.keys(f).some(m=>!Object.hasOwn(t.inputs,m)))throw new p("INVALID_REQUEST","Undeclared content input");for(let[m,r]of Object.entries(t.inputs))if(Object.hasOwn(f,m))ce(r).parse(f[m]);else if(r.required)throw new p("INVALID_REQUEST",`Missing content input ${m}`);return f}async function Ae(s,t){return le(s,t,!1)}async function Se(s,t){return le(s,t,!0)}async function le(s,t,f){t.signal?.throwIfAborted();let m=X.parse(t.content),r=m.document;if(t.closeControl==="content"&&!r.screen.actions.some(e=>e.type==="event"&&e.close))throw new p("INVALID_REQUEST","An authored Close control requires a declared Close action");if(z.has(s))throw new p("CONFLICT","Content is already mounted in this container");let y=ae(t.inputs??{},r.contract),T=new Set(u.array(u.string()).max(40).parse(t.mutableInputs??[]));if(T.size!==(t.mutableInputs?.length??0)||[...T].some(e=>!Object.hasOwn(r.contract.inputs,e)))throw new p("INVALID_REQUEST","Mutable content inputs must name unique declared inputs");for(let e of Object.keys(r.contract.outputs))if(typeof t.actions[e]!="function")throw new p("INVALID_REQUEST",`Missing host handler for ${e}`);let M=K.parse(t.bindings??[]),d=s.ownerDocument,ue=s.clientHeight||d.defaultView?.innerHeight||800,P,w,a,_,x=r.kind==="popup",n=x?d.createElement("dialog"):null,c=d.createElement("div");if(c.dataset.indianaContent=r.kind,c.setAttribute("aria-label",r.name),c.style.cssText="width:100%;min-width:0",n){n.setAttribute("aria-label",r.name);let e=r.screen.presentation;n.style.cssText="box-sizing:border-box;padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto",e.type==="modal"||e.type==="sheet"?(n.style.width=`${$[e.size]}px`,e.type==="sheet"&&(n.style.margin="auto auto 0")):n.style.width="100vw",a=ee(n,r.screen,()=>{w?.resizeViewport(d.defaultView?.innerHeight||800,d.defaultView?.innerWidth||1024)}),n.append(c),s.append(n)}else s.append(c);let i=!1,A=!1,E=!1,S=!1,de=n?oe(n):se(c,s),D=re(s,t,r.kind,()=>{k()&&(b(),h(t.onDismiss))}),q,H,L=new Promise((e,o)=>{q=e,H=o});L.catch(()=>{});let g=null,I=structuredClone(r.screen),W=G(I,[t.locale,...d.defaultView?.navigator.languages??[]]),j=t.capabilities;I.actions=I.actions.map(e=>e.type==="event"?{...e,close:!1}:e);function b(){i||(i=!0,t.signal?.removeEventListener("abort",b),D.finish("dismissed"),H(new Error("Content preparation cancelled")),a?.destroy(),_?.(),w?.destroy(),n?.close(),n?.remove(),c.remove(),z.delete(s),n&&P?.())}let v=()=>{!E||!k()||(b(),h(t.onDismiss))};function k(){try{return t.canDismiss?.()!==!1}catch(e){return h(t.onError,e),!1}}if(n&&t.closeControl!=="content"){let e=d.createElement("button");e.type="button",e.textContent="\xD7",e.setAttribute("aria-label",t.locale?.startsWith("zh")?"\u5173\u95ED":"Close"),ne(e,r.screen.theme),e.addEventListener("click",v),n.prepend(e)}n&&a?.responsive&&(_=Z(n,v,k,t.locale?.startsWith("zh")?"\u5173\u95ED":"Close"),n.addEventListener("click",e=>{if(e.target!==n)return;let o=n.getBoundingClientRect();(e.clientX<o.left||e.clientX>o.right||e.clientY<o.top||e.clientY>o.bottom)&&v()})),n?.addEventListener("cancel",e=>{e.preventDefault(),v()}),n?.addEventListener("keydown",e=>{e.key==="Escape"&&(e.preventDefault(),v())});async function F(){if(i||!E||A||!g)return;let e=g;A=!0,c.setAttribute("aria-busy","true");try{await t.actions[e.actionId](structuredClone(e)),g=null}catch(o){i||h(t.onError,o)}finally{A=!1,i||c.removeAttribute("aria-busy")}}function J(){if(i)throw new p("CONFLICT","Content host has been destroyed");E||!S||(P??=N(d),D.present(e=>{de(),n&&(a?.latch(),n.showModal(),a?.responsive&&n.focus({preventScroll:!0}),!e&&t.loading!=="host"&&te(n,a?.type??r.screen.presentation.type,a?.responsive)),E=!0}))}function U(e){D.finish("error",e),H(e instanceof Error?e:new Error(String(e))),b()}let Q={destroy:b,show:J,get pendingAction(){return g?structuredClone(g):null},retryAction:F,updateInputs(e){if(i)throw new p("CONFLICT","Content host has been destroyed");let o=u.record(u.string(),R).parse(e),C=ae({...y,...o},r.contract);for(let l of Object.keys(o))if(!T.has(l)&&(!Object.hasOwn(y,l)||V(y[l])!==V(C[l])))throw new p("PRECONDITION_FAILED","This content input is frozen; prepare a new presentation");V(y)!==V(C)&&(w?.update(I,W,{capabilities:j,serverInput:{bindings:M,answers:{},values:C}}),y=C)},updateCapabilities(e){if(i)return;let o=structuredClone(e);w?.updateCapabilities(o),j=o}};z.set(s,Q),t.signal?.addEventListener("abort",b,{once:!0});try{if(t.signal?.throwIfAborted(),f||(P=N(d),D.start(x,t.locale??r.screen.strings.defaultLocale),i&&await L),w=ie(c,{mode:"live",rendererUrl:t.rendererUrl,title:r.name,viewportHeight:r.kind==="page"?ue:a?.responsive?d.defaultView?.innerHeight||800:void 0,...a?.responsive?{viewportWidth:d.defaultView?.innerWidth||1024,hostPresentation:()=>a.type}:{},onResize:e=>{i||a?.responsive&&(c.style.height=`${e}px`,c.style.overflow="clip",a.setContentHeight(e))},onRendered:e=>{if(!i&&(e&&n?.setAttribute("aria-label",e),!S))try{S=!0,f||J(),q()}catch(o){U(o),h(t.onError,o)}},onError:e=>{if(i)return;let o=new Error(e);S||U(o),h(t.onError,o)},onEscape:x?v:void 0,onAction:(e,o,C)=>{if(i||!E||A||g)return;let l=r.screen.actions.find(O=>O.id===e),B=r.contract.outputs[e];if(!(l?.type!=="event"||!B)&&!(l.close&&!k()))try{let O=ce(B).parse(Object.hasOwn(l.properties,"value")?l.properties.value:l.properties);g=structuredClone({requestId:crypto.randomUUID(),contentVersionId:m.id,actionId:e,event:l.event,value:O,selection:o??{},answers:C??{},requestedClose:l.close}),F()}catch(O){h(t.onError,O)}}}),w.update(I,W,{capabilities:j,serverInput:{bindings:M,answers:{},values:y}}),await Promise.race([w.ready,L]),f&&await L,i)throw new Error("Content preparation cancelled");return Q}catch(e){throw U(e),e}}export{Ae as mountContent,Se as prepareContent};
@@ -0,0 +1 @@
1
+ import{b as B}from"./chunk-ETK6GC5P.js";import{a as z}from"./chunk-SFHIFCXG.js";import{b as S}from"./chunk-YVXLCQGM.js";import{b as V}from"./chunk-RNEF4MZW.js";import"./chunk-73NP72FV.js";import"./chunk-W32FI2A2.js";import{i as W,j}from"./chunk-XUGEOELU.js";import"./chunk-KPDHY76A.js";import"./chunk-MSK3VZ3A.js";import"./chunk-2FE4FTPH.js";import"./chunk-EUTWY7A2.js";import"./chunk-CIP5SQ5Y.js";import"./chunk-CKKIB2HC.js";import"./chunk-W6OQTXLL.js";import"./chunk-BOVN2BE3.js";import"./chunk-PUR5CYWX.js";import"./chunk-TAFALMQN.js";import"./chunk-ZGCKQWQ5.js";import"./chunk-3NCMYTNG.js";import"./chunk-VEX2FOFZ.js";import"./chunk-V7PFLFHE.js";import"./chunk-56BYGPQ6.js";import"./chunk-VYFSRHXM.js";import"./chunk-BQRS7Y4K.js";import"./chunk-U4RSRFZY.js";import"./chunk-KE26KWIU.js";import"./chunk-TJGIT5CU.js";import{a as v}from"./chunk-OX7PA64E.js";import"./chunk-V7MMTILA.js";import"./chunk-SLUA7ABW.js";import"./chunk-TLZP7BW6.js";import"./chunk-3VUPVXAV.js";import"./chunk-EM3MGDPG.js";import"./chunk-VF6QMMEA.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import{a as u}from"./chunk-DSPLGTQI.js";import"./chunk-WOT6VMZA.js";var m=new WeakMap,I=new WeakMap,H=new WeakSet;function re(C,e){let s=e.prepared,N=()=>{s&&!H.has(s)&&S(s)?.release()},R=m.get(e.client);if(R)return N(),R;let c=e.allowNewPurchase===!1||!e.start?void 0:{...e.start,requestId:e.start.requestId??crypto.randomUUID()};c&&s?.state==="ready"&&s.matches(c)&&s.open();let i=c&&s&&(s.state==="preparing"||["shown","closed"].includes(s.state)&&s.matches(c))?s:void 0;i?H.add(i):N();let d=i&&S(i);d?.claim();let b=Promise.resolve().then(async()=>{let r=!1,w,E,U=!1,T=()=>{},L=()=>{},y,M=!1,O=!1,f,_=!1,n=e.signal?AbortSignal.any([e.signal,e.client.identitySignal]):e.client.identitySignal,P=()=>{m.get(e.client)===b&&m.delete(e.client),n.removeEventListener("abort",A),T(),L(),i&&H.delete(i),d?.release()};function x(){if(f)return f;let l=new Promise(h=>f=h);return I.set(e.client,l),l.then(()=>{I.get(e.client)===l&&I.delete(e.client)}),m.get(e.client)===b&&m.delete(e.client),f}let a=j(C,e,"funnel",()=>F(),z);function A(){F()}function F(l=!1){if(!r){if(r=!0,a.finish("dismissed"),w){w.destroy();return}if(l&&y){let h=x();_=!0,y.then(async g=>{g.mode==="run"&&g.status!=="blocked"&&e.client.controller&&e.client.attempt?.requestId===c?.requestId&&await e.client.close()}).catch(()=>{}).finally(()=>{h(),u(e.onDismiss,null)}),P();return}P(),u(e.onDismiss,null)}}n.addEventListener("abort",A,{once:!0}),d&&(L=d.onClose(()=>{M?r||x():F(!0)}));try{let k=function(){!r&&!n.aborted&&!U&&E&&e.client.recovery.status==="complete"&&(U=!0,u(e.onComplete,structuredClone(E)))},D=function(t){if(n.throwIfAborted(),r)throw new DOMException("Presentation dismissed","AbortError");return e.onCheckoutUrl?e.onCheckoutUrl(t):C.ownerDocument.defaultView?.location.assign(t)};var J=k,K=D;n.throwIfAborted();let l=e.client.controller?.view?.paywall?.resolution,h=l&&"document"in l?l.document:e.loadingDocument;a.start(!0,c?.locale??e.client.attempt?.locale??h?.screen.strings.defaultLocale,h??null),i?.state==="shown"?(O=!0,a.present(()=>{})):i?.state==="preparing"&&i.ready.then(t=>{if(t){if(r||!a.active||!i.matches(c)||!d?.revealable)return d?.release();a.present(()=>{i.open()==="shown"?O=!0:d.release()})}});let g=I.get(e.client);if(g&&await a.wait(g),r)return null;n.throwIfAborted(),y=c?e.client.start(c):e.client.refresh();let q=await a.wait(y,W);if(r)return null;n.throwIfAborted();let G=e.client.controller;return q.mode!=="run"||q.status==="blocked"||!G?(a.finish("skipped"),P(),O&&u(e.onDismiss,null),null):(n.removeEventListener("abort",A),M=!0,T=e.client.subscribe(k),w=await B(C,{...e,prepared:i,client:G,signal:n,checkoutNavigation:"after_confirmation",resumeCheckout:t=>e.client.continueCheckout(D,t),terminateCheckout:e.allowNewPurchase===!1?void 0:t=>e.client.terminateCheckout(t),async onCheckoutUrl(t){if(n.throwIfAborted(),r)throw new DOMException("Presentation dismissed","AbortError");let o=e.client.recovery;if((!o.actions.includes("continue_checkout")||!o.purchases.some(p=>p.type==="checkout"&&p.checkoutUrl===t))&&(o=await e.client.refresh(),n.throwIfAborted(),r))throw new DOMException("Presentation dismissed","AbortError");if(V(o)!==t)throw new v("PURCHASE_PENDING","Checkout differs from the original recovery proof");return D(t)},async resolveOfferId(t){if(n.throwIfAborted(),r)throw new DOMException("Presentation dismissed","AbortError");let o=e.client.attempt;if(!o)throw new v("PURCHASE_PENDING","Read the original Start before selecting an offer");let p=await e.resolveOfferId?.(t,o);if(n.throwIfAborted(),r)throw new DOMException("Presentation dismissed","AbortError");if(e.client.attempt?.requestId!==o.requestId)throw new v("PURCHASE_STORAGE_CONFLICT","The original purchase changed while selecting an offer");return p},onComplete(t){E=t,k()},onError(t){u(e.onError,t),t instanceof v&&t.status===401&&!n.aborted&&e.client.refresh().catch(o=>u(e.onError,o))},onDismiss(t){r=!0,P(),f?.(),u(e.onDismiss,t)}},a),r||n.aborted?(w.destroy(),null):w)}catch(l){if(_||f?.(),r)return null;throw a.finish("error",l),P(),u(e.onError,l),l}});return m.set(e.client,b),b}export{re as showFunnelPurchase};
@@ -28450,6 +28450,27 @@ interface PaywallSession {
28450
28450
  /** An independent Paywall view; purchases use the same commercial operations as a custom UI. */
28451
28451
  declare function createPaywallSession(options: IndianaOptions, input: PaywallStartInput): Promise<PaywallSession>;
28452
28452
 
28453
+ interface IndianaServerOptions extends IndianaOptions {
28454
+ apiKey: string;
28455
+ scope: Scope;
28456
+ }
28457
+
28458
+ type Start = Extract<FunnelCommand, {
28459
+ operation: "start";
28460
+ }>;
28461
+ type FunnelStartInput = Omit<Start, "operation">;
28462
+ /**
28463
+ * Funnel start. The host persists requestId before calling; retries reuse the entire input.
28464
+ * A server Key names the Customer: { type: "id" } for an Indiana Customer (including a Guest), or
28465
+ * { type: "externalUserId" } to get-or-create by your user ID with creation-only customerData
28466
+ * (customers:write). A Customer credential always starts as its own Customer and names none.
28467
+ */
28468
+ declare function createFunnelStartClient(options: IndianaServerOptions): {
28469
+ start(input: FunnelStartInput): Promise<FunnelRuntimeResponse & {
28470
+ runToken: string;
28471
+ }>;
28472
+ };
28473
+
28453
28474
  /**
28454
28475
  * Where the SDK expects the server to accept a Local segment, for instant display only. It is never
28455
28476
  * sent and never a command; the server calculates and accepts the path, and its response wins.
@@ -49435,27 +49456,6 @@ declare function createFunnelRunController(options: FunnelRunControllerOptions):
49435
49456
  reset: () => void;
49436
49457
  };
49437
49458
 
49438
- interface IndianaServerOptions extends IndianaOptions {
49439
- apiKey: string;
49440
- scope: Scope;
49441
- }
49442
-
49443
- type Start = Extract<FunnelCommand, {
49444
- operation: "start";
49445
- }>;
49446
- type FunnelStartInput = Omit<Start, "operation">;
49447
- /**
49448
- * Funnel start. The host persists requestId before calling; retries reuse the entire input.
49449
- * A server Key names the Customer: { type: "id" } for an Indiana Customer (including a Guest), or
49450
- * { type: "externalUserId" } to get-or-create by your user ID with creation-only customerData
49451
- * (customers:write). A Customer credential always starts as its own Customer and names none.
49452
- */
49453
- declare function createFunnelStartClient(options: IndianaServerOptions): {
49454
- start(input: FunnelStartInput): Promise<FunnelRuntimeResponse & {
49455
- runToken: string;
49456
- }>;
49457
- };
49458
-
49459
49459
  type RemoteResults = ReturnType<typeof evaluateFeaturesResultSchema.parse>;
49460
49460
  type FeatureClientOptions = {
49461
49461
  /** Shared configuration control is checked even if a wall-clock expiry appears fresh. */
@@ -49834,4 +49834,4 @@ type LocalFunnelClient = {
49834
49834
  /** Local predicts public rules for display. The server calculates and accepts every Flow segment. */
49835
49835
  declare function createLocalFunnelClient(options: LocalFunnelClientOptions): Promise<LocalFunnelClient>;
49836
49836
 
49837
- export { createLocalFunnelClient as A, getPaywallRecovery as B, type CustomerSession as C, preparePaywallFallback as D, type Scope as E, type FunnelRunController as F, type PushAddressObservation as G, type FunnelProcessOpenInput as H, type IndianaOptions as I, type FunnelProcessResponse as J, type FunnelCommand as K, type LocalFunnelClient as L, type FunnelProcessMutation as M, type FunnelPageExperimentsResponse as N, type IndianaServerOptions as O, type PaywallSession as P, type FunnelProcessSuppression as Q, type RemoteFeatureResult as R, type SubscriptionOperation as S, type FunnelProcessCommand as T, createFunnelStartClient as U, type FunnelRunView as a, type PaywallRecovery as b, type FunnelCommandStorage as c, type SessionCredentials as d, type FunnelExecutionPolicy as e, type SubscriptionAttachQuote as f, type FunnelStartInput as g, type IamFunnelEntryDelivery as h, type FunnelProcessRunView as i, createPaywallSession as j, type FeatureClient as k, type FeatureClientOptions as l, type FunnelControllerResponse as m, type FunnelPendingEntry as n, type FunnelPurchaseRecovery as o, type FunnelRuntimeResponse as p, type FunnelSegmentPrediction as q, type LocalFunnelClientOptions as r, scopeSchema as s, IndianaError as t, type PaywallPurchaseInput as u, type PaywallStartInput as v, type PushHost as w, type PushJournal as x, createFeatureClient as y, createFunnelRunController as z };
49837
+ export { createFunnelRunController as A, createLocalFunnelClient as B, type CustomerSession as C, getPaywallRecovery as D, preparePaywallFallback as E, type FunnelCommandStorage as F, type Scope as G, type PushAddressObservation as H, type IndianaOptions as I, type FunnelProcessOpenInput as J, type FunnelProcessResponse as K, type LocalFunnelClient as L, type FunnelCommand as M, type FunnelProcessMutation as N, type FunnelPageExperimentsResponse as O, type PaywallSession as P, type IndianaServerOptions as Q, type RemoteFeatureResult as R, type SubscriptionOperation as S, type FunnelProcessSuppression as T, type FunnelProcessCommand as U, createFunnelStartClient as V, type FunnelStartInput as a, type SessionCredentials as b, type FunnelExecutionPolicy as c, type PaywallRecovery as d, type SubscriptionAttachQuote as e, type FunnelRunController as f, type PaywallResolution as g, type FunnelRunView as h, type IamFunnelEntryDelivery as i, type FunnelProcessRunView as j, createPaywallSession as k, type FeatureClient as l, type FeatureClientOptions as m, type FunnelControllerResponse as n, type FunnelPendingEntry as o, type FunnelPurchaseRecovery as p, type FunnelRuntimeResponse as q, type FunnelSegmentPrediction as r, scopeSchema as s, type LocalFunnelClientOptions as t, IndianaError as u, type PaywallPurchaseInput as v, type PaywallStartInput as w, type PushHost as x, type PushJournal as y, createFeatureClient as z };
@@ -0,0 +1 @@
1
+ import{a,b,c}from"./chunk-YVXLCQGM.js";import"./chunk-V7PFLFHE.js";import"./chunk-OX7PA64E.js";import"./chunk-V7MMTILA.js";import"./chunk-VF6QMMEA.js";import"./chunk-DSPLGTQI.js";import"./chunk-WOT6VMZA.js";export{a as PRERENDER_MAX_AGE_MS,b as preparedInternals,c as prerenderFunnelPurchase};
@@ -1,6 +1,6 @@
1
1
  import * as zod from 'zod';
2
2
  import { z } from 'zod';
3
- import { l as FeatureClientOptions, I as IndianaOptions, C as CustomerSession, R as RemoteFeatureResult, G as PushAddressObservation, g as FunnelStartInput, p as FunnelRuntimeResponse, m as FunnelControllerResponse, z as createFunnelRunController, H as FunnelProcessOpenInput, J as FunnelProcessResponse, K as FunnelCommand, M as FunnelProcessMutation, N as FunnelPageExperimentsResponse, i as FunnelProcessRunView, F as FunnelRunController } from './funnel-local-client-BeGBvi3z.js';
3
+ import { m as FeatureClientOptions, I as IndianaOptions, C as CustomerSession, R as RemoteFeatureResult, H as PushAddressObservation, a as FunnelStartInput, q as FunnelRuntimeResponse, n as FunnelControllerResponse, A as createFunnelRunController, J as FunnelProcessOpenInput, K as FunnelProcessResponse, M as FunnelCommand, N as FunnelProcessMutation, O as FunnelPageExperimentsResponse, j as FunnelProcessRunView, f as FunnelRunController } from './funnel-local-client-Dz1dTgES.js';
4
4
  import { A as ApiInput, O as OfferingItem, I as InvoiceModeParams, a as ApiOutput } from './api-Do-6AyWa.js';
5
5
  import { O as Offer } from './coupon-kfkIVf9n.js';
6
6
  import { S as StackNode } from './screen-CGCJ46b1.js';
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-ETK6GC5P.js";import"./chunk-SFHIFCXG.js";import"./chunk-YVXLCQGM.js";import"./chunk-73NP72FV.js";import"./chunk-W32FI2A2.js";import"./chunk-XUGEOELU.js";import"./chunk-TAFALMQN.js";import"./chunk-ZGCKQWQ5.js";import"./chunk-3NCMYTNG.js";import"./chunk-VEX2FOFZ.js";import"./chunk-V7PFLFHE.js";import"./chunk-56BYGPQ6.js";import"./chunk-VYFSRHXM.js";import"./chunk-BQRS7Y4K.js";import"./chunk-U4RSRFZY.js";import"./chunk-KE26KWIU.js";import"./chunk-TJGIT5CU.js";import"./chunk-OX7PA64E.js";import"./chunk-V7MMTILA.js";import"./chunk-SLUA7ABW.js";import"./chunk-TLZP7BW6.js";import"./chunk-EM3MGDPG.js";import"./chunk-VF6QMMEA.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import"./chunk-DSPLGTQI.js";import"./chunk-WOT6VMZA.js";export{a as showFunnelRun,b as showObservedFunnelRun};
package/dist/index.d.ts CHANGED
@@ -3,14 +3,14 @@ import { S as ScreenAnswers, P as PresentationLoadingOptions, s as screenInputBi
3
3
  export { d as PresentationState } from './presentation-loading-CFSiS0VX.js';
4
4
  import { J as JsonValue } from './growth-rules-B4YYy64R.js';
5
5
  import { S as StackNode, a as ScreenSelection } from './screen-CGCJ46b1.js';
6
- import { P as PaywallSession, S as SubscriptionOperation, F as FunnelRunController, a as FunnelRunView, b as PaywallRecovery, c as FunnelCommandStorage, s as scopeSchema, I as IndianaOptions, d as SessionCredentials, e as FunnelExecutionPolicy, f as SubscriptionAttachQuote, g as FunnelStartInput, h as IamFunnelEntryDelivery, i as FunnelProcessRunView, j as createPaywallSession$1 } from './funnel-local-client-BeGBvi3z.js';
7
- export { C as CustomerSession, k as FeatureClient, l as FeatureClientOptions, m as FunnelControllerResponse, n as FunnelPendingEntry, o as FunnelPurchaseRecovery, p as FunnelRuntimeResponse, q as FunnelSegmentPrediction, L as LocalFunnelClient, r as LocalFunnelClientOptions, t as LongplayError, u as PaywallPurchaseInput, v as PaywallStartInput, w as PushHost, x as PushJournal, y as createFeatureClient, z as createFunnelRunController, A as createLocalFunnelClient, B as getPaywallRecovery, D as preparePaywallFallback } from './funnel-local-client-BeGBvi3z.js';
6
+ import { P as PaywallSession, S as SubscriptionOperation, F as FunnelCommandStorage, s as scopeSchema, a as FunnelStartInput, I as IndianaOptions, b as SessionCredentials, c as FunnelExecutionPolicy, d as PaywallRecovery, e as SubscriptionAttachQuote, f as FunnelRunController, g as PaywallResolution, h as FunnelRunView, i as IamFunnelEntryDelivery, j as FunnelProcessRunView, k as createPaywallSession$1 } from './funnel-local-client-Dz1dTgES.js';
7
+ export { C as CustomerSession, l as FeatureClient, m as FeatureClientOptions, n as FunnelControllerResponse, o as FunnelPendingEntry, p as FunnelPurchaseRecovery, q as FunnelRuntimeResponse, r as FunnelSegmentPrediction, L as LocalFunnelClient, t as LocalFunnelClientOptions, u as LongplayError, v as PaywallPurchaseInput, w as PaywallStartInput, x as PushHost, y as PushJournal, z as createFeatureClient, A as createFunnelRunController, B as createLocalFunnelClient, D as getPaywallRecovery, E as preparePaywallFallback } from './funnel-local-client-Dz1dTgES.js';
8
8
  import { E as EntitlementCheckResult, M as MerchantBridgeManifest } from './funnel-node-evaluation-COxXtZEQ.js';
9
9
  export { a as EntitlementCheckInput, b as EntitlementCheckObservation, c as EntitlementRequirement, F as FunnelNodeEvaluationContext, e as evaluateFunnelNode } from './funnel-node-evaluation-COxXtZEQ.js';
10
10
  import { C as CouponInput } from './coupon-kfkIVf9n.js';
11
11
  export { O as Offer, a as OfferUnavailableReason } from './coupon-kfkIVf9n.js';
12
- import { c as createFunnelProcess } from './funnel-process-client-C6QKDZun.js';
13
- export { F as FunnelProcessAdapter, a as FunnelProcessOptions, b as FunnelResourceSource, I as LongplayFeatureOptions, d as createFunnelClient, e as createLongplay } from './funnel-process-client-C6QKDZun.js';
12
+ import { c as createFunnelProcess } from './funnel-process-client-D6qjStm2.js';
13
+ export { F as FunnelProcessAdapter, a as FunnelProcessOptions, b as FunnelResourceSource, I as LongplayFeatureOptions, d as createFunnelClient, e as createLongplay } from './funnel-process-client-D6qjStm2.js';
14
14
  export { C as ConfigurationStorage, a as ConfigurationSync, b as ConfigurationSyncOptions, c as createConfigurationSync } from './configuration-sync-DdTRUv7A.js';
15
15
  import './api-Do-6AyWa.js';
16
16
  import 'zod/v4';
@@ -307,6 +307,8 @@ type PaywallHostOptions = PresentationLoadingOptions & {
307
307
  canInteract?: () => boolean;
308
308
  /** Host work each Customer action waits for. A rejection is reported with Retry. */
309
309
  beforeAction?: () => Promise<void>;
310
+ /** Rendered before it is shown: return focus to what was focused when it was revealed. */
311
+ focusAtReveal?: boolean;
310
312
  check?: () => Promise<EntitlementCheckResult>;
311
313
  start: () => Promise<PaywallSession>;
312
314
  /** Hand selection to the host instead of creating a quote or commercial operation. */
@@ -316,8 +318,19 @@ type PaywallHostOptions = PresentationLoadingOptions & {
316
318
  signal: AbortSignal;
317
319
  }) => unknown | Promise<unknown>;
318
320
  onCheckoutUrl?: (url: string) => unknown;
321
+ /** Reads the exact confirmed Operation and opens its original Checkout. */
322
+ resumeCheckout?: (operationId: string) => Promise<void>;
323
+ /** Allow only the existing Checkout when purchase targeting has been disabled. */
324
+ allowNewPurchase?: boolean;
319
325
  /** Recovery waits for Continue checkout; an active explicit confirmation can navigate once. */
320
326
  checkoutNavigation?: "automatic" | "after_confirmation";
327
+ /**
328
+ * Ends the exact original unpaid Checkout before another selection is quoted. With
329
+ * `checkoutNavigation: "after_confirmation"` it makes recovery part of the Paywall: the
330
+ * original plan's button reads Continue checkout, and another plan spins in its button while
331
+ * the original is terminated, read back closed and unpaid, and only then quoted.
332
+ */
333
+ terminateCheckout?: (operationId: string) => Promise<unknown>;
321
334
  /** Use hosted confirmation for new subscriptions when the merchant guarantees Checkout collects payment. */
322
335
  confirmOnHostedCheckout?: boolean;
323
336
  /** Explicit merchant selection from the Customer's claimed offers. The server validates eligibility. */
@@ -336,56 +349,6 @@ type PaywallHostOptions = PresentationLoadingOptions & {
336
349
  onError?: (error: unknown) => unknown;
337
350
  };
338
351
 
339
- type FunnelHostOptions = PresentationLoadingOptions & {
340
- client: FunnelRunController;
341
- /** Exact merchant build; enables only page experiments explicitly selected by accepted Splits. */
342
- appManifestRelease?: string;
343
- onPurchase?: PaywallHostOptions["onPurchase"];
344
- onCheckoutUrl?: PaywallHostOptions["onCheckoutUrl"];
345
- checkoutNavigation?: PaywallHostOptions["checkoutNavigation"];
346
- confirmOnHostedCheckout?: PaywallHostOptions["confirmOnHostedCheckout"];
347
- resolveOfferId?: PaywallHostOptions["resolveOfferId"];
348
- /**
349
- * Opens an external page or a Paywall link. Return `false` (or throw) when the page could not be
350
- * opened; an external page then takes its `failed` route. Without a handler, `same_window` navigates
351
- * this page and `new_window` opens a browser window; a blocked window takes `failed`.
352
- */
353
- onOpenUrl?: (instruction: {
354
- receiptId: string;
355
- url: string;
356
- openIn: FunnelOpenIn;
357
- }) => unknown;
358
- onEvent?: (name: string) => unknown;
359
- onCustomerDataIntent?: (intent: CustomerDataIntent, run: FunnelRunView) => unknown;
360
- onState?: (run: FunnelRunView) => unknown;
361
- onComplete?: (run: FunnelRunView) => unknown;
362
- onDismiss?: (run: FunnelRunView | null) => unknown;
363
- onError?: (error: unknown) => unknown;
364
- };
365
- /**
366
- * A current-protocol host. Refresh, rendering and shown telemetry never authorize a purchase.
367
- * A Run the controller already holds renders at once; with none yet, the first read comes first.
368
- */
369
- declare function showFunnelRun$1(container: HTMLElement, input: FunnelHostOptions, initialLoading?: ReturnType<typeof createPresentationLoading>): Promise<{
370
- destroy: () => void;
371
- refresh: () => Promise<void>;
372
- readonly recovery: PaywallRecovery;
373
- prepareFallback(): Promise<PaywallRecovery>;
374
- review: (receiptId?: string) => Promise<void>;
375
- exitReview: () => Promise<void>;
376
- readonly unappliedDrafts: Map<string, Record<string, string | boolean | string[]>>;
377
- }>;
378
- /** Share an authenticated purchase observation and its current loading lifecycle. */
379
- declare function showObservedFunnelRun(container: HTMLElement, input: FunnelHostOptions, initialLoading?: ReturnType<typeof createPresentationLoading>): Promise<{
380
- destroy: () => void;
381
- refresh: () => Promise<void>;
382
- readonly recovery: PaywallRecovery;
383
- prepareFallback(): Promise<PaywallRecovery>;
384
- review: (receiptId?: string) => Promise<void>;
385
- exitReview: () => Promise<void>;
386
- readonly unappliedDrafts: Map<string, Record<string, string | boolean | string[]>>;
387
- }>;
388
-
389
352
  interface FunnelStorageLocks {
390
353
  request<T>(name: string, options: {
391
354
  mode: "exclusive";
@@ -1535,19 +1498,176 @@ declare function createFunnelPurchaseClient(input: FunnelPurchaseOptions): {
1535
1498
  readonly recovery: FunnelPurchaseState;
1536
1499
  readonly attempt: FunnelPurchaseAttempt | null;
1537
1500
  readonly identitySignal: AbortSignal;
1501
+ /**
1502
+ * Storage only, no request: whether a new Start would begin afresh ("none", "finished") or
1503
+ * recover a pending original purchase ("pending"), an unpaid Checkout included.
1504
+ */
1505
+ retained: () => Promise<"none" | "finished" | "pending">;
1506
+ /**
1507
+ * Storage first, then Longplay's lookup: "found" is an original purchase Longplay knows of
1508
+ * (another device or cleared storage), now retained here; "blocked" is one it cannot
1509
+ * attribute. Call it with the page so the click does not wait for the lookup; a lookup in
1510
+ * flight, or one that found nothing within PURCHASE_DISCOVERY_REUSE_MS, is reused.
1511
+ */
1512
+ findPurchase(): Promise<"none" | "finished" | "pending" | "found" | "blocked">;
1513
+ /**
1514
+ * Reads one published Paywall Version for the current Customer, with its content, exactly as a
1515
+ * standalone Paywall would show it. It starts nothing; a pre-render shows it before the Run exists.
1516
+ */
1517
+ readPaywall(input: {
1518
+ /** One exact Version, or the Paywall's current published Version. */
1519
+ paywallVersionId?: string;
1520
+ paywallId?: string;
1521
+ commerce: {
1522
+ provider: string;
1523
+ currency: string;
1524
+ };
1525
+ locale: string;
1526
+ }): Promise<PaywallResolution>;
1538
1527
  start(start: FunnelPurchaseStart): Promise<FunnelPurchaseState>;
1539
1528
  refresh: () => Promise<FunnelPurchaseState>;
1540
1529
  confirm: () => Promise<FunnelPurchaseState>;
1541
1530
  retry: () => Promise<FunnelPurchaseState>;
1542
1531
  close(): Promise<FunnelPurchaseState>;
1543
1532
  /** Explicit user action; the merchant owns allowed destinations and navigation. */
1544
- continueCheckout(open: (url: string) => unknown): Promise<void>;
1533
+ continueCheckout(open: (url: string) => unknown, operationId?: string): Promise<void>;
1534
+ /**
1535
+ * Asks Longplay to end the exact original unpaid Checkout (the merchant confirms it closed
1536
+ * and unpaid through purchase.closed). It never starts anything: a new selection is quoted
1537
+ * only once the original reads as closed. A merchant without checkout_termination refuses
1538
+ * definitely (CAPABILITY_UNAVAILABLE or NOT_CONFIGURED) and the Checkout stays open.
1539
+ */
1540
+ terminateCheckout(operationId: string): Promise<FunnelPurchaseState>;
1545
1541
  subscribe(listener: (state: FunnelPurchaseState) => unknown): () => void;
1546
1542
  destroy: () => void;
1547
1543
  };
1548
1544
  type FunnelPurchaseClient = ReturnType<typeof createFunnelPurchaseClient>;
1549
1545
 
1550
- type FunnelPurchaseHostOptions = Omit<FunnelHostOptions, "client" | "checkoutNavigation" | "resolveOfferId"> & {
1546
+ type Start = Omit<FunnelPurchaseStart, "requestId">;
1547
+ type PreparedState = "preparing" | "ready" | "unavailable" | "shown" | "adopted" | "released" | "closed";
1548
+ /**
1549
+ * A Funnel purchase Paywall rendered before the Customer asks for it. Passing it as `prepared` to
1550
+ * showFunnelPurchase or showFunnelRun hands it to the SDK: whenever the SDK cannot use it (another
1551
+ * presentation is open, another or no Start, no Run, operation-only or blocked recovery, a failure,
1552
+ * or the Run presents something else first) it releases it, so a revealed copy never stays on
1553
+ * screen. Do not reuse a copy after passing it.
1554
+ */
1555
+ interface PreparedFunnelPurchase {
1556
+ readonly state: PreparedState;
1557
+ /**
1558
+ * Why it is unavailable: a purchase pending in storage (`purchase_pending`), an original
1559
+ * purchase Longplay found for this Customer (`original_purchase`) or could not attribute
1560
+ * (`purchase_blocked`), an unavailable plan, an error or its age. With an original purchase
1561
+ * the click takes the normal path, which shows that purchase's own Paywall.
1562
+ */
1563
+ readonly reason?: string;
1564
+ /** Resolves true once it can be revealed, false when it never will be. */
1565
+ readonly ready: Promise<boolean>;
1566
+ /** The Start it was rendered for, once known. */
1567
+ readonly start?: Start;
1568
+ /** Whether a Start with this input would present this Paywall. */
1569
+ matches(start: Start): boolean;
1570
+ /**
1571
+ * Call synchronously from the opening click, then pass it with the same Start to
1572
+ * showFunnelPurchase. "shown" reveals it in this frame; "pending" means it is still rendering:
1573
+ * pass it anyway, it is revealed only if it is ready before the Run presents; false means show
1574
+ * the purchase the normal way.
1575
+ */
1576
+ open(): "shown" | "pending" | false;
1577
+ destroy(): void;
1578
+ }
1579
+ /**
1580
+ * Renders, hidden and before any click, the Paywall a Funnel purchase Start would present, so the
1581
+ * click only reveals it. Nothing starts here: no Run, receipt or exposure. The Run started at the
1582
+ * click takes over the same rendered Paywall when it presents the same, untouched one; until then
1583
+ * a purchase tap waits for it. Keep `container` in place for the page's lifetime: moving it
1584
+ * restarts the Paywall's frame.
1585
+ */
1586
+ declare function prerenderFunnelPurchase$1(container: HTMLElement, input: {
1587
+ client: FunnelPurchaseClient;
1588
+ /**
1589
+ * The Start, or a promise for it while the merchant's own checks run: rendering starts at
1590
+ * once and it becomes ready only with a Start. Null leaves it unavailable.
1591
+ */
1592
+ start: Start | Promise<Start | null | undefined>;
1593
+ /** The Paywall the Funnel presents first: an exact Version or its current published one. */
1594
+ paywallVersionId?: string;
1595
+ paywallId?: string;
1596
+ /** Required while `start` is a promise: the Start's commerce and locale. */
1597
+ commerce?: {
1598
+ provider: string;
1599
+ currency: string;
1600
+ };
1601
+ locale?: string;
1602
+ maxAgeMs?: number;
1603
+ signal?: AbortSignal;
1604
+ onState?(state: PreparedState): void;
1605
+ }): PreparedFunnelPurchase;
1606
+
1607
+ type FunnelHostOptions = PresentationLoadingOptions & {
1608
+ client: FunnelRunController;
1609
+ /**
1610
+ * A pre-rendered Paywall, handed to the SDK: revealed, the first Paywall takes it over when it is
1611
+ * the same and untouched; otherwise it is released. Closed before the takeover, the Run closes.
1612
+ */
1613
+ prepared?: PreparedFunnelPurchase;
1614
+ /** Exact merchant build; enables only page experiments explicitly selected by accepted Splits. */
1615
+ appManifestRelease?: string;
1616
+ onPurchase?: PaywallHostOptions["onPurchase"];
1617
+ onCheckoutUrl?: PaywallHostOptions["onCheckoutUrl"];
1618
+ resumeCheckout?: PaywallHostOptions["resumeCheckout"];
1619
+ allowNewPurchase?: PaywallHostOptions["allowNewPurchase"];
1620
+ checkoutNavigation?: PaywallHostOptions["checkoutNavigation"];
1621
+ /**
1622
+ * Recovers an unpaid original Checkout inside the Paywall (see PaywallHostOptions). Closing
1623
+ * that Paywall then leaves its Run waiting on the Checkout instead of closing it, so the next
1624
+ * opening shows the same Paywall with Continue checkout.
1625
+ */
1626
+ terminateCheckout?: PaywallHostOptions["terminateCheckout"];
1627
+ confirmOnHostedCheckout?: PaywallHostOptions["confirmOnHostedCheckout"];
1628
+ resolveOfferId?: PaywallHostOptions["resolveOfferId"];
1629
+ /**
1630
+ * Opens an external page or a Paywall link. Return `false` (or throw) when the page could not be
1631
+ * opened; an external page then takes its `failed` route. Without a handler, `same_window` navigates
1632
+ * this page and `new_window` opens a browser window; a blocked window takes `failed`.
1633
+ */
1634
+ onOpenUrl?: (instruction: {
1635
+ receiptId: string;
1636
+ url: string;
1637
+ openIn: FunnelOpenIn;
1638
+ }) => unknown;
1639
+ onEvent?: (name: string) => unknown;
1640
+ onCustomerDataIntent?: (intent: CustomerDataIntent, run: FunnelRunView) => unknown;
1641
+ onState?: (run: FunnelRunView) => unknown;
1642
+ onComplete?: (run: FunnelRunView) => unknown;
1643
+ onDismiss?: (run: FunnelRunView | null) => unknown;
1644
+ onError?: (error: unknown) => unknown;
1645
+ };
1646
+ /**
1647
+ * A current-protocol host. Refresh, rendering and shown telemetry never authorize a purchase.
1648
+ * A Run the controller already holds renders at once; with none yet, the first read comes first.
1649
+ */
1650
+ declare function showFunnelRun$1(container: HTMLElement, input: FunnelHostOptions, initialLoading?: ReturnType<typeof createPresentationLoading>): Promise<{
1651
+ destroy: () => void;
1652
+ refresh: () => Promise<void>;
1653
+ readonly recovery: PaywallRecovery;
1654
+ prepareFallback(): Promise<PaywallRecovery>;
1655
+ review: (receiptId?: string) => Promise<void>;
1656
+ exitReview: () => Promise<void>;
1657
+ readonly unappliedDrafts: Map<string, Record<string, string | boolean | string[]>>;
1658
+ }>;
1659
+ /** Share an authenticated purchase observation and its current loading lifecycle. */
1660
+ declare function showObservedFunnelRun(container: HTMLElement, input: FunnelHostOptions, initialLoading?: ReturnType<typeof createPresentationLoading>): Promise<{
1661
+ destroy: () => void;
1662
+ refresh: () => Promise<void>;
1663
+ readonly recovery: PaywallRecovery;
1664
+ prepareFallback(): Promise<PaywallRecovery>;
1665
+ review: (receiptId?: string) => Promise<void>;
1666
+ exitReview: () => Promise<void>;
1667
+ readonly unappliedDrafts: Map<string, Record<string, string | boolean | string[]>>;
1668
+ }>;
1669
+
1670
+ type FunnelPurchaseHostOptions = Omit<FunnelHostOptions, "client" | "checkoutNavigation" | "resolveOfferId" | "resumeCheckout" | "terminateCheckout"> & {
1551
1671
  /** An already available Paywall design for the first frame. */
1552
1672
  loadingDocument?: PaywallLoadingDocument;
1553
1673
  client: FunnelPurchaseClient;
@@ -1556,7 +1676,12 @@ type FunnelPurchaseHostOptions = Omit<FunnelHostOptions, "client" | "checkoutNav
1556
1676
  resolveOfferId?: (purchase: Parameters<NonNullable<FunnelHostOptions["resolveOfferId"]>>[0], attempt: FunnelPurchaseAttempt) => ReturnType<NonNullable<FunnelHostOptions["resolveOfferId"]>>;
1557
1677
  };
1558
1678
  type Host = Awaited<ReturnType<typeof showObservedFunnelRun>>;
1559
- /** Same Controller/Host lifecycle; operation-only or blocked recovery goes to onRecovery. */
1679
+ /**
1680
+ * Same Controller/Host lifecycle; operation-only or blocked recovery goes to onRecovery. An
1681
+ * unpaid original Checkout is recovered inside its Run's Paywall (Continue checkout, or another
1682
+ * plan after the original is terminated). A `prepared` Paywall is handed to the SDK: one it
1683
+ * cannot use for this Start is released.
1684
+ */
1560
1685
  declare function showFunnelPurchase$1(container: HTMLElement, options: FunnelPurchaseHostOptions): Promise<Host | null>;
1561
1686
 
1562
1687
  declare class MerchantBridgeError extends Error {
@@ -2287,6 +2412,15 @@ declare function showFunnelPurchase(...args: Parameters<typeof showFunnelPurchas
2287
2412
  exitReview: () => Promise<void>;
2288
2413
  readonly unappliedDrafts: Map<string, Record<string, string | boolean | string[]>>;
2289
2414
  } | null>;
2415
+ /**
2416
+ * Renders the first Paywall of a Funnel purchase hidden, before the Customer opens it, so the
2417
+ * opening click only reveals it: call `prepared.open()` synchronously in the click, then pass it to
2418
+ * `showFunnelPurchase` as `prepared` with the same Start, which hands it to the SDK (released when
2419
+ * it cannot be used). The Run takes the revealed Paywall over. Nothing starts here. Keep
2420
+ * `container` in place; a copy is revealed only within 5 minutes of its render; `commerce` and
2421
+ * `locale` are required while `start` is a promise.
2422
+ */
2423
+ declare function prerenderFunnelPurchase(...args: Parameters<typeof prerenderFunnelPurchase$1>): Promise<PreparedFunnelPurchase>;
2290
2424
 
2291
2425
  declare function mountContent(...args: Parameters<typeof mountContent$1>): Promise<{
2292
2426
  destroy: () => void;
@@ -2306,4 +2440,4 @@ declare function prepareContent(...args: Parameters<typeof prepareContent$1>): P
2306
2440
  updateCapabilities(data: SurfaceData): void;
2307
2441
  }>;
2308
2442
 
2309
- export { type ContentActionIntent, type ContentHostOptions, EntitlementCheckResult, FunnelCommandStorage, FunnelExecutionPolicy, type FunnelHostOptions, type FunnelPurchaseAttempt, type FunnelPurchaseClient, type FunnelPurchaseEntry, type FunnelPurchaseHostOptions, type FunnelPurchaseOptions, type FunnelPurchaseStart, type FunnelPurchaseState, type FunnelPurchaseStorage, FunnelRunController, type IamFunnelEntriesOptions, type IamFunnelProcessEntriesOptions, IndianaOptions as LongplayOptions, MerchantBridgeError, type MerchantBridgeOptions, type PaywallHostOptions, PaywallLoadingDocument, type PaywallPurchaseIntent, PaywallRecovery, PaywallSession, PresentationLoadingOptions, SessionCredentials, createBrowserFunnelCommandStorage, createBrowserFunnelPurchaseStorage, createFunnelPageExperiments, createFunnelProcess, createFunnelPurchaseClient, createIamFunnelEntries, createIamFunnelProcessEntries, createMerchantBridge, createPaywallSession, formatCouponDiscount, formatCouponMoney, formatCouponTerms, mountContent, prepareContent, showFunnelPurchase, showFunnelRun, showPaywall };
2443
+ export { type ContentActionIntent, type ContentHostOptions, EntitlementCheckResult, FunnelCommandStorage, FunnelExecutionPolicy, type FunnelHostOptions, type FunnelPurchaseAttempt, type FunnelPurchaseClient, type FunnelPurchaseEntry, type FunnelPurchaseHostOptions, type FunnelPurchaseOptions, type FunnelPurchaseStart, type FunnelPurchaseState, type FunnelPurchaseStorage, FunnelRunController, type IamFunnelEntriesOptions, type IamFunnelProcessEntriesOptions, IndianaOptions as LongplayOptions, MerchantBridgeError, type MerchantBridgeOptions, type PaywallHostOptions, PaywallLoadingDocument, type PaywallPurchaseIntent, PaywallRecovery, PaywallSession, type PreparedFunnelPurchase, type PreparedState, PresentationLoadingOptions, SessionCredentials, createBrowserFunnelCommandStorage, createBrowserFunnelPurchaseStorage, createFunnelPageExperiments, createFunnelProcess, createFunnelPurchaseClient, createIamFunnelEntries, createIamFunnelProcessEntries, createMerchantBridge, createPaywallSession, formatCouponDiscount, formatCouponMoney, formatCouponTerms, mountContent, prepareContent, prerenderFunnelPurchase, showFunnelPurchase, showFunnelRun, showPaywall };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as cn,c as dn}from"./chunk-3JJYWRA3.js";import{a as Ue,b as fn,c as Ie}from"./chunk-RKPAIF6U.js";import{g as pe}from"./chunk-4WZVC4TM.js";import"./chunk-U6UHASIB.js";import{a as en,c as sn,d as un}from"./chunk-7NELM6EH.js";import"./chunk-I6TSQQ5N.js";import{a as an}from"./chunk-5JWMP4YD.js";import"./chunk-UWLEGMWX.js";import{h as Qe,i as on,k as ln}from"./chunk-7VRZYSTR.js";import"./chunk-FYQXSGRT.js";import"./chunk-7MNJH5GB.js";import{F as Re,e as Ve,g as je,h as fe,i as me,j as Ge,x as nn}from"./chunk-QBA3B4YK.js";import{a as qe}from"./chunk-ITGERPCJ.js";import"./chunk-THMGTRXP.js";import"./chunk-NAZU3EEJ.js";import{B as Fe,D as Oe,E as xe,G as De,H as Te,I as ke,J as Be,K as Ee,L as He,x as ve,y as Me,z as Ne}from"./chunk-SCC3O2RD.js";import{$ as Le,l as Ye,m as Ze,n as We}from"./chunk-R23IGK5U.js";import"./chunk-ZGCKQWQ5.js";import{c as tn,d as rn}from"./chunk-EHDHWYVJ.js";import"./chunk-BXPXJARS.js";import{b as be}from"./chunk-WTVLNUMS.js";import"./chunk-VYFSRHXM.js";import"./chunk-N7YXDSQL.js";import"./chunk-MIBRUDIS.js";import{a as H}from"./chunk-X4W22IH6.js";import"./chunk-R4FDIYMN.js";import{a as ge,c as ce}from"./chunk-J6KIN4RH.js";import"./chunk-SLUA7ABW.js";import{c as ye,d as he}from"./chunk-6T575JKD.js";import"./chunk-3VUPVXAV.js";import"./chunk-WKIR2EQG.js";import{b as K}from"./chunk-VF6QMMEA.js";import{a as Z}from"./chunk-DSPLGTQI.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import"./chunk-WOT6VMZA.js";var y=class extends Error{constructor(m,k=0,_=!1,E="fix_request"){super(m);this.code=m;this.status=k;this.retryable=_;this.recovery=E;this.name="MerchantBridgeError"}code;status;retryable;recovery};async function mn(n,A){if(!n.headers.get("content-type")?.split(";",1)[0].trim().match(/^application\/(?:json|[a-z0-9.+-]+\+json)$/i))throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE");let m=n.body?.getReader();if(!m)throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE");let k=()=>{m.cancel().catch(()=>{})};A.addEventListener("abort",k,{once:!0});let _=0,E="",r=new TextDecoder("utf-8",{fatal:!0});try{for(A.throwIfAborted();;){let i=await m.read();if(A.throwIfAborted(),i.done)break;if(_+=i.value.byteLength,_>262144)throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE");E+=r.decode(i.value,{stream:!0})}return E+=r.decode(),JSON.parse(E)}catch(i){throw A.throwIfAborted(),i instanceof y?i:new y("MERCHANT_BRIDGE_INVALID_RESPONSE")}finally{A.removeEventListener("abort",k),await m.cancel().catch(()=>{}),m.releaseLock()}}function pn(n){let A=Oe.parse(n.origin),m=xe.parse(n.manifest),k={projectId:n.scope.projectId,environmentId:n.scope.environmentId,environment:n.scope.environment};for(let c of["projectId","environmentId","environment"])if(m[c]!==n.scope[c])throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");let _=n.customerId===void 0?null:K.uuid().parse(n.customerId),E=0,r=null,i=null,g=new AbortController,I=n.fetch??globalThis.fetch;async function U(c,s,p,w,h){if(!m.capabilities.includes(c))throw new y("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let d=Fe[c];if(["merchant_catalog_reader","merchant_refund_authority","indiana_server_key"].includes(d.authority))throw new y("MERCHANT_BRIDGE_FORBIDDEN",403);let l=E,o=AbortSignal.any([g.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],...w?[w]:[]]);o.throwIfAborted();let N=new Headers(await n.headers?.());if(o.throwIfAborted(),l!==E)throw new DOMException("Merchant identity changed","AbortError");if(/\bgg_(?:sk|ct|rt)_/.test(N.get("authorization")??"")||N.has("X-Indiana-Bridge-Signature")||N.has("X-Indiana-Bridge-Key-Id"))throw new y("MERCHANT_BRIDGE_FORBIDDEN",403);N.set(Ne,String(ve)),N.set("Accept","application/json");let P=crypto.randomUUID();N.set("X-Request-Id",P),N.set("Content-Type","application/json");let b=await I(A+Me,{method:"POST",credentials:"include",redirect:"error",cache:"no-store",headers:N,signal:o,body:JSON.stringify({bridgeVersion:ve,requestId:P,command:d.command,scope:k,data:h??(p===void 0?{}:{operationId:p})})}),V=await mn(b,o);if(o.throwIfAborted(),l!==E)throw new DOMException("Merchant identity changed","AbortError");if(!b.ok){let D=He.safeParse(V);throw!D.success||D.data.scope.projectId!==n.scope.projectId||D.data.scope.environment!==n.scope.environment||D.data.scope.environmentId!==n.scope.environmentId||D.data.requestId!==P||D.data.command!==d.command?new y("MERCHANT_BRIDGE_INVALID_RESPONSE",b.status):new y(D.data.error.code,b.status,D.data.error.retryable,D.data.error.recovery)}let u=De(K.unknown()).safeParse(V);if(!u.success||u.data.scope.projectId!==n.scope.projectId||u.data.scope.environment!==n.scope.environment||u.data.scope.environmentId!==n.scope.environmentId||u.data.requestId!==P||u.data.command!==d.command)throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE",b.status);let j=s.safeParse(u.data.data);if(!j.success)throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE",b.status);return j.data}function M(){if(!_)throw new y("MERCHANT_BRIDGE_UNAUTHENTICATED",401);return _}async function z(c,s,p,w){let h=M();if(w!==void 0&&Ee.parse({operationId:w,customerId:h}),!m.capabilities.includes(c))throw new y("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let d=E,l=AbortSignal.any([g.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],...s?[s]:[]]);l.throwIfAborted();let o,N=new Promise((P,b)=>{o=()=>b(l.reason),l.addEventListener("abort",o,{once:!0})});try{let b=p(async()=>{let u=await import("./merchant-bridge-contracts-ZUQ6SGXZ.js");if(l.throwIfAborted(),d!==E||_!==h)throw new DOMException("Merchant identity changed","AbortError");return u},l),V=await Promise.race([b,N]);return l.throwIfAborted(),V}finally{l.removeEventListener("abort",o)}}async function J(c,s,p,w){let h=M(),d=Ee.parse({operationId:p,customerId:h}),l=await U(c,s,d.operationId,w,d);if(l.customerId!==h||l.operationId!==d.operationId)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");return l}return{async readPresentation(c){let s=await U("presentation",ke,void 0,c);if(i!==null&&i!==s.nativeUserId)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(s.presentation&&_!==null&&s.presentation.customerId!==_)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");return i=s.nativeUserId,r=s.presentation,s},async createSession(c){let s=await U("session",Te,void 0,c);if(i!==null&&i!==s.nativeUserId)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(_!==null&&_!==s.session.customerId)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(r&&r.customerId!==s.session.customerId)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");return _=s.session.customerId,i=s.nativeUserId,s.session},async reportPresentation(c,s){let p=M(),w=Be.parse(c);if(!r||r.customerId!==p||r.decisionId!==w.decisionId)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");return U("presentation_events",K.strictObject({queued:K.literal(!0)}),void 0,s,w)},async readCustomerCommerce(c){let s=M(),p=await z("customer_commerce",c,async(w,h)=>{let[d,l]=await Promise.all([w(),U("customer_commerce",K.unknown(),void 0,h)]),o=d.merchantBridgeCommerceSchema.safeParse(l);if(!o.success)throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE");return o.data});if(p.customerId!==s)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");return p},async executePurchase(c,s){let p=await z("purchases",s,async(w,h)=>J("purchases",(await w()).merchantBridgeOperationSchema,c,h),c);if(p.type!=="purchase")throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE");return p},readOperation:(c,s)=>z("operation_status",s,async(p,w)=>J("operation_status",(await p()).merchantOperationLookupSchema,c,w),c),async executeSubscriptionChange(c,s){let p=await z("subscription_changes",s,async(w,h)=>J("subscription_changes",(await w()).merchantBridgeOperationSchema,c,h),c);if(p.type!=="subscription_change")throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE");return p},reset(){E++,g.abort(),g=new AbortController,_=null,r=null,i=null}}}var $e=K.strictObject({command:me,target:je,runId:K.uuid().optional(),expiresAt:K.iso.datetime({offset:!0}).optional()}).refine(n=>n.command.release===n.target.release),Ke=K.strictObject({schemaVersion:K.literal(1),entries:K.array($e).max(4e3)});function ze(n){let A=!1,m=()=>{A||n.unavailable(),A=!0};function k(){return n.storage===!1?void 0:n.storage??globalThis.sessionStorage}function _(r){let i=k()?.getItem(r);if(!i)return[];if(i.length>1048576)throw Error("Entry recovery is too large");return Ke.parse(JSON.parse(i)).entries}function E(r,i){let g=k();if(!g)return;if(!i.length)return g.removeItem(r);let I=JSON.stringify(Ke.parse({schemaVersion:1,entries:i}));if(I.length>1048576)throw Error("Entry recovery is too large");g.setItem(r,I)}return{load(){try{let r=n.binding();if(!r||n.storage===!1)return;let i="indiana.funnel.entries.v1."+JSON.stringify(r);return{key:i,entries:_(i)}}catch{m();return}},retain(r,i){if(r)try{let g=$e.parse(i);E(r,[..._(r).filter(I=>I.command.funnelId!==g.command.funnelId),g])}catch{m()}},forget(r,i){if(r)try{E(r,_(r).filter(g=>g.command.requestId!==i))}catch{m()}}}}var we=n=>["running","waiting"].includes(n.status)&&!n.pendingRequest&&(n.stopped||!n.screen&&!n.paywall&&n.instruction?.type==="wait"&&n.instruction.kind!=="operation");function yn(n){let A=ye(n.baseUrl),m=n.scope,k=be(n),_=n.fetch??globalThis.fetch.bind(globalThis),E,r=!1,i=!1,g=0,I=0,U="",M=0,z=0,J=0,c=!1,s,p=!0,w,h,d,l,o,N=-1,P,b=e=>{P===e&&(P=void 0,q())},V=new Set,u=(e,a)=>Z(n.onStatus,e,a),j=new Set,D=ze({storage:n.recoveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[A,m.projectId,m.environment,n.environmentId,n.appManifestRelease,e]:void 0},unavailable:()=>u("recovery_unavailable")}),X=e=>D.forget(e.storageKey,e.command.requestId);function re(e,a){a&&(e.runId=a.id,e.expiresAt=a.runExpiresAt),D.retain(e.storageKey,{command:e.command,target:e.target,...e.runId&&{runId:e.runId},...e.expiresAt&&{expiresAt:e.expiresAt}})}function ee(){let e=o;o=void 0,e?.host.destroy(),e?.slot.remove(),e?.client.reset(),q()}let de=()=>P!==void 0||o!==void 0&&!o.background;function t(e,a){if(o?.client!==e)return;re(o.recovery,a);let f=we(a);o.slot.hidden=f,f!==o.background&&(o.background=f,f?u("run_background",o.entryId):N=I,q())}function R(e,a,f){let S=e.client.view;if(!a||e.background||!S?.screen||S.paywall||S.pendingRequest||S.stopped||S.status!=="waiting")return;let O=Le.parse({operation:"close",requestId:crypto.randomUUID(),nodeId:S.nodeId,visit:S.visit,revision:S.revision,customerToken:a}),$=be({...n,session:void 0});$.requestWithCredential("funnels",O,e.runToken,{keepalive:f}).then(()=>X(e.recovery)).catch(()=>{}).finally(()=>$.dispose())}let F=()=>{o&&R(o,n.session.peek(),!0)},L=()=>Date.now()<z&&performance.now()<J;function G(e){if(e.target.release!==n.appManifestRelease||!L())return!1;try{return ce(e.target.render,document,location.pathname,()=>{})}catch{return u("incompatible",e.id),!1}}function ne(e){if(r||e.epoch!==M||e.visit!==I||document.visibilityState==="hidden")return!1;try{return ce(e.target.render,document,location.pathname,()=>{})}catch{return!1}}async function oe(e){if(de()){u("in_progress",e.id);return}if(!n.session.peek()){u("identity_required",e.id);return}let a=D.load(),f=a?.entries.find(O=>O.command.funnelId===e.funnelId&&(!O.expiresAt||Date.parse(O.expiresAt)>Date.now()));if(f){if(!ae(f)){u("recovery_pending",e.id);return}let O={...f,storageKey:a.key,epoch:M,visit:I};j.add(O.command.requestId),P=O,await te(O);return}let S={freshStart:!0,command:me.parse({operation:"entry_start",entryId:e.id,funnelId:e.funnelId,versionId:e.versionId,release:n.appManifestRelease,requestId:crypto.randomUUID(),locale:document.documentElement.lang||"en"}),epoch:M,visit:I,target:e.target,storageKey:a?.key};j.add(S.command.requestId),P=S,await te(S)}async function te(e){if(e.dispatching)return;e.dispatching=!0;let a=e.freshStart===!0;e.freshStart=!1;let f,S=!1,O=!1;async function $(T){if(e.epoch!==M)return;let v=T.view;if(!(e.storageKey&&v&&(we(v)||v.paywall||v.pendingRequest))&&v&&["running","waiting"].includes(v.status))try{await T.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:v.nodeId,visit:v.visit,revision:v.revision}),X(e)}catch(x){if(!(x instanceof H&&x.code==="FORBIDDEN"))throw x}}try{re(e),u("starting",e.command.entryId);let T=await k.request("funnels",e.command),v=Ge.safeParse(T);if(v.success){if(v.data.scope.projectId!==m.projectId||v.data.scope.environment!==m.environment)throw new H("SCOPE_MISMATCH","Entry scope changed");e.epoch===M&&u(v.data.reason,e.command.entryId),X(e),b(e);return}let x=Ve.parse(T);if(!x.runToken||x.scope.projectId!==m.projectId||x.scope.environment!==m.environment||x.run.source.type!=="funnel"||x.run.source.id!==e.command.funnelId||x.run.source.versionId!==e.command.versionId||e.runId!==void 0&&x.run.id!==e.runId)throw new H("INVALID_RESPONSE","Invalid entry Run");if(e.epoch!==M){b(e),u("identity_changed",e.command.entryId);return}re(e,x.run);let C=Re({...n,runToken:x.runToken,funnelId:e.command.funnelId,initialResponse:a?T:void 0});f=C,O=!0,await C.get(),O=!1;let Y=C.view;if(!Y||Y.id!==x.run.id||Y.source.type!=="funnel"||Y.source.id!==e.command.funnelId||Y.source.versionId!==e.command.versionId)throw new H("INVALID_RESPONSE","Entry Run version changed");if(!["running","waiting"].includes(Y.status)){X(e),b(e),u("run_ended",e.command.entryId);return}if(!ne(e)){await $(C),u("left_screen",e.command.entryId),b(e);return}let se=!1,Ae=!1;if(o&&!o.background){await $(C),u("in_progress",e.command.entryId),b(e);return}o&&ee();let Q=document.createElement("div");Q.hidden=we(Y),n.container.append(Q);let Ce=await Ie(Q,{...n.host,client:C,appManifestRelease:n.appManifestRelease,onState(B){t(C,B),Z(n.host?.onState,B)},onDismiss(B){se=!0,Q.remove(),B&&!["running","waiting"].includes(B.status)&&X(e),o?.client===C&&(o=void 0,C.reset(),q(),B&&B.status!=="completed"&&u("run_ended",e.command.entryId)),Z(n.host?.onDismiss,B)},onComplete(B){Ae=!0,X(e),o?.client===C&&ee(),Z(n.host?.onComplete,B)},onError(B){Z(n.host?.onError,B),o?.client===C&&B instanceof H&&B.code==="FORBIDDEN"&&(X(e),ee(),u("run_ended",e.command.entryId))}}).catch(B=>{throw Q.remove(),B});if(!ne(e)||se||Ae){Ce.destroy(),Q.remove(),ne(e)||await $(C),b(e);return}let le=we(C.view??Y);Q.hidden=le,o={host:Ce,client:C,slot:Q,entryId:e.command.entryId,background:le,runToken:x.runToken,owner:n.session.peek(),recovery:e},le||(N=e.visit),S=!0,b(e),u("started",e.command.entryId),le&&u("run_background",e.command.entryId)}catch(T){T instanceof H&&(!f||O&&T.code==="FORBIDDEN")&&T.status!==void 0&&T.status>=400&&T.status<500&&!T.retryable&&(X(e),b(e)),e.epoch===M&&!r&&(u("start_failed",e.command.entryId),Z(n.host?.onError,T))}finally{S||f?.reset(),e.dispatching=!1}}function ae(e){if(e.command.release!==n.appManifestRelease||e.target.release!==n.appManifestRelease)return!1;try{return ce(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function W(){if(de())return!1;let e=D.load();for(let a of e?.entries??[]){if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now()){D.forget(e.key,a.command.requestId);continue}if(a.command.requestId===o?.recovery.command.requestId||j.has(a.command.requestId)||!ae(a))continue;j.add(a.command.requestId);let f={...a,storageKey:e.key,epoch:M,visit:I};return P=f,te(f),!0}return!1}function ue(){if(c=!1,r||!i||document.visibilityState==="hidden")return;ie();let e=o!==void 0&&!o.background;if(e&&(N=I),!W()){if(!L()){p=!0;return}p=!1;for(let a of E?.entries??[]){let f=`${a.funnelId}:${a.id}`;if(!(a.event!=="screen_enter"||V.has(f)||!G(a))){if(!n.session.peek()){u("identity_required",a.id);continue}if(N===I){V.add(f),e&&u("in_progress",a.id);continue}if(P){u("in_progress",a.id);return}V.add(f),oe(a);break}}}}let q=()=>{!c&&!r&&(c=!0,queueMicrotask(ue))};function ie(){let e=location.origin+location.pathname;return e===U?!1:(U=e,I++,p=!0,V.clear(),j.clear(),!0)}function Je(){ie()&&q()}function Se(e){if(!e.isTrusted||e.button!==0||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||document.visibilityState==="hidden")return;let a=e.target;if(!(a instanceof Element)||a.closest("[data-indiana-funnel]"))return;let f=a.closest("button,a,input");if(!(!f||f.matches(":disabled,[aria-disabled='true']")||f.closest("[hidden],[inert],[aria-hidden='true']")))for(let S of E?.entries??[]){let O=S.target.button;if(!(S.event!=="button_click"||!O||!G(S))){try{let $=ge(document);if(!f.matches(O.selector)||$(O.selector,f)!==1)continue}catch{u("incompatible",S.id);continue}oe(S);break}}}async function _e(){if(r)return;if(s)return s;let e=++g,a=new AbortController;w=a;let f,S=new Promise((T,v)=>{f=()=>v(new H("TIMEOUT","Funnel entry configuration read cancelled or timed out")),a.signal.addEventListener("abort",f,{once:!0})}),O=setTimeout(()=>a.abort(),n.timeoutMs??5e3),$=(async()=>{let T=async()=>{let se=await _(`${A}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:a.signal});if(!se.ok)throw new H("SERVICE_UNAVAILABLE","Funnel entries unavailable",se.status);return fe.parse(await se.json())},v=await Promise.race([T(),S]),x=Date.parse(v.validatedAt),C=Date.parse(v.validUntil);if(v.scope.projectId!==m.projectId||v.scope.environment!==m.environment||v.scope.environmentId!==n.environmentId||v.release!==n.appManifestRelease||C<=Date.now()||x>Date.now()+5e3||C-x>6e4||C<=x)throw new H("INVALID_RESPONSE","Entry configuration scope or deadline changed");if(r||e!==g)return;let Y=E===void 0;E=v,z=C,J=performance.now()+Math.min(C-Date.now(),6e4),(Y||p)&&q()})();s=$;try{await $}finally{clearTimeout(O),a.signal.removeEventListener("abort",f),s===$&&(s=void 0)}}async function Xe(){if(!(!i||r)){try{await _e()}catch{r||u("configuration_unavailable")}q()}}let Pe=pe({document,run:Xe,delay:()=>i&&!r?15e3:void 0});return{async start(){i||r||(i=!0,U=location.origin+location.pathname,h=he(Je),d=n.session.subscribeIdentity(()=>{M++,p=!0,P=void 0,V.clear(),N=-1,j.clear(),o&&R(o,o.owner,!1),ee(),q()}),l=new MutationObserver(q),l.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",Se,!0),addEventListener("pagehide",F),await Pe.refresh())},refresh:_e,async retry(){P&&!r&&P.epoch===M&&await te(P)},destroy(){r=!0,g++,Pe.destroy(),w?.abort(),l?.disconnect(),h?.(),d?.(),document.removeEventListener("click",Se,!0),removeEventListener("pagehide",F),F(),ee(),k.dispose(),E=void 0}}}function hn(n){let A=ye(n.baseUrl),m=n.fetch??globalThis.fetch.bind(globalThis),k,_=0,E=0,r=!1,i=!1,g=0,I=0,U=-1,M=!1,z="",J,c,s,p,w=new Set,h,d,l,o=(t,R)=>Z(n.onStatus,t,R),N=()=>Date.now()<_&&performance.now()<E;function P(t){try{return N()&&t.target.release===n.appManifestRelease&&ce(t.target.render,document,location.pathname,()=>{})}catch{return o("incompatible",t.id),!1}}function b(){let t=l;l=void 0,t?.host.destroy(),t?.slot.remove()}async function V(t){if(t.dispatching)return;t.dispatching=!0;let R=g;try{let F=await t.process.open({operation:"entry_start",funnelId:t.entry.funnelId,versionId:t.entry.versionId,entryId:t.entry.id,release:n.appManifestRelease,locale:n.locale??"en"});if(r||R!==g||d!==t)return;let L=document.createElement("div");n.container.append(L),U=I;let G=await Ie(L,{...n.host,client:F.controller,appManifestRelease:n.appManifestRelease,onDismiss(ne){l?.process===t.process&&(l=void 0,L.remove()),Z(n.host?.onDismiss,ne)}});if(r||R!==g||d!==t){G.destroy(),L.remove();return}l={entry:t.entry,process:t.process,host:G,slot:L},d=void 0,o("run_presented",t.entry.id)}catch(F){if(r||R!==g||d!==t)return;F instanceof H&&"result"in F?(d=void 0,t.process.destroy(),o("suppressed",t.entry.id),j()):o("entry_unavailable",t.entry.id)}finally{t.dispatching=!1}}function u(t){if(r||d||l||h||U===I||!P(t))return;let R=`${I}:${t.id}`;if(w.has(R))return;w.add(R);let F={entry:t,process:n.createProcess(t),visit:I};d=F,V(F)}function j(){M||r||(M=!0,queueMicrotask(()=>{if(M=!1,!(r||document.visibilityState==="hidden"||!N()||d||l||h||U===I)){for(let t of k?.entries??[])if(t.event==="screen_enter"&&P(t)){u(t);break}}}))}function D(t){if(!t.isTrusted||t.defaultPrevented||!(t.target instanceof Element)||d||l||h||U===I)return;let R=ge(document,()=>{});for(let F of k?.entries??[]){let L=F.target.button;if(F.event!=="button_click"||!L||!P(F))continue;let G=t.target.closest(L.selector);if(!(!G||G.tagName.toLowerCase()!==L.tag||R(L.selector)!==1||G.matches(":disabled")||G.closest('[inert],[hidden],[aria-hidden="true"]'))){u(F);break}}}let X=()=>{let t=location.origin+location.pathname;t!==z&&(z=t,I++,w.clear(),j())};async function re(){if(r)return;if(c)return c;let t=g,R=new AbortController;J=R;let F,L=new Promise((te,ae)=>{F=ae}),G=()=>F(new H("TIMEOUT","Funnel entry read cancelled"));R.signal.addEventListener("abort",G,{once:!0});let ne=setTimeout(()=>R.abort(),n.timeoutMs??5e3),oe=(async()=>{let te=encodeURIComponent(JSON.stringify(["funnel-process/1"])),ae=async()=>{let ie=await m(`${A}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}&executionContracts=${te}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:R.signal});if(!ie.ok)throw new H("SERVICE_UNAVAILABLE","Funnel entries unavailable",ie.status);return fe.parse(await ie.json())},W=await Promise.race([ae(),L]),ue=Date.parse(W.validatedAt),q=Date.parse(W.validUntil);if(W.scope.projectId!==n.scope.projectId||W.scope.environment!==n.scope.environment||W.scope.environmentId!==n.environmentId||W.release!==n.appManifestRelease||q<=Date.now()||ue>Date.now()+5e3||q<=ue||q-ue>6e4)throw new H("INVALID_RESPONSE","Entry scope or deadline changed");r||t!==g||(k=W,_=q,E=performance.now()+Math.min(q-Date.now(),6e4),j())})();c=oe;try{await oe}finally{clearTimeout(ne),R.signal.removeEventListener("abort",G),c===oe&&(c=void 0)}}async function ee(){if(!(!i||r))try{await re()}catch{r||o("configuration_unavailable")}}let de=pe({document,run:ee,delay:()=>i&&!r?15e3:void 0});return{async start(){i||r||(i=!0,z=location.origin+location.pathname,s=he(X),p=new MutationObserver(j),p.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",D,!0),await de.refresh())},refresh:re,async retry(){d&&!r&&await V(d)},async syncIdentity(){let t=l??d??h;if(t)try{let R=await t.process.syncIdentity();return h===t&&(d={entry:t.entry,process:t.process,visit:I},h=void 0,await V(d)),R}catch(R){throw t.process.view||(h={entry:t.entry,process:t.process,visit:I},d=void 0,b()),R}},async detach(){g++,J?.abort();let t=l??d??h;t&&(h={entry:t.entry,process:t.process,visit:I}),d=void 0,b(),t&&await t.process.detach()},destroy(){r=!0,g++,de.destroy(),J?.abort(),p?.disconnect(),s?.(),document.removeEventListener("click",D,!0);let t=l??d??h;d=void 0,h=void 0,b(),t?.process.destroy(),k=void 0}}}async function zn(n,A){return(await import("./paywall-HO4PS472.js")).showPaywall(n,A)}async function Jn(...n){return n[1]=qe(n[1]),(await import("./paywall-session-MZXFOPTR.js")).createPaywallSession(...n)}async function Xn(...n){let A=n[1].signal?.aborted?void 0:Ue(n[1].client);try{let[m]=await Promise.all([import("./funnel-runtime-host-V6TYIDX3.js"),import("./screen-renderer-W7ZGBFIR.js"),import("./paywall-HO4PS472.js")]);return await m.showFunnelRun(...n)}finally{A?.()}}async function Yn(...n){return(await import("./funnel-host-purchase-BEFE3N3E.js")).showFunnelPurchase(...n)}async function Zn(...n){return(await import("./content-ORU4ODJQ.js")).mountContent(...n)}async function Wn(...n){return(await import("./content-ORU4ODJQ.js")).prepareContent(...n)}export{H as LongplayError,y as MerchantBridgeError,nn as createBrowserFunnelCommandStorage,cn as createBrowserFunnelPurchaseStorage,on as createConfigurationSync,Qe as createFeatureClient,sn as createFunnelClient,fn as createFunnelPageExperiments,un as createFunnelProcess,dn as createFunnelPurchaseClient,Re as createFunnelRunController,yn as createIamFunnelEntries,hn as createIamFunnelProcessEntries,ln as createLocalFunnelClient,en as createLongplay,pn as createMerchantBridge,Jn as createPaywallSession,an as evaluateFunnelNode,Ze as formatCouponDiscount,Ye as formatCouponMoney,We as formatCouponTerms,tn as getPaywallRecovery,Zn as mountContent,Wn as prepareContent,rn as preparePaywallFallback,Yn as showFunnelPurchase,Xn as showFunnelRun,zn as showPaywall};
1
+ import{a as dn,c as un}from"./chunk-RNEF4MZW.js";import{a as Ue,c as mn}from"./chunk-73NP72FV.js";import{a as pe}from"./chunk-W32FI2A2.js";import{a as nn,c as cn,d as ln}from"./chunk-RML52BOR.js";import"./chunk-KPDHY76A.js";import{a as sn}from"./chunk-UVRT4MY6.js";import"./chunk-MSK3VZ3A.js";import{h as en,i as an,k as fn}from"./chunk-BLVBUN2R.js";import{F as be,e as Ve,g as je,h as fe,i as me,j as Ge,x as tn}from"./chunk-2FE4FTPH.js";import{a as qe}from"./chunk-EUTWY7A2.js";import"./chunk-7MNJH5GB.js";import"./chunk-CIP5SQ5Y.js";import"./chunk-LF2UIJYD.js";import{B as Ne,D as Oe,E as xe,G as De,H as Te,I as ke,J as Be,K as ve,L as He,x as we,y as Me,z as Fe}from"./chunk-CKKIB2HC.js";import"./chunk-W6OQTXLL.js";import"./chunk-BOVN2BE3.js";import"./chunk-PUR5CYWX.js";import{$ as Le,l as Ze,m as We,n as Qe}from"./chunk-TAFALMQN.js";import"./chunk-ZGCKQWQ5.js";import{c as rn,e as on}from"./chunk-3NCMYTNG.js";import"./chunk-VEX2FOFZ.js";import"./chunk-V7PFLFHE.js";import{b as Ee}from"./chunk-56BYGPQ6.js";import"./chunk-VYFSRHXM.js";import"./chunk-BQRS7Y4K.js";import"./chunk-U4RSRFZY.js";import"./chunk-KE26KWIU.js";import"./chunk-TJGIT5CU.js";import{a as L}from"./chunk-OX7PA64E.js";import"./chunk-V7MMTILA.js";import"./chunk-SLUA7ABW.js";import{a as Ie,c as se}from"./chunk-J6KIN4RH.js";import{c as ye,d as he}from"./chunk-TLZP7BW6.js";import"./chunk-3VUPVXAV.js";import"./chunk-EM3MGDPG.js";import{b as G}from"./chunk-VF6QMMEA.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import{a as Z}from"./chunk-DSPLGTQI.js";import"./chunk-WOT6VMZA.js";var y=class extends Error{constructor(m,D=0,_=!1,b="fix_request"){super(m);this.code=m;this.status=D;this.retryable=_;this.recovery=b;this.name="MerchantBridgeError"}code;status;retryable;recovery};async function pn(n,w){if(!n.headers.get("content-type")?.split(";",1)[0].trim().match(/^application\/(?:json|[a-z0-9.+-]+\+json)$/i))throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE");let m=n.body?.getReader();if(!m)throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE");let D=()=>{m.cancel().catch(()=>{})};w.addEventListener("abort",D,{once:!0});let _=0,b="",r=new TextDecoder("utf-8",{fatal:!0});try{for(w.throwIfAborted();;){let i=await m.read();if(w.throwIfAborted(),i.done)break;if(_+=i.value.byteLength,_>262144)throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE");b+=r.decode(i.value,{stream:!0})}return b+=r.decode(),JSON.parse(b)}catch(i){throw w.throwIfAborted(),i instanceof y?i:new y("MERCHANT_BRIDGE_INVALID_RESPONSE")}finally{w.removeEventListener("abort",D),await m.cancel().catch(()=>{}),m.releaseLock()}}function yn(n){let w=Oe.parse(n.origin),m=xe.parse(n.manifest),D={projectId:n.scope.projectId,environmentId:n.scope.environmentId,environment:n.scope.environment};for(let c of["projectId","environmentId","environment"])if(m[c]!==n.scope[c])throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");let _=n.customerId===void 0?null:G.uuid().parse(n.customerId),b=0,r=null,i=null,I=new AbortController,g=n.fetch??globalThis.fetch;async function U(c,s,p,v,h){if(!m.capabilities.includes(c))throw new y("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let d=Ne[c];if(["merchant_catalog_reader","merchant_refund_authority","indiana_server_key"].includes(d.authority))throw new y("MERCHANT_BRIDGE_FORBIDDEN",403);let l=b,o=AbortSignal.any([I.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],...v?[v]:[]]);o.throwIfAborted();let F=new Headers(await n.headers?.());if(o.throwIfAborted(),l!==b)throw new DOMException("Merchant identity changed","AbortError");if(/\bgg_(?:sk|ct|rt)_/.test(F.get("authorization")??"")||F.has("X-Indiana-Bridge-Signature")||F.has("X-Indiana-Bridge-Key-Id"))throw new y("MERCHANT_BRIDGE_FORBIDDEN",403);F.set(Fe,String(we)),F.set("Accept","application/json");let A=crypto.randomUUID();F.set("X-Request-Id",A),F.set("Content-Type","application/json");let R=await g(w+Me,{method:"POST",credentials:"include",redirect:"error",cache:"no-store",headers:F,signal:o,body:JSON.stringify({bridgeVersion:we,requestId:A,command:d.command,scope:D,data:h??(p===void 0?{}:{operationId:p})})}),V=await pn(R,o);if(o.throwIfAborted(),l!==b)throw new DOMException("Merchant identity changed","AbortError");if(!R.ok){let T=He.safeParse(V);throw!T.success||T.data.scope.projectId!==n.scope.projectId||T.data.scope.environment!==n.scope.environment||T.data.scope.environmentId!==n.scope.environmentId||T.data.requestId!==A||T.data.command!==d.command?new y("MERCHANT_BRIDGE_INVALID_RESPONSE",R.status):new y(T.data.error.code,R.status,T.data.error.retryable,T.data.error.recovery)}let u=De(G.unknown()).safeParse(V);if(!u.success||u.data.scope.projectId!==n.scope.projectId||u.data.scope.environment!==n.scope.environment||u.data.scope.environmentId!==n.scope.environmentId||u.data.requestId!==A||u.data.command!==d.command)throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE",R.status);let j=s.safeParse(u.data.data);if(!j.success)throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE",R.status);return j.data}function M(){if(!_)throw new y("MERCHANT_BRIDGE_UNAUTHENTICATED",401);return _}async function $(c,s,p,v){let h=M();if(v!==void 0&&ve.parse({operationId:v,customerId:h}),!m.capabilities.includes(c))throw new y("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let d=b,l=AbortSignal.any([I.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],...s?[s]:[]]);l.throwIfAborted();let o,F=new Promise((A,R)=>{o=()=>R(l.reason),l.addEventListener("abort",o,{once:!0})});try{let R=p(async()=>{let u=await import("./merchant-bridge-contracts-EAE4HQE4.js");if(l.throwIfAborted(),d!==b||_!==h)throw new DOMException("Merchant identity changed","AbortError");return u},l),V=await Promise.race([R,F]);return l.throwIfAborted(),V}finally{l.removeEventListener("abort",o)}}async function J(c,s,p,v){let h=M(),d=ve.parse({operationId:p,customerId:h}),l=await U(c,s,d.operationId,v,d);if(l.customerId!==h||l.operationId!==d.operationId)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");return l}return{async readPresentation(c){let s=await U("presentation",ke,void 0,c);if(i!==null&&i!==s.nativeUserId)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(s.presentation&&_!==null&&s.presentation.customerId!==_)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");return i=s.nativeUserId,r=s.presentation,s},async createSession(c){let s=await U("session",Te,void 0,c);if(i!==null&&i!==s.nativeUserId)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(_!==null&&_!==s.session.customerId)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(r&&r.customerId!==s.session.customerId)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");return _=s.session.customerId,i=s.nativeUserId,s.session},async reportPresentation(c,s){let p=M(),v=Be.parse(c);if(!r||r.customerId!==p||r.decisionId!==v.decisionId)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");return U("presentation_events",G.strictObject({queued:G.literal(!0)}),void 0,s,v)},async readCustomerCommerce(c){let s=M(),p=await $("customer_commerce",c,async(v,h)=>{let[d,l]=await Promise.all([v(),U("customer_commerce",G.unknown(),void 0,h)]),o=d.merchantBridgeCommerceSchema.safeParse(l);if(!o.success)throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE");return o.data});if(p.customerId!==s)throw new y("MERCHANT_BRIDGE_SCOPE_MISMATCH");return p},async executePurchase(c,s){let p=await $("purchases",s,async(v,h)=>J("purchases",(await v()).merchantBridgeOperationSchema,c,h),c);if(p.type!=="purchase")throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE");return p},readOperation:(c,s)=>$("operation_status",s,async(p,v)=>J("operation_status",(await p()).merchantOperationLookupSchema,c,v),c),async executeSubscriptionChange(c,s){let p=await $("subscription_changes",s,async(v,h)=>J("subscription_changes",(await v()).merchantBridgeOperationSchema,c,h),c);if(p.type!=="subscription_change")throw new y("MERCHANT_BRIDGE_INVALID_RESPONSE");return p},reset(){b++,I.abort(),I=new AbortController,_=null,r=null,i=null}}}var $e=G.strictObject({command:me,target:je,runId:G.uuid().optional(),expiresAt:G.iso.datetime({offset:!0}).optional()}).refine(n=>n.command.release===n.target.release),Ke=G.strictObject({schemaVersion:G.literal(1),entries:G.array($e).max(4e3)});function ze(n){let w=!1,m=()=>{w||n.unavailable(),w=!0};function D(){return n.storage===!1?void 0:n.storage??globalThis.sessionStorage}function _(r){let i=D()?.getItem(r);if(!i)return[];if(i.length>1048576)throw Error("Entry recovery is too large");return Ke.parse(JSON.parse(i)).entries}function b(r,i){let I=D();if(!I)return;if(!i.length)return I.removeItem(r);let g=JSON.stringify(Ke.parse({schemaVersion:1,entries:i}));if(g.length>1048576)throw Error("Entry recovery is too large");I.setItem(r,g)}return{load(){try{let r=n.binding();if(!r||n.storage===!1)return;let i="indiana.funnel.entries.v1."+JSON.stringify(r);return{key:i,entries:_(i)}}catch{m();return}},retain(r,i){if(r)try{let I=$e.parse(i);b(r,[..._(r).filter(g=>g.command.funnelId!==I.command.funnelId),I])}catch{m()}},forget(r,i){if(r)try{b(r,_(r).filter(I=>I.command.requestId!==i))}catch{m()}}}}var ge=n=>["running","waiting"].includes(n.status)&&!n.pendingRequest&&(n.stopped||!n.screen&&!n.paywall&&n.instruction?.type==="wait"&&n.instruction.kind!=="operation");function hn(n){let w=ye(n.baseUrl),m=n.scope,D=Ee(n),_=n.fetch??globalThis.fetch.bind(globalThis),b,r=!1,i=!1,I=0,g=0,U="",M=0,$=0,J=0,c=!1,s,p=!0,v,h,d,l,o,F=-1,A,R=e=>{A===e&&(A=void 0,q())},V=new Set,u=(e,a)=>Z(n.onStatus,e,a),j=new Set,T=ze({storage:n.recoveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[w,m.projectId,m.environment,n.environmentId,n.appManifestRelease,e]:void 0},unavailable:()=>u("recovery_unavailable")}),X=e=>T.forget(e.storageKey,e.command.requestId);function oe(e,a){a&&(e.runId=a.id,e.expiresAt=a.runExpiresAt),T.retain(e.storageKey,{command:e.command,target:e.target,...e.runId&&{runId:e.runId},...e.expiresAt&&{expiresAt:e.expiresAt}})}function te(){let e=o;o=void 0,e?.host.destroy(),e?.slot.remove(),e?.client.reset(),q()}let ce=()=>A!==void 0||o!==void 0&&!o.background;function t(e,a){if(o?.client!==e)return;oe(o.recovery,a);let f=ge(a);o.slot.hidden=f,f!==o.background&&(o.background=f,f?u("run_background",o.entryId):F=g,q())}function S(e,a,f){let P=e.client.view;if(!a||e.background||!P?.screen||P.paywall||P.pendingRequest||P.stopped||P.status!=="waiting")return;let O=Le.parse({operation:"close",requestId:crypto.randomUUID(),nodeId:P.nodeId,visit:P.visit,revision:P.revision,customerToken:a}),K=Ee({...n,session:void 0});K.requestWithCredential("funnels",O,e.runToken,{keepalive:f}).then(()=>X(e.recovery)).catch(()=>{}).finally(()=>K.dispose())}let N=()=>{o&&S(o,n.session.peek(),!0)},z=()=>Date.now()<$&&performance.now()<J;function B(e){if(e.target.release!==n.appManifestRelease||!z())return!1;try{return se(e.target.render,document,location.pathname,()=>{})}catch{return u("incompatible",e.id),!1}}function Q(e){if(r||e.epoch!==M||e.visit!==g||document.visibilityState==="hidden")return!1;try{return se(e.target.render,document,location.pathname,()=>{})}catch{return!1}}async function ee(e){if(ce()){u("in_progress",e.id);return}if(!n.session.peek()){u("identity_required",e.id);return}let a=T.load(),f=a?.entries.find(O=>O.command.funnelId===e.funnelId&&(!O.expiresAt||Date.parse(O.expiresAt)>Date.now()));if(f){if(!ae(f)){u("recovery_pending",e.id);return}let O={...f,storageKey:a.key,epoch:M,visit:g};j.add(O.command.requestId),A=O,await re(O);return}let P={freshStart:!0,command:me.parse({operation:"entry_start",entryId:e.id,funnelId:e.funnelId,versionId:e.versionId,release:n.appManifestRelease,requestId:crypto.randomUUID(),locale:document.documentElement.lang||"en"}),epoch:M,visit:g,target:e.target,storageKey:a?.key};j.add(P.command.requestId),A=P,await re(P)}async function re(e){if(e.dispatching)return;e.dispatching=!0;let a=e.freshStart===!0;e.freshStart=!1;let f,P=!1,O=!1;async function K(k){if(e.epoch!==M)return;let E=k.view;if(!(e.storageKey&&E&&(ge(E)||E.paywall||E.pendingRequest))&&E&&["running","waiting"].includes(E.status))try{await k.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:E.nodeId,visit:E.visit,revision:E.revision}),X(e)}catch(x){if(!(x instanceof L&&x.code==="FORBIDDEN"))throw x}}try{oe(e),u("starting",e.command.entryId);let k=await D.request("funnels",e.command),E=Ge.safeParse(k);if(E.success){if(E.data.scope.projectId!==m.projectId||E.data.scope.environment!==m.environment)throw new L("SCOPE_MISMATCH","Entry scope changed");e.epoch===M&&u(E.data.reason,e.command.entryId),X(e),R(e);return}let x=Ve.parse(k);if(!x.runToken||x.scope.projectId!==m.projectId||x.scope.environment!==m.environment||x.run.source.type!=="funnel"||x.run.source.id!==e.command.funnelId||x.run.source.versionId!==e.command.versionId||e.runId!==void 0&&x.run.id!==e.runId)throw new L("INVALID_RESPONSE","Invalid entry Run");if(e.epoch!==M){R(e),u("identity_changed",e.command.entryId);return}oe(e,x.run);let C=be({...n,runToken:x.runToken,funnelId:e.command.funnelId,initialResponse:a?k:void 0});f=C,O=!0,await C.get(),O=!1;let Y=C.view;if(!Y||Y.id!==x.run.id||Y.source.type!=="funnel"||Y.source.id!==e.command.funnelId||Y.source.versionId!==e.command.versionId)throw new L("INVALID_RESPONSE","Entry Run version changed");if(!["running","waiting"].includes(Y.status)){X(e),R(e),u("run_ended",e.command.entryId);return}let{showFunnelRun:ue}=await import("./funnel-runtime-host-UKSOOA4H.js");if(!Q(e)){await K(C),u("left_screen",e.command.entryId),R(e);return}let _e=!1,Ae=!1;if(o&&!o.background){await K(C),u("in_progress",e.command.entryId),R(e);return}o&&te();let ne=document.createElement("div");ne.hidden=ge(Y),n.container.append(ne);let Ce=await ue(ne,{...n.host,client:C,appManifestRelease:n.appManifestRelease,onState(H){t(C,H),Z(n.host?.onState,H)},onDismiss(H){_e=!0,ne.remove(),H&&!["running","waiting"].includes(H.status)&&X(e),o?.client===C&&(o=void 0,C.reset(),q(),H&&H.status!=="completed"&&u("run_ended",e.command.entryId)),Z(n.host?.onDismiss,H)},onComplete(H){Ae=!0,X(e),o?.client===C&&te(),Z(n.host?.onComplete,H)},onError(H){Z(n.host?.onError,H),o?.client===C&&H instanceof L&&H.code==="FORBIDDEN"&&(X(e),te(),u("run_ended",e.command.entryId))}}).catch(H=>{throw ne.remove(),H});if(!Q(e)||_e||Ae){Ce.destroy(),ne.remove(),Q(e)||await K(C),R(e);return}let le=ge(C.view??Y);ne.hidden=le,o={host:Ce,client:C,slot:ne,entryId:e.command.entryId,background:le,runToken:x.runToken,owner:n.session.peek(),recovery:e},le||(F=e.visit),P=!0,R(e),u("started",e.command.entryId),le&&u("run_background",e.command.entryId)}catch(k){k instanceof L&&(!f||O&&k.code==="FORBIDDEN")&&k.status!==void 0&&k.status>=400&&k.status<500&&!k.retryable&&(X(e),R(e)),e.epoch===M&&!r&&(u("start_failed",e.command.entryId),Z(n.host?.onError,k))}finally{P||f?.reset(),e.dispatching=!1}}function ae(e){if(e.command.release!==n.appManifestRelease||e.target.release!==n.appManifestRelease)return!1;try{return se(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function W(){if(ce())return!1;let e=T.load();for(let a of e?.entries??[]){if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now()){T.forget(e.key,a.command.requestId);continue}if(a.command.requestId===o?.recovery.command.requestId||j.has(a.command.requestId)||!ae(a))continue;j.add(a.command.requestId);let f={...a,storageKey:e.key,epoch:M,visit:g};return A=f,re(f),!0}return!1}function de(){if(c=!1,r||!i||document.visibilityState==="hidden")return;ie();let e=o!==void 0&&!o.background;if(e&&(F=g),!W()){if(!z()){p=!0;return}p=!1;for(let a of b?.entries??[]){let f=`${a.funnelId}:${a.id}`;if(!(a.event!=="screen_enter"||V.has(f)||!B(a))){if(!n.session.peek()){u("identity_required",a.id);continue}if(F===g){V.add(f),e&&u("in_progress",a.id);continue}if(A){u("in_progress",a.id);return}V.add(f),ee(a);break}}}}let q=()=>{!c&&!r&&(c=!0,queueMicrotask(de))};function ie(){let e=location.origin+location.pathname;return e===U?!1:(U=e,g++,p=!0,V.clear(),j.clear(),!0)}function Xe(){ie()&&q()}function Re(e){if(!e.isTrusted||e.button!==0||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||document.visibilityState==="hidden")return;let a=e.target;if(!(a instanceof Element)||a.closest("[data-indiana-funnel]"))return;let f=a.closest("button,a,input");if(!(!f||f.matches(":disabled,[aria-disabled='true']")||f.closest("[hidden],[inert],[aria-hidden='true']")))for(let P of b?.entries??[]){let O=P.target.button;if(!(P.event!=="button_click"||!O||!B(P))){try{let K=Ie(document);if(!f.matches(O.selector)||K(O.selector,f)!==1)continue}catch{u("incompatible",P.id);continue}ee(P);break}}}async function Se(){if(r)return;if(s)return s;let e=++I,a=new AbortController;v=a;let f,P=new Promise((k,E)=>{f=()=>E(new L("TIMEOUT","Funnel entry configuration read cancelled or timed out")),a.signal.addEventListener("abort",f,{once:!0})}),O=setTimeout(()=>a.abort(),n.timeoutMs??5e3),K=(async()=>{let k=async()=>{let ue=await _(`${w}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:a.signal});if(!ue.ok)throw new L("SERVICE_UNAVAILABLE","Funnel entries unavailable",ue.status);return fe.parse(await ue.json())},E=await Promise.race([k(),P]),x=Date.parse(E.validatedAt),C=Date.parse(E.validUntil);if(E.scope.projectId!==m.projectId||E.scope.environment!==m.environment||E.scope.environmentId!==n.environmentId||E.release!==n.appManifestRelease||C<=Date.now()||x>Date.now()+5e3||C-x>6e4||C<=x)throw new L("INVALID_RESPONSE","Entry configuration scope or deadline changed");if(r||e!==I)return;let Y=b===void 0;b=E,$=C,J=performance.now()+Math.min(C-Date.now(),6e4),(Y||p)&&q()})();s=K;try{await K}finally{clearTimeout(O),a.signal.removeEventListener("abort",f),s===K&&(s=void 0)}}async function Ye(){if(!(!i||r)){try{await Se()}catch{r||u("configuration_unavailable")}q()}}let Pe=pe({document,run:Ye,delay:()=>i&&!r?15e3:void 0});return{async start(){i||r||(i=!0,U=location.origin+location.pathname,h=he(Xe),d=n.session.subscribeIdentity(()=>{M++,p=!0,A=void 0,V.clear(),F=-1,j.clear(),o&&S(o,o.owner,!1),te(),q()}),l=new MutationObserver(q),l.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",Re,!0),addEventListener("pagehide",N),await Pe.refresh())},refresh:Se,async retry(){A&&!r&&A.epoch===M&&await re(A)},destroy(){r=!0,I++,Pe.destroy(),v?.abort(),l?.disconnect(),h?.(),d?.(),document.removeEventListener("click",Re,!0),removeEventListener("pagehide",N),N(),te(),D.dispose(),b=void 0}}}function In(n){let w=ye(n.baseUrl),m=n.fetch??globalThis.fetch.bind(globalThis),D,_=0,b=0,r=!1,i=!1,I=0,g=0,U=-1,M=!1,$="",J,c,s,p,v=new Set,h,d,l,o=(t,S)=>Z(n.onStatus,t,S),F=()=>Date.now()<_&&performance.now()<b;function A(t){try{return F()&&t.target.release===n.appManifestRelease&&se(t.target.render,document,location.pathname,()=>{})}catch{return o("incompatible",t.id),!1}}function R(){let t=l;l=void 0,t?.host.destroy(),t?.slot.remove()}async function V(t){if(t.dispatching)return;t.dispatching=!0;let S=I;try{let N=await t.process.open({operation:"entry_start",funnelId:t.entry.funnelId,versionId:t.entry.versionId,entryId:t.entry.id,release:n.appManifestRelease,locale:n.locale??"en"}),{showFunnelRun:z}=await import("./funnel-runtime-host-UKSOOA4H.js");if(r||S!==I||d!==t)return;let B=document.createElement("div");n.container.append(B),U=g;let Q=await z(B,{...n.host,client:N.controller,appManifestRelease:n.appManifestRelease,onDismiss(ee){l?.process===t.process&&(l=void 0,B.remove()),Z(n.host?.onDismiss,ee)}});if(r||S!==I||d!==t){Q.destroy(),B.remove();return}l={entry:t.entry,process:t.process,host:Q,slot:B},d=void 0,o("run_presented",t.entry.id)}catch(N){if(r||S!==I||d!==t)return;N instanceof L&&"result"in N?(d=void 0,t.process.destroy(),o("suppressed",t.entry.id),j()):o("entry_unavailable",t.entry.id)}finally{t.dispatching=!1}}function u(t){if(r||d||l||h||U===g||!A(t))return;let S=`${g}:${t.id}`;if(v.has(S))return;v.add(S);let N={entry:t,process:n.createProcess(t),visit:g};d=N,V(N)}function j(){M||r||(M=!0,queueMicrotask(()=>{if(M=!1,!(r||document.visibilityState==="hidden"||!F()||d||l||h||U===g)){for(let t of D?.entries??[])if(t.event==="screen_enter"&&A(t)){u(t);break}}}))}function T(t){if(!t.isTrusted||t.defaultPrevented||!(t.target instanceof Element)||d||l||h||U===g)return;let S=Ie(document,()=>{});for(let N of D?.entries??[]){let z=N.target.button;if(N.event!=="button_click"||!z||!A(N))continue;let B=t.target.closest(z.selector);if(!(!B||B.tagName.toLowerCase()!==z.tag||S(z.selector)!==1||B.matches(":disabled")||B.closest('[inert],[hidden],[aria-hidden="true"]'))){u(N);break}}}let X=()=>{let t=location.origin+location.pathname;t!==$&&($=t,g++,v.clear(),j())};async function oe(){if(r)return;if(c)return c;let t=I,S=new AbortController;J=S;let N,z=new Promise((re,ae)=>{N=ae}),B=()=>N(new L("TIMEOUT","Funnel entry read cancelled"));S.signal.addEventListener("abort",B,{once:!0});let Q=setTimeout(()=>S.abort(),n.timeoutMs??5e3),ee=(async()=>{let re=encodeURIComponent(JSON.stringify(["funnel-process/1"])),ae=async()=>{let ie=await m(`${w}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}&executionContracts=${re}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:S.signal});if(!ie.ok)throw new L("SERVICE_UNAVAILABLE","Funnel entries unavailable",ie.status);return fe.parse(await ie.json())},W=await Promise.race([ae(),z]),de=Date.parse(W.validatedAt),q=Date.parse(W.validUntil);if(W.scope.projectId!==n.scope.projectId||W.scope.environment!==n.scope.environment||W.scope.environmentId!==n.environmentId||W.release!==n.appManifestRelease||q<=Date.now()||de>Date.now()+5e3||q<=de||q-de>6e4)throw new L("INVALID_RESPONSE","Entry scope or deadline changed");r||t!==I||(D=W,_=q,b=performance.now()+Math.min(q-Date.now(),6e4),j())})();c=ee;try{await ee}finally{clearTimeout(Q),S.signal.removeEventListener("abort",B),c===ee&&(c=void 0)}}async function te(){if(!(!i||r))try{await oe()}catch{r||o("configuration_unavailable")}}let ce=pe({document,run:te,delay:()=>i&&!r?15e3:void 0});return{async start(){i||r||(i=!0,$=location.origin+location.pathname,s=he(X),p=new MutationObserver(j),p.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",T,!0),await ce.refresh())},refresh:oe,async retry(){d&&!r&&await V(d)},async syncIdentity(){let t=l??d??h;if(t)try{let S=await t.process.syncIdentity();return h===t&&(d={entry:t.entry,process:t.process,visit:g},h=void 0,await V(d)),S}catch(S){throw t.process.view||(h={entry:t.entry,process:t.process,visit:g},d=void 0,R()),S}},async detach(){I++,J?.abort();let t=l??d??h;t&&(h={entry:t.entry,process:t.process,visit:g}),d=void 0,R(),t&&await t.process.detach()},destroy(){r=!0,I++,ce.destroy(),J?.abort(),p?.disconnect(),s?.(),document.removeEventListener("click",T,!0);let t=l??d??h;d=void 0,h=void 0,R(),t?.process.destroy(),D=void 0}}}async function $n(n,w){return(await import("./paywall-VYUBYBUI.js")).showPaywall(n,w)}async function zn(...n){return n[1]=qe(n[1]),(await import("./paywall-session-E5V42XUT.js")).createPaywallSession(...n)}async function Jn(...n){let w=n[1].signal?.aborted?void 0:Ue(n[1].client);try{return import("./screen-renderer-R5GH7XLV.js").catch(()=>{}),import("./paywall-VYUBYBUI.js").catch(()=>{}),await(await Je(()=>import("./funnel-runtime-host-UKSOOA4H.js"),n[1].prepared)).showFunnelRun(...n)}finally{w?.()}}async function Je(n,w){try{return await n()}catch(m){throw w&&w.state!=="adopted"&&await import("./funnel-paywall-prerender-QHCUZZY3.js").then(D=>D.preparedInternals(w)?.release(),()=>{}),m}}async function Xn(...n){return import("./screen-renderer-R5GH7XLV.js").catch(()=>{}),import("./paywall-VYUBYBUI.js").catch(()=>{}),(await Je(()=>import("./funnel-host-purchase-Z7FCJ5CX.js"),n[1].prepared)).showFunnelPurchase(...n)}async function Yn(...n){return import("./funnel-host-purchase-Z7FCJ5CX.js").catch(()=>{}),import("./screen-renderer-R5GH7XLV.js").catch(()=>{}),(await import("./funnel-paywall-prerender-QHCUZZY3.js")).prerenderFunnelPurchase(...n)}async function Zn(...n){return(await import("./content-AJDTSI7A.js")).mountContent(...n)}async function Wn(...n){return(await import("./content-AJDTSI7A.js")).prepareContent(...n)}export{L as LongplayError,y as MerchantBridgeError,tn as createBrowserFunnelCommandStorage,dn as createBrowserFunnelPurchaseStorage,an as createConfigurationSync,en as createFeatureClient,cn as createFunnelClient,mn as createFunnelPageExperiments,ln as createFunnelProcess,un as createFunnelPurchaseClient,be as createFunnelRunController,hn as createIamFunnelEntries,In as createIamFunnelProcessEntries,fn as createLocalFunnelClient,nn as createLongplay,yn as createMerchantBridge,zn as createPaywallSession,sn as evaluateFunnelNode,We as formatCouponDiscount,Ze as formatCouponMoney,Qe as formatCouponTerms,rn as getPaywallRecovery,Zn as mountContent,Wn as prepareContent,on as preparePaywallFallback,Yn as prerenderFunnelPurchase,Xn as showFunnelPurchase,Jn as showFunnelRun,$n as showPaywall};
@@ -0,0 +1 @@
1
+ import{N as r,O as m,h as e}from"./chunk-CKKIB2HC.js";import"./chunk-ZGCKQWQ5.js";import"./chunk-VYFSRHXM.js";import"./chunk-KE26KWIU.js";import"./chunk-TJGIT5CU.js";import"./chunk-V7MMTILA.js";import"./chunk-VF6QMMEA.js";import"./chunk-BID4UGWB.js";import"./chunk-WOT6VMZA.js";export{m as merchantBridgeCommerceSchema,r as merchantBridgeOperationSchema,e as merchantOperationLookupSchema};