@tinkerlandai/longplay-sdk 0.10.30 → 0.10.31

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.
@@ -1 +1 @@
1
- import{b as d}from"./chunk-OHOROFWN.js";import{a as u}from"./chunk-DSPLGTQI.js";function m(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let i of document.cookie.split(";"))if(i.trim().startsWith(`${e}=`))try{t=decodeURIComponent(i.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function y(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function g(e=d){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var o=new Set,s;function S(e){let t=()=>e();if(o.add(t),!s){let i=!0,a=history.pushState,p=history.replaceState,r=()=>{if(i)for(let n of[...o])o.has(n)&&u(n)},c=function(...n){a.apply(this,n),r()},h=function(...n){p.apply(this,n),r()};history.pushState=c,history.replaceState=h,addEventListener("popstate",r),addEventListener("hashchange",r),s=()=>{i=!1,history.pushState===c&&(history.pushState=a),history.replaceState===h&&(history.replaceState=p),removeEventListener("popstate",r),removeEventListener("hashchange",r)}}return()=>{o.delete(t)&&(o.size||(s?.(),s=void 0))}}export{m as a,y as b,g as c,S as d};
1
+ import{b as d}from"./chunk-FVGUBIVT.js";import{a as u}from"./chunk-DSPLGTQI.js";function m(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let i of document.cookie.split(";"))if(i.trim().startsWith(`${e}=`))try{t=decodeURIComponent(i.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function y(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function g(e=d){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var o=new Set,s;function S(e){let t=()=>e();if(o.add(t),!s){let i=!0,a=history.pushState,p=history.replaceState,r=()=>{if(i)for(let n of[...o])o.has(n)&&u(n)},c=function(...n){a.apply(this,n),r()},h=function(...n){p.apply(this,n),r()};history.pushState=c,history.replaceState=h,addEventListener("popstate",r),addEventListener("hashchange",r),s=()=>{i=!1,history.pushState===c&&(history.pushState=a),history.replaceState===h&&(history.replaceState=p),removeEventListener("popstate",r),removeEventListener("hashchange",r)}}return()=>{o.delete(t)&&(o.size||(s?.(),s=void 0))}}export{m as a,y as b,g as c,S as d};
@@ -1 +1 @@
1
- import{i as ie}from"./chunk-TF2OFTYS.js";import{a as Z,c as ee,d as te,e as ne,g as re,h as oe,i as se,k as N}from"./chunk-RBMOWJGE.js";import{b as X}from"./chunk-YXCEZAQL.js";import{r as V}from"./chunk-4ZVVG5LM.js";import"./chunk-ITVSLSRM.js";import"./chunk-SJSCROSL.js";import"./chunk-ACFQLHJR.js";import"./chunk-CLAZ7NVN.js";import"./chunk-J4VTKRH7.js";import{E as $,P as G,U as R,la as Y,ma as K}from"./chunk-WRUW2UIJ.js";import"./chunk-FJGJQGYF.js";import{a as p}from"./chunk-HJLGRW4A.js";import"./chunk-XIP32WI7.js";import"./chunk-OHOROFWN.js";import{b as u}from"./chunk-ZY4XAKNQ.js";import{a as h}from"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.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};
1
+ import{i as ie}from"./chunk-TF2OFTYS.js";import{a as Z,c as ee,d as te,e as ne,g as re,h as oe,i as se,k as N}from"./chunk-RBMOWJGE.js";import{b as X}from"./chunk-YXCEZAQL.js";import{r as V}from"./chunk-4ZVVG5LM.js";import"./chunk-ITVSLSRM.js";import"./chunk-SJSCROSL.js";import"./chunk-ACFQLHJR.js";import"./chunk-XZEGVBAI.js";import"./chunk-J4VTKRH7.js";import{E as $,P as G,U as R,la as Y,ma as K}from"./chunk-WRUW2UIJ.js";import"./chunk-FJGJQGYF.js";import{a as p}from"./chunk-HJLGRW4A.js";import"./chunk-XIP32WI7.js";import"./chunk-FVGUBIVT.js";import{b as u}from"./chunk-ZY4XAKNQ.js";import{a as h}from"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.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};
@@ -1 +1 @@
1
- import{b as y}from"./chunk-TJZESXCS.js";import{d as A}from"./chunk-U3QUHGQX.js";import"./chunk-UWYL2QCF.js";import{f as g,g as I}from"./chunk-RBMOWJGE.js";import"./chunk-JWPTJLAN.js";import"./chunk-TMZGZAWM.js";import"./chunk-XHQBABH6.js";import"./chunk-STPMMA64.js";import"./chunk-QPHT6QHE.js";import"./chunk-4ZVVG5LM.js";import"./chunk-LZV4QJ5E.js";import"./chunk-ITVSLSRM.js";import"./chunk-SJSCROSL.js";import"./chunk-B3KFE57L.js";import"./chunk-ACFQLHJR.js";import"./chunk-CLAZ7NVN.js";import"./chunk-J4VTKRH7.js";import"./chunk-WRUW2UIJ.js";import"./chunk-FJGJQGYF.js";import{a as c}from"./chunk-HJLGRW4A.js";import"./chunk-XIP32WI7.js";import"./chunk-SLUA7ABW.js";import"./chunk-XRR5X74T.js";import"./chunk-3VUPVXAV.js";import"./chunk-OHOROFWN.js";import"./chunk-ZY4XAKNQ.js";import{a as i}from"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";var d=new WeakMap;function T(h,e){let P=d.get(e.client);if(P)return P;let m=Promise.resolve().then(async()=>{let n=!1,s,w,E=!1,v=()=>{},r=e.signal?AbortSignal.any([e.signal,e.client.identitySignal]):e.client.identitySignal,u=()=>{d.get(e.client)===m&&d.delete(e.client),r.removeEventListener("abort",f),v()},o=I(h,e,"funnel",f);function f(){n||(n=!0,o.finish("dismissed"),s?s.destroy():(u(),i(e.onDismiss,null)))}r.addEventListener("abort",f,{once:!0});try{let b=function(){!n&&!r.aborted&&!E&&w&&e.client.recovery.status==="complete"&&(E=!0,i(e.onComplete,structuredClone(w)))};var C=b;r.throwIfAborted(),o.start(!0,e.start?.locale);let l=await o.wait(e.start?e.client.start(e.start):e.client.refresh(),g);r.throwIfAborted();let O=e.client.controller;return l.mode!=="run"||l.status==="blocked"||!O?(o.finish("skipped"),u(),null):(r.removeEventListener("abort",f),v=e.client.subscribe(b),s=await A(h,{...e,client:O,signal:r,checkoutNavigation:"after_confirmation",onCheckoutUrl(t){if(r.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");if(y(e.client.recovery)!==t)throw new c("PURCHASE_PENDING","Checkout differs from the original recovery proof");return e.onCheckoutUrl?e.onCheckoutUrl(t):h.ownerDocument.defaultView?.location.assign(t)},async resolveOfferId(t){if(r.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");let a=e.client.attempt;if(!a)throw new c("PURCHASE_PENDING","Read the original Start before selecting an offer");let F=await e.resolveOfferId?.(t,a);if(r.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");if(e.client.attempt?.requestId!==a.requestId)throw new c("PURCHASE_STORAGE_CONFLICT","The original purchase changed while selecting an offer");return F},onComplete(t){w=t,b()},onError(t){i(e.onError,t),t instanceof c&&t.status===401&&!r.aborted&&e.client.refresh().catch(a=>i(e.onError,a))},onDismiss(t){n=!0,u(),i(e.onDismiss,t)}},o),n||r.aborted?(s.destroy(),null):s)}catch(l){if(n)return null;throw o.finish("error",l),u(),i(e.onError,l),l}});return d.set(e.client,m),m}export{T as showFunnelPurchase};
1
+ import{b as y}from"./chunk-YEXRETKV.js";import{d as A}from"./chunk-PI25NLDV.js";import"./chunk-UWYL2QCF.js";import{f as g,g as I}from"./chunk-RBMOWJGE.js";import"./chunk-2TPPGW7V.js";import"./chunk-TMZGZAWM.js";import"./chunk-7Z7JT4HE.js";import"./chunk-WK4WQZHK.js";import"./chunk-QPHT6QHE.js";import"./chunk-4ZVVG5LM.js";import"./chunk-LZV4QJ5E.js";import"./chunk-ITVSLSRM.js";import"./chunk-SJSCROSL.js";import"./chunk-B3KFE57L.js";import"./chunk-ACFQLHJR.js";import"./chunk-XZEGVBAI.js";import"./chunk-J4VTKRH7.js";import"./chunk-WRUW2UIJ.js";import"./chunk-FJGJQGYF.js";import{a as c}from"./chunk-HJLGRW4A.js";import"./chunk-XIP32WI7.js";import"./chunk-SLUA7ABW.js";import"./chunk-ZYTT7ZAB.js";import"./chunk-3VUPVXAV.js";import"./chunk-FVGUBIVT.js";import"./chunk-ZY4XAKNQ.js";import{a as i}from"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";var d=new WeakMap;function T(h,e){let P=d.get(e.client);if(P)return P;let m=Promise.resolve().then(async()=>{let n=!1,s,w,E=!1,v=()=>{},r=e.signal?AbortSignal.any([e.signal,e.client.identitySignal]):e.client.identitySignal,u=()=>{d.get(e.client)===m&&d.delete(e.client),r.removeEventListener("abort",f),v()},o=I(h,e,"funnel",f);function f(){n||(n=!0,o.finish("dismissed"),s?s.destroy():(u(),i(e.onDismiss,null)))}r.addEventListener("abort",f,{once:!0});try{let b=function(){!n&&!r.aborted&&!E&&w&&e.client.recovery.status==="complete"&&(E=!0,i(e.onComplete,structuredClone(w)))};var C=b;r.throwIfAborted(),o.start(!0,e.start?.locale);let l=await o.wait(e.start?e.client.start(e.start):e.client.refresh(),g);r.throwIfAborted();let O=e.client.controller;return l.mode!=="run"||l.status==="blocked"||!O?(o.finish("skipped"),u(),null):(r.removeEventListener("abort",f),v=e.client.subscribe(b),s=await A(h,{...e,client:O,signal:r,checkoutNavigation:"after_confirmation",onCheckoutUrl(t){if(r.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");if(y(e.client.recovery)!==t)throw new c("PURCHASE_PENDING","Checkout differs from the original recovery proof");return e.onCheckoutUrl?e.onCheckoutUrl(t):h.ownerDocument.defaultView?.location.assign(t)},async resolveOfferId(t){if(r.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");let a=e.client.attempt;if(!a)throw new c("PURCHASE_PENDING","Read the original Start before selecting an offer");let F=await e.resolveOfferId?.(t,a);if(r.throwIfAborted(),n)throw new DOMException("Presentation dismissed","AbortError");if(e.client.attempt?.requestId!==a.requestId)throw new c("PURCHASE_STORAGE_CONFLICT","The original purchase changed while selecting an offer");return F},onComplete(t){w=t,b()},onError(t){i(e.onError,t),t instanceof c&&t.status===401&&!r.aborted&&e.client.refresh().catch(a=>i(e.onError,a))},onDismiss(t){n=!0,u(),i(e.onDismiss,t)}},o),n||r.aborted?(s.destroy(),null):s)}catch(l){if(n)return null;throw o.finish("error",l),u(),i(e.onError,l),l}});return d.set(e.client,m),m}export{T as showFunnelPurchase};
@@ -1 +1 @@
1
- import{c as a,d as b}from"./chunk-U3QUHGQX.js";import"./chunk-UWYL2QCF.js";import"./chunk-RBMOWJGE.js";import"./chunk-ITVSLSRM.js";import"./chunk-SJSCROSL.js";import"./chunk-B3KFE57L.js";import"./chunk-ACFQLHJR.js";import"./chunk-CLAZ7NVN.js";import"./chunk-J4VTKRH7.js";import"./chunk-WRUW2UIJ.js";import"./chunk-FJGJQGYF.js";import"./chunk-HJLGRW4A.js";import"./chunk-XIP32WI7.js";import"./chunk-SLUA7ABW.js";import"./chunk-XRR5X74T.js";import"./chunk-OHOROFWN.js";import"./chunk-ZY4XAKNQ.js";import"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";export{a as showFunnelRun,b as showObservedFunnelRun};
1
+ import{c as a,d as b}from"./chunk-PI25NLDV.js";import"./chunk-UWYL2QCF.js";import"./chunk-RBMOWJGE.js";import"./chunk-ITVSLSRM.js";import"./chunk-SJSCROSL.js";import"./chunk-B3KFE57L.js";import"./chunk-ACFQLHJR.js";import"./chunk-XZEGVBAI.js";import"./chunk-J4VTKRH7.js";import"./chunk-WRUW2UIJ.js";import"./chunk-FJGJQGYF.js";import"./chunk-HJLGRW4A.js";import"./chunk-XIP32WI7.js";import"./chunk-SLUA7ABW.js";import"./chunk-ZYTT7ZAB.js";import"./chunk-FVGUBIVT.js";import"./chunk-ZY4XAKNQ.js";import"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";export{a as showFunnelRun,b as showObservedFunnelRun};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as cn,c as dn}from"./chunk-TJZESXCS.js";import{a as Ue,b as fn,c as Ie}from"./chunk-U3QUHGQX.js";import{f as pe}from"./chunk-UWYL2QCF.js";import"./chunk-RBMOWJGE.js";import{a as en,c as sn,d as un}from"./chunk-3TXBNPEP.js";import"./chunk-JWPTJLAN.js";import{a as an}from"./chunk-U6BYOYEE.js";import"./chunk-TMZGZAWM.js";import{h as Qe,i as on,k as ln}from"./chunk-DIMBCG2C.js";import"./chunk-23WNEOK4.js";import"./chunk-JNSU2AP2.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-XHQBABH6.js";import{a as qe}from"./chunk-STPMMA64.js";import"./chunk-QPHT6QHE.js";import"./chunk-4ZVVG5LM.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-LZV4QJ5E.js";import{$ as Le,l as Ye,m as Ze,n as We}from"./chunk-ITVSLSRM.js";import"./chunk-SJSCROSL.js";import{c as tn,d as rn}from"./chunk-B3KFE57L.js";import"./chunk-ACFQLHJR.js";import{b as be}from"./chunk-CLAZ7NVN.js";import"./chunk-J4VTKRH7.js";import"./chunk-WRUW2UIJ.js";import"./chunk-FJGJQGYF.js";import{a as H}from"./chunk-HJLGRW4A.js";import"./chunk-XIP32WI7.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-XRR5X74T.js";import"./chunk-3VUPVXAV.js";import"./chunk-OHOROFWN.js";import{b as K}from"./chunk-ZY4XAKNQ.js";import{a as Z}from"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.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-LJKL7PNJ.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-L7M4VA3Z.js")).showPaywall(n,A)}async function Jn(...n){return n[1]=qe(n[1]),(await import("./paywall-session-KRYPLLPR.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-ANA2Y3WR.js"),import("./screen-renderer-W5MP4KVG.js"),import("./paywall-L7M4VA3Z.js")]);return await m.showFunnelRun(...n)}finally{A?.()}}async function Yn(...n){return(await import("./funnel-host-purchase-NFYF2NY4.js")).showFunnelPurchase(...n)}async function Zn(...n){return(await import("./content-AU7IRQXV.js")).mountContent(...n)}async function Wn(...n){return(await import("./content-AU7IRQXV.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 cn,c as dn}from"./chunk-YEXRETKV.js";import{a as Ue,b as fn,c as Ie}from"./chunk-PI25NLDV.js";import{f as pe}from"./chunk-UWYL2QCF.js";import"./chunk-RBMOWJGE.js";import{a as en,c as sn,d as un}from"./chunk-D3UU546S.js";import"./chunk-2TPPGW7V.js";import{a as an}from"./chunk-NH5ML5SB.js";import"./chunk-TMZGZAWM.js";import{h as Qe,i as on,k as ln}from"./chunk-2QQZSMTB.js";import"./chunk-23WNEOK4.js";import"./chunk-JNSU2AP2.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-7Z7JT4HE.js";import{a as qe}from"./chunk-WK4WQZHK.js";import"./chunk-QPHT6QHE.js";import"./chunk-4ZVVG5LM.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-LZV4QJ5E.js";import{$ as Le,l as Ye,m as Ze,n as We}from"./chunk-ITVSLSRM.js";import"./chunk-SJSCROSL.js";import{c as tn,d as rn}from"./chunk-B3KFE57L.js";import"./chunk-ACFQLHJR.js";import{b as be}from"./chunk-XZEGVBAI.js";import"./chunk-J4VTKRH7.js";import"./chunk-WRUW2UIJ.js";import"./chunk-FJGJQGYF.js";import{a as H}from"./chunk-HJLGRW4A.js";import"./chunk-XIP32WI7.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-ZYTT7ZAB.js";import"./chunk-3VUPVXAV.js";import"./chunk-FVGUBIVT.js";import{b as K}from"./chunk-ZY4XAKNQ.js";import{a as Z}from"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.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-LJKL7PNJ.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-DI62MX5L.js")).showPaywall(n,A)}async function Jn(...n){return n[1]=qe(n[1]),(await import("./paywall-session-AW6R3PJB.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-CJTPLZ4N.js"),import("./screen-renderer-W5MP4KVG.js"),import("./paywall-DI62MX5L.js")]);return await m.showFunnelRun(...n)}finally{A?.()}}async function Yn(...n){return(await import("./funnel-host-purchase-IRFPNIZY.js")).showFunnelPurchase(...n)}async function Zn(...n){return(await import("./content-OY5MRXF5.js")).mountContent(...n)}async function Wn(...n){return(await import("./content-OY5MRXF5.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 +1 @@
1
- import"./chunk-5N7QFF5M.js";import"./chunk-BQLT2LDP.js";import"./chunk-CLAZ7NVN.js";import"./chunk-J4VTKRH7.js";import{a as i}from"./chunk-HJLGRW4A.js";import"./chunk-XIP32WI7.js";import"./chunk-OHOROFWN.js";import{b as A}from"./chunk-ZY4XAKNQ.js";import"./chunk-WOT6VMZA.js";var c=A.number().int().min(0).max(1e9);function R(e,o){let a=c.parse(e.promptTokens),p=c.parse(e.completionTokens),s=c.parse(e.promptTokensDetails?.cachedTokens??0),t=c.parse(e.promptTokensDetails?.cacheWriteTokens??0),r=c.parse(e.promptTokensDetails?.audioTokens??0),l=c.parse(e.completionTokensDetails?.audioTokens??0),n=c.parse(e.completionTokensDetails?.reasoningTokens??0);if(c.parse(e.totalTokens)!==a+p||s+t+r>a||n+l>p||(e.promptTokensDetails?.videoTokens??0)>0)throw new i("AI_USAGE_UNAVAILABLE","Token pools must conserve usage; video needs an explicit token mapper");return{input:a-s-t-r,output:p-l-(o==="separate"?n:0),cache_read:s,cache_write:t,input_audio:r,output_audio:l,reasoning:o==="separate"?n:0}}function I(e){if(!Number.isFinite(e)||e<0)throw new i("AI_USAGE_UNAVAILABLE","Provider cost must be a nonnegative USD amount");let o=String(e),a=o.includes("e")?e.toFixed(18).replace(/0+$/,"").replace(/\.$/,""):o;if(!/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/.test(a)||Number(a)!==e)throw new i("AI_USAGE_UNAVAILABLE","Provider cost exceeds the supported precision");return a}async function f(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning)||!e.modelId||!e.generationId)throw new i("INVALID_REQUEST","Actual model, generation ID and reasoning pricing are required");let o={context:e.context,generationId:e.generationId,modelId:`openrouter/${e.modelId}`,usage:e.usage,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(o);let a=e.mapTokens?e.mapTokens(e.usage):R(e.usage,e.reasoning),p=e.usage.cost==null?void 0:I(e.usage.cost),s=e.quote??await e.pricing.quoteTokens({modelId:o.modelId,tokens:a});if(s.pricing.modelId!==o.modelId||Object.keys(a).some(l=>a[l]!==s.tokens[l]))throw new i("INVALID_REQUEST","Saved quote must match the provider model and token pools");await e.persist({...o,tokens:a,quote:s,phase:"quoted"});let t=await e.pricing.trackTokens(e.client,{...e.context,quote:s,providerCostUsd:p,generationId:e.generationId});if(!t.receipt.accepted)throw new i("AI_BALANCE_REJECTED","OpenRouter usage was saved but the balance request was rejected");let r={...o,tokens:a,quote:s,receipt:t,phase:"settled"};return await e.persist(r),r}function T(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning))throw new i("INVALID_REQUEST","Reasoning pricing is required");let o=e.openRouter.chat;async function a(t){if(!t.usage||!t.modelId||!t.generationId)throw new i("AI_USAGE_UNAVAILABLE","OpenRouter did not return final usage and the actual model");await f({...e,context:t.context,generationId:t.generationId,modelId:t.modelId.slice(11),usage:t.usage})}let p=async(t,r)=>{let n={context:await e.context(),generationId:null,modelId:null,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"},d;try{d=await o.send(t,r)}catch(g){throw await e.persist(n),g}if(!(d instanceof ReadableStream)){if(n={...n,generationId:d.id,modelId:d.model?`openrouter/${d.model}`:null,usage:d.usage??null},!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter omitted final accounting");return await a(n),d}let w=d.getReader(),m=!1;return new ReadableStream({async pull(g){try{let{value:u,done:k}=await w.read();if(k){if(m=!0,!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter stream ended without final accounting");await a(n),g.close();return}if(u.error)throw new i("AI_PROVIDER_ERROR",u.error.message);u.usage&&(n={...n,generationId:u.id,modelId:u.model?`openrouter/${u.model}`:null,usage:u.usage}),g.enqueue(u)}catch(u){m||(m=!0,await e.persist(n)),await w.cancel(u),g.error(u)}},async cancel(g){m||(m=!0,await e.persist(n)),await w.cancel(g)}})},s=new Proxy(o,{get(t,r){return r==="send"?p:Reflect.get(t,r,t)}});return new Proxy(e.openRouter,{get(t,r){return r==="chat"?s:Reflect.get(t,r,t)}})}export{T as createOpenRouterUsageClient,f as trackOpenRouterUsage};
1
+ import"./chunk-5N7QFF5M.js";import"./chunk-BQLT2LDP.js";import"./chunk-XZEGVBAI.js";import"./chunk-J4VTKRH7.js";import{a as i}from"./chunk-HJLGRW4A.js";import"./chunk-XIP32WI7.js";import"./chunk-FVGUBIVT.js";import{b as A}from"./chunk-ZY4XAKNQ.js";import"./chunk-WOT6VMZA.js";var c=A.number().int().min(0).max(1e9);function R(e,o){let a=c.parse(e.promptTokens),p=c.parse(e.completionTokens),s=c.parse(e.promptTokensDetails?.cachedTokens??0),t=c.parse(e.promptTokensDetails?.cacheWriteTokens??0),r=c.parse(e.promptTokensDetails?.audioTokens??0),l=c.parse(e.completionTokensDetails?.audioTokens??0),n=c.parse(e.completionTokensDetails?.reasoningTokens??0);if(c.parse(e.totalTokens)!==a+p||s+t+r>a||n+l>p||(e.promptTokensDetails?.videoTokens??0)>0)throw new i("AI_USAGE_UNAVAILABLE","Token pools must conserve usage; video needs an explicit token mapper");return{input:a-s-t-r,output:p-l-(o==="separate"?n:0),cache_read:s,cache_write:t,input_audio:r,output_audio:l,reasoning:o==="separate"?n:0}}function I(e){if(!Number.isFinite(e)||e<0)throw new i("AI_USAGE_UNAVAILABLE","Provider cost must be a nonnegative USD amount");let o=String(e),a=o.includes("e")?e.toFixed(18).replace(/0+$/,"").replace(/\.$/,""):o;if(!/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/.test(a)||Number(a)!==e)throw new i("AI_USAGE_UNAVAILABLE","Provider cost exceeds the supported precision");return a}async function f(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning)||!e.modelId||!e.generationId)throw new i("INVALID_REQUEST","Actual model, generation ID and reasoning pricing are required");let o={context:e.context,generationId:e.generationId,modelId:`openrouter/${e.modelId}`,usage:e.usage,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(o);let a=e.mapTokens?e.mapTokens(e.usage):R(e.usage,e.reasoning),p=e.usage.cost==null?void 0:I(e.usage.cost),s=e.quote??await e.pricing.quoteTokens({modelId:o.modelId,tokens:a});if(s.pricing.modelId!==o.modelId||Object.keys(a).some(l=>a[l]!==s.tokens[l]))throw new i("INVALID_REQUEST","Saved quote must match the provider model and token pools");await e.persist({...o,tokens:a,quote:s,phase:"quoted"});let t=await e.pricing.trackTokens(e.client,{...e.context,quote:s,providerCostUsd:p,generationId:e.generationId});if(!t.receipt.accepted)throw new i("AI_BALANCE_REJECTED","OpenRouter usage was saved but the balance request was rejected");let r={...o,tokens:a,quote:s,receipt:t,phase:"settled"};return await e.persist(r),r}function T(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning))throw new i("INVALID_REQUEST","Reasoning pricing is required");let o=e.openRouter.chat;async function a(t){if(!t.usage||!t.modelId||!t.generationId)throw new i("AI_USAGE_UNAVAILABLE","OpenRouter did not return final usage and the actual model");await f({...e,context:t.context,generationId:t.generationId,modelId:t.modelId.slice(11),usage:t.usage})}let p=async(t,r)=>{let n={context:await e.context(),generationId:null,modelId:null,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"},d;try{d=await o.send(t,r)}catch(g){throw await e.persist(n),g}if(!(d instanceof ReadableStream)){if(n={...n,generationId:d.id,modelId:d.model?`openrouter/${d.model}`:null,usage:d.usage??null},!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter omitted final accounting");return await a(n),d}let w=d.getReader(),m=!1;return new ReadableStream({async pull(g){try{let{value:u,done:k}=await w.read();if(k){if(m=!0,!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter stream ended without final accounting");await a(n),g.close();return}if(u.error)throw new i("AI_PROVIDER_ERROR",u.error.message);u.usage&&(n={...n,generationId:u.id,modelId:u.model?`openrouter/${u.model}`:null,usage:u.usage}),g.enqueue(u)}catch(u){m||(m=!0,await e.persist(n)),await w.cancel(u),g.error(u)}},async cancel(g){m||(m=!0,await e.persist(n)),await w.cancel(g)}})},s=new Proxy(o,{get(t,r){return r==="send"?p:Reflect.get(t,r,t)}});return new Proxy(e.openRouter,{get(t,r){return r==="chat"?s:Reflect.get(t,r,t)}})}export{T as createOpenRouterUsageClient,f as trackOpenRouterUsage};
package/dist/page.js CHANGED
@@ -1 +1 @@
1
- import{d as o,e as r,f as e,g as f}from"./chunk-U6ULFK7M.js";import"./chunk-XRR5X74T.js";import"./chunk-3VUPVXAV.js";import"./chunk-OHOROFWN.js";import"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";export{f as createPageExperiments,o as mergeQueryStrings,r as pageAttributes,e as readPayload};
1
+ import{d as o,e as r,f as e,g as f}from"./chunk-S5H3WJVQ.js";import"./chunk-ZYTT7ZAB.js";import"./chunk-3VUPVXAV.js";import"./chunk-FVGUBIVT.js";import"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";export{f as createPageExperiments,o as mergeQueryStrings,r as pageAttributes,e as readPayload};
@@ -1 +1 @@
1
- import{b as at,c as Ne,e as ot,g as st,h as ct}from"./chunk-UWYL2QCF.js";import{c as Xe,d as Ze,e as et,f as pe,g as tt,h as nt,i as rt,k as it}from"./chunk-RBMOWJGE.js";import{a as Ge,c as Se,d as Ye,g as Je,j as Ke}from"./chunk-B3KFE57L.js";import{b as te}from"./chunk-ACFQLHJR.js";import"./chunk-CLAZ7NVN.js";import"./chunk-J4VTKRH7.js";import{c as ee,o as re,oa as ie,qa as Oe}from"./chunk-WRUW2UIJ.js";import{c as Te}from"./chunk-FJGJQGYF.js";import{a as k}from"./chunk-HJLGRW4A.js";import"./chunk-XIP32WI7.js";import"./chunk-OHOROFWN.js";import"./chunk-ZY4XAKNQ.js";import{a as W}from"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";async function lt(T,r,D){if(r.status!=="complete")throw new k("INVALID_RESPONSE","A verified completed purchase is required");let O=T?re.parse(T):null;if(await D.onComplete?.(r),!O||!D.check)return;let S=re.parse(await D.check());if(S.internal_feature_id!==O.internal_feature_id||S.quantity!==O.quantity||O.observation!==void 0&&(S.observation===void 0||S.observation.requirementDigest!==O.observation.requirementDigest||S.observation.authority!==O.observation.authority||Te(S.observation.subject)!==Te(O.observation.subject)))throw new k("INVALID_RESPONSE","The access requirement changed");S.allowed&&await D.onAccessGranted?.(S)}function De(T){return Object.entries(T.document.buttons).filter(([,r])=>r.type==="checkout"&&r.product.type==="fixed"&&!te(r.product,{},T.capabilities)).map(([r])=>r)}async function zt(T,r,D){let O=it(T.ownerDocument),S=()=>{C.finish("dismissed"),O()},B=()=>S(),C=tt(T,r,"paywall",()=>{S(),W(r.onDismiss)});r.signal?.throwIfAborted(),r.signal?.addEventListener("abort",B,{once:!0});let G=null,_,h,Le;try{if(C.start(!0),C.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(G=r.check?re.parse(await C.wait(r.check(),pe)):null,G?.allowed)return C.finish("skipped"),r.signal?.removeEventListener("abort",B),O(),await r.onAccessGranted?.(G),{check:G,host:null};let[e,t]=await Promise.allSettled([C.wait(import("./screen-renderer-W5MP4KVG.js")),C.wait(r.start().then(s=>(C.cancelled&&s.destroy(),s)),pe)]);if(e.status==="rejected")throw t.status==="fulfilled"&&t.value.destroy(),e.reason;if(t.status==="rejected")throw t.reason;Le=e.value,_=t.value,r.signal?.throwIfAborted(),_.signal?.throwIfAborted(),_.signal?.addEventListener("abort",B,{once:!0});let n=_.view??await C.wait(_.refresh(),pe);if(!n)throw new k("INVALID_RESPONSE","Paywall presentation is missing");_.signal?.throwIfAborted(),h=n}catch(e){throw C.finish("error",e),r.signal?.removeEventListener("abort",B),_?.signal?.removeEventListener("abort",B),_?.destroy(),O(),e}let i=_,{mountScreenPreview:ut}=Le,d=T.ownerDocument,fe=new AbortController,I=d.createElement("section"),Y=d.createElement("div"),U=d.createElement("div"),u=d.createElement("p"),y=d.createElement("button"),b=d.createElement("button"),w=d.createElement("dialog"),a=h.document.screen.strings.defaultLocale.startsWith("zh"),dt=a?"\u6B63\u5728\u5904\u7406\u2026":"Processing\u2026",pt=a?"\u6B63\u5728\u51C6\u5907\u62A5\u4EF7\u2026":"Preparing your price\u2026",P=at(h.document.screen.theme);I.dataset.indianaPaywall="",I.setAttribute("aria-label",h.document.name),I.style.cssText=P.root,U.style.cssText=P.controls,u.style.cssText=P.message,u.setAttribute("role","status"),b.style.cssText=P.link,b.textContent=a?"\u5173\u95ED":"Close",y.style.cssText=P.secondary,y.textContent=a?"\u91CD\u8BD5":"Retry",y.hidden=!0,U.append(u,y,b),I.append(Y,U);let Me=()=>{let e=H??U,t=[...e.children].every(s=>s===u?!u.textContent:s.hidden),n=[...e.children].some(s=>s===b?!1:s===u?!!u.textContent:!s.hidden);e.style.cssText=t?P.controls.replace(/padding:[^;]+/,"padding:0"):n?`${P.controls};${P.pinned}`:P.controls,we()},_e=typeof MutationObserver>"u"?void 0:new MutationObserver(Me);_e?.observe(I,{attributes:!0,attributeFilter:["hidden"],characterData:!0,childList:!0,subtree:!0});let J=h.document.presentation,F,Ue,me=!1,$e=JSON.stringify(h.capabilities),qe=e=>K?Object.entries(e.document.buttons).filter(([,t])=>t.type==="checkout").map(([t])=>t):De(e);function he(e){if(p)return;h=e;let t=JSON.stringify(e.capabilities);t!==$e&&(F?.updateCapabilities(e.capabilities,qe(e)),$e=t),mt(e)}let g,ye=0;function we(){let e=d.defaultView;if(!g?.responsive||!e)return;let t=H??U,n=e.innerHeight-(g.type==="modal"?32:0);t.style.maxHeight=`${Math.max(1,n)}px`,t.style.overflowY="auto",t.style.flexShrink="0",ye=Math.max(1,n-t.getBoundingClientRect().height),F?.resizeViewport?.(ye,e.innerWidth)}let p=!1,K=!1,E=null,ae=!1,Ve=!1,j=!1,be,ge=!1,V,H;function ft(){return K||p||V||ge?{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null}:Se(i)}let R=()=>!p&&!ae&&!V&&r.canInteract?.()!==!1,oe=!1,l=null,$=null;function mt(e){K||E||i.quote||i.operation||(u.textContent=Object.values(e.capabilities.plans).some(t=>t.available)?"":a?"\u5F53\u524D\u8D26\u53F7\u6682\u65E0\u53EF\u8D2D\u4E70\u7684\u65B9\u6848\u3002":"No plans are currently available for this account.")}let ve=new Map,Ce=!1;function ht(e,t,n,s){let o=e.lines.length===1?e.lines[0]:void 0,m=te(n,s,t.capabilities);if(!o||!m||o.productVersionId!==m)return!1;let x;try{x=Oe(t.document.screen,m,s,t.capabilities)}catch{return!1}let A=Object.fromEntries((o.prepaid??[]).map(z=>[z.internal_feature_id,z.quantity]));return[...new Set([...Object.keys(x),...Object.keys(A)])].every(z=>(x[z]??0)===(A[z]??0))}let se=e=>Ge({quote:i.quote,operation:e,requestId:null,pending:!1,destroyed:p,canReselect:i.canReselect});async function Pe(e){let t=e.merchantExecution;if(!(!R()||!e.checkoutUrl||r.checkoutNavigation==="after_confirmation"&&se(e).type!=="checkout"||t?.type==="purchase"&&!["not_started","pending"].includes(t.paymentStatus)||ve.get(e.operationId)===e.checkoutUrl)){ve.set(e.operationId,e.checkoutUrl);try{r.onCheckoutUrl?await r.onCheckoutUrl(e.checkoutUrl):d.defaultView?.location.assign(e.checkoutUrl)}catch(n){throw ve.delete(e.operationId),n}}}let Q=(e,t=!1)=>{if(t){let n=e instanceof k?e.code:void 0;n==="CAPABILITY_UNAVAILABLE"||n==="NOT_CONFIGURED"?(l=null,u.textContent=a?"\u6682\u65F6\u65E0\u6CD5\u4E3A\u6B64\u5957\u9910\u62A5\u4EF7\uFF0C\u4ED8\u6B3E\u5C1A\u672A\u5F00\u59CB\u3002":"Pricing for this plan is unavailable. Payment hasn\u2019t started."):i.canReselect===!0&&!E?u.textContent=a?"\u672A\u80FD\u53D6\u5F97\u62A5\u4EF7\uFF0C\u4ED8\u6B3E\u5C1A\u672A\u5F00\u59CB\u3002\u8BF7\u91CD\u65B0\u9009\u62E9\u5957\u9910\u3002":"We couldn\u2019t prepare your price. Payment hasn\u2019t started. Choose a plan again.":n==="COMMAND_PENDING"?u.textContent=a?"\u4ECD\u5728\u51C6\u5907\u62A5\u4EF7\uFF0C\u8BF7\u91CD\u8BD5\u4EE5\u67E5\u770B\u7ED3\u679C\u3002":"Your price is still being prepared. Retry to check the result.":u.textContent=a?"\u672A\u80FD\u53D6\u5F97\u62A5\u4EF7\uFF0C\u4ED8\u6B3E\u5C1A\u672A\u5F00\u59CB\u3002\u8BF7\u91CD\u8BD5\u3002":"We couldn\u2019t prepare your price. Payment hasn\u2019t started. Try again."}else u.textContent=e instanceof k&&(e.code==="NETWORK_ERROR"||e.code==="TIMEOUT")?ot(e,a):e instanceof k?e.message:a?"\u64CD\u4F5C\u672A\u5B8C\u6210\uFF0C\u8BF7\u91CD\u8BD5\u3002":"This action couldn\u2019t be completed. Try again.";y.hidden=l===null,t&&!g?.responsive&&u.scrollIntoView?.({block:"nearest"}),W(t&&D?.quoteError?D.quoteError:r.onError,e)},ce=new WeakMap;function le(e){K=e,F?.updateCapabilities?.(h.capabilities,qe(h));for(let t of $?.querySelectorAll("button")??[])e?(ce.set(t,t.disabled),t.disabled=!0):ce.has(t)&&(t.disabled=ce.get(t),ce.delete(t)),Ne(t)}function Ee(){u.textContent=a?"\u6682\u65F6\u65E0\u6CD5\u64CD\u4F5C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"This action is unavailable right now. Try again in a moment."}async function yt(e){if(r.beforeAction)try{await r.beforeAction()}catch(t){throw l=e,t}}async function q(e){if(K||p)return;if(!R()){Ee();return}let t=e===ue,n=t?pt:dt;le(!0),y.hidden=!0,u.textContent=n;try{if(await yt(e),p)return;if(!R()){l=e,y.hidden=!1,Ee();return}await e()}catch(s){p||Q(s,t)}finally{le(!1),u.textContent===n&&(u.textContent="")}}async function wt(e){await lt(G,e,r)}function He(e){return Se(i).type==="recording"||se(e).type==="recording"}function Be(e){let t=e.merchantTerms,n=t?.subscriptionTerms?.items??[],s=t?t.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),o=t?n.length===1&&n[0]?.amountMinor===s&&n[0]:e.lines.length===1&&e.lines[0]?.catalogAmountMinor===s&&e.lines[0],m=s===null?ee(t.subtotalMinor-t.discountMinor,e.currency)+(a?" + \u5F85\u786E\u8BA4\u7A0E\u8D39":" + tax confirmed at checkout"):ee(s,e.currency)+(o?ie(o.interval,a?"zh-CN":"en",o.intervalCount??1):""),x=e.lines.map(A=>A.productName).join(", ");return{label:x?`${x} \xB7 ${m}`:m,recurring:o}}async function N(e,t=r.checkoutNavigation!=="after_confirmation"){if(p)return;if(!R()){l=async()=>N(await i.read()),y.hidden=!1;return}if(u.textContent=ct(e.status,a),He(e)){let o=e.merchantExecution?.type==="purchase"&&e.merchantExecution.recordingStatus==="failed";u.textContent=o?a?"\u4ED8\u6B3E\u548C\u5546\u6237\u5904\u7406\u5DF2\u5B8C\u6210\uFF0C\u4F46\u4EA4\u6613\u8BB0\u5F55\u5931\u8D25\u3002\u8BF7\u8054\u7CFB\u5546\u6237\u4FEE\u590D\uFF0C\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":a?"\u4ED8\u6B3E\u548C\u5546\u6237\u5904\u7406\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u786E\u8BA4\u4EA4\u6613\u8BB0\u5F55\u3002\u8BF7\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",y.textContent=a?"\u67E5\u8BE2\u8BB0\u5F55":"Check recording",l=async()=>N(await i.read()),y.hidden=!1;return}if(e.problem){let o=e.problem;l=ne,y.textContent=a?"\u68C0\u67E5\u5E76\u6062\u590D\u539F\u64CD\u4F5C":"Check and recover original purchase",Q(new k(o.code,o.reason==="RESULT_UNKNOWN"?a?"\u4ED8\u6B3E\u7ED3\u679C\u5C1A\u672A\u786E\u5B9A\uFF0C\u8BF7\u6062\u590D\u539F\u64CD\u4F5C\uFF0C\u6682\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"The payment result is unknown. Recover the original purchase before buying again.":o.phase==="fulfillment"?a?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u5546\u6237\u6743\u76CA\u5904\u7406\u9700\u8981\u6838\u5BF9\u3002":"Payment was recorded. Access fulfillment needs attention.":o.code==="CAPABILITY_UNAVAILABLE"?a?"\u5546\u6237\u5C1A\u4E0D\u652F\u6301\u672C\u6B21\u8D2D\u4E70\u6240\u9700\u7684\u5B8C\u6574\u80FD\u529B\uFF0C\u8BF7\u5904\u7406\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":o.code==="NOT_CONFIGURED"?a?"\u4ED8\u6B3E\u670D\u52A1\u8FDE\u63A5\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u8054\u7CFB\u5546\u6237\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":a?"\u539F\u8D2D\u4E70\u64CD\u4F5C\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u67E5\u8BE2\u6216\u6062\u590D\u6B64\u64CD\u4F5C\u3002":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,o));return}if(e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(u.textContent=a?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u6B63\u5728\u7B49\u5F85\u5546\u6237\u5B8C\u6210\u5904\u7406\u3002":"Payment was recorded. Waiting for merchant fulfillment."),e.status==="complete"){l=null,await wt(e);return}if(e.status!=="pending"){if(i.canReselect===!1){u.textContent=a?"\u6B63\u5728\u6838\u5BF9\u539F\u8D2D\u4E70\u7ED3\u679C":"Checking the original purchase result",y.textContent=a?"\u67E5\u8BE2\u7ED3\u679C":"Check result",l=async()=>N(await i.read()),y.hidden=!1;return}e.status==="cancelled"?u.textContent=a?"\u8FD9\u7B14\u8D2D\u4E70\u5DF2\u53D6\u6D88\uFF0C\u53EF\u4EE5\u91CD\u65B0\u9009\u62E9\u65B9\u6848\u3002":"This purchase was cancelled. Choose a plan to start again.":e.status==="failed"&&(u.textContent=a?"\u8FD9\u7B14\u8D2D\u4E70\u672A\u80FD\u5B8C\u6210\uFF0C\u53EF\u4EE5\u91CD\u65B0\u9009\u62E9\u65B9\u6848\u3002":"This purchase didn\u2019t go through. Choose a plan to try again."),y.textContent=a?"\u91CD\u8BD5":"Retry",l=null,E=null;return}if(!t&&se(e).type==="checkout"){let o=i.quote,m=o?.operationId===e.operationId?Be(o).label:"";u.textContent=Ce?m?a?`${m} \u5C1A\u672A\u4ED8\u6B3E\u3002\u518D\u6B21\u9009\u62E9\u8BE5\u65B9\u6848\u5373\u53EF\u7EE7\u7EED\u4ED8\u6B3E\u3002`:`${m} is still unpaid. Choose it again to continue paying.`:a?"\u4E4B\u524D\u7684\u8D2D\u4E70\u5C1A\u672A\u4ED8\u6B3E\u3002\u518D\u6B21\u9009\u62E9\u8BE5\u65B9\u6848\u5373\u53EF\u7EE7\u7EED\u4ED8\u6B3E\u3002":"Your earlier purchase is still unpaid. Choose that plan again to continue paying.":"",Ce=!1,l=null;return}await Pe(e);let n=Date.now()+6e5,s=2e3;me=!0,W(r.onObservationChange,!0);try{for(;!p&&Date.now()<n;){if(await st(s,d,fe.signal),p)return;if(!R()){l=async()=>N(await i.read()),y.hidden=!1;return}let o=await i.read();if(!t&&se(o).type==="checkout"){await N(o,!1);return}if(!o.problem&&o.status==="pending"&&await Pe(o),o.status!=="pending"||o.problem||He(o)){await N(o);return}s=Math.min(s*1.5,3e4)}}finally{me=!1,W(r.onObservationChange,!1)}l=async()=>N(await i.read()),y.hidden=!1}async function xe(e=!1){let t=await i.read();if(p)return;if(!R()){l=()=>xe(e),y.hidden=!1;return}let n=i.quote;if(n&&Je(t,{operationId:n.operationId,currency:n.currency},"The original purchase operation changed"),n&&t.status==="pending"&&t.quoteFinalized===!1&&!t.confirmedAt&&!t.checkoutUrl&&!t.nativePurchase&&!t.merchantExecution&&!t.problem&&!i.pendingCancellation){Fe(n);return}await N(t,e||void 0)}async function ne(){$?.remove(),$=null,l=ne;let e=await i.confirm();if(!R()){l=ne,y.hidden=!1;return}if(e.problem){await N(e);return}if(e.status==="pending"){if(e.checkoutUrl)await Pe(e);else if(e.execution&&e.execution.provider!=="merchant"||e.nativePurchase){if(!r.onPurchase)throw new k("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await r.onPurchase({operation:e,signal:fe.signal})}}l=async()=>N(await i.read()),await N(e,!0)}function Fe(e){$?.remove();let t=!(Date.parse(e.expiresAt)>Date.now());u.textContent=t?a?"\u6B64\u62A5\u4EF7\u5DF2\u8FC7\u671F\u3002\u8BF7\u5148\u53D6\u6D88\uFF0C\u518D\u91CD\u65B0\u9009\u62E9\u3002":"This quote has expired. Cancel it, then choose again.":"";let n=d.createElement("div"),s=d.createElement("button"),o=d.createElement("button"),m=d.createElement("div"),x=d.createElement("p"),A=e.merchantTerms,de=a?"zh-CN":"en",z=A?.subscriptionTerms?.items??[],Re=A?A.subscriptionTerms?.trial?.days:e.lines.find(c=>c.trial)?.trial?.days,Z=Re===void 0?null:A?A.totalMinor:e.charge?e.charge.totalMinor:e.lines.every(c=>c.trial)?0:null,je=(c,f)=>a?`${f} \u5929\u8BD5\u7528\u7ED3\u675F\u540E ${c}`:`Then ${c} after the ${f}-day trial`,{label:bt,recurring:Qe}=Be(e),gt=e.lines.map(c=>c.productName).join(", "),ze=Z===null?"":`${a?"\u4ECA\u5929\u5E94\u4ED8":"Due today"} ${ee(Z,e.currency)}`;x.textContent=ze?[gt,ze].filter(Boolean).join(" \xB7 "):bt,s.textContent=a?"\u786E\u8BA4\u8D2D\u4E70":"Confirm purchase",s.disabled=t,o.textContent=a?"\u53D6\u6D88":"Cancel",n.style.cssText=P.panel,x.style.cssText=P.summary,m.style.cssText=P.actions,s.style.cssText=P.primary,o.style.cssText=P.secondary,Ne(s),s.onclick=()=>{q(ne)};let We=async()=>{let c=await i.cancel();p||(n.remove(),$=null,await N(c))};o.onclick=()=>{l=We,q(We)};let L=d.createElement("div");if(L.style.cssText=P.terms,A){for(let f of z){if(Z===null&&f===Qe)continue;let v=d.createElement("p"),M=ee(f.amountMinor,e.currency)+ie(f.interval,de,f.intervalCount);v.textContent=Z!==null&&Re!==void 0?je(M,Re):M,L.append(v)}let c=A.subscriptionTerms?.trial;if(c){let f=d.createElement("p");f.textContent=a?`\u8BD5\u7528 ${c.days} \u5929\uFF1B${c.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${c.days}; ${c.cardRequired?"a payment method is required":"no payment method is required"}`,L.append(f)}for(let f of[...A.expectedEffects.map(v=>v.description),...A.requiredConsents.map(v=>v.summary)]){let v=d.createElement("p");v.textContent=f,L.append(v)}}else{for(let c of e.lines){if(Z!==null||c!==Qe){let f=d.createElement("p"),v=`${ee(c.catalogAmountMinor,e.currency)}${ie(c.interval,de,c.intervalCount??1)}`;f.textContent=Z!==null&&c.trial?(e.lines.length>1?`${c.productName} \xB7 `:"")+je(v,c.trial.days):`${c.productName} \xB7 ${v}`,L.append(f)}for(let f of c.prepaid??[]){let v=d.createElement("p"),M=i.view?.capabilities.plans[c.productVersionId]?.prepaid?.find(vt=>vt.internalFeatureId===f.internal_feature_id);v.textContent=`${M?.name??f.internal_feature_id} \xB7 ${f.quantity} ${a?"\u4EFD":"packs"} \xD7 ${f.terms.units}`,M&&(v.textContent+=ie(M.reset==="week"||M.reset==="month"||M.reset==="year"?M.reset:"one_time",de,M.resetCount)),L.append(v)}if(c.trial){let f=d.createElement("p");f.textContent=a?`\u8BD5\u7528 ${c.trial.days} \u5929\uFF1B${c.trial.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${c.trial.days}; ${c.trial.cardRequired?"a payment method is required":"no payment method is required"}`,L.append(f)}}if(!e.charge){let c=d.createElement("p");c.textContent=a?"\u76EE\u5F55\u4EF7\u683C\uFF1B\u6700\u7EC8\u91D1\u989D\u4EE5\u7ED3\u8D26\u65F6\u7A0E\u8D39\u548C\u8BD5\u7528\u89C4\u5219\u4E3A\u51C6\u3002":"Catalog price; the final charge depends on checkout taxes and trial terms.",L.append(c)}}for(let c of L.children)c.style.margin="0";m.append(s,o),n.append(x,...L.childElementCount?[L]:[],m),U.prepend(n),g?.responsive||n.scrollIntoView?.({block:"nearest"}),s.focus({preventScroll:!0}),$=n,l=null}async function ue(){if(!E)return;if(l=ue,!oe){let n=i.view,s=n?.document.buttons[E.actionId],o=n&&s?.type==="checkout"?te(s.product,E.selection,n.capabilities):null;if(!o)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");let m=await r.resolveOfferId?.({actionId:E.actionId,productVersionId:o});if(p)return;m!==void 0&&(E.offerId=m),oe=!0}if(!R()){y.hidden=!1;return}let e;try{e=await i.preview(E)}catch(n){throw i.canReselect===!0&&(E=null,oe=!1,l=null),n}if(p)return;let t=e.merchantTerms;if(r.confirmOnHostedCheckout&&R()&&e.provider==="merchant"&&e.billingSubscriptionId===null&&t?.request.action==="purchase"&&t.request.mode==="subscription"&&t.subscriptionTerms?.trial===null&&t.requiredConsents.length===0&&Date.parse(e.expiresAt)>Date.now()){let n=a?"\u6B63\u5728\u6253\u5F00\u6536\u94F6\u53F0\u2026":"Opening checkout\u2026";u.textContent=n;try{await ne()}catch(s){p||Q(s)}finally{u.textContent===n&&(u.textContent="")}return}Fe(e)}function X(e="destroy"){p||(p=!0,r.signal?.removeEventListener("abort",B),i.signal?.removeEventListener("abort",B),C.finish("dismissed"),Ue?.(),fe.abort(),_e?.disconnect(),g?.destroy(),F?.destroy(),i.destroy(),w.open&&w.close(),w.remove(),I.remove(),O(),e==="dismiss"&&W(r.onDismiss))}S=X;async function ke(){if(!j||p||ae||V==="closing"||!V&&!R())return;if(!D){X("dismiss");return}let e=d.createElement("p");e.setAttribute("role","status"),e.textContent=a?"\u6B63\u5728\u5173\u95ED\u2026":"Closing\u2026",H||(H=d.createElement("div"),H.style.cssText=U.style.cssText,U.replaceWith(H),Y.inert=!0),b.hidden=!1,H.replaceChildren(e,b),V="closing",b.setAttribute("aria-disabled","true"),b.focus({preventScroll:!0});try{await D.dismiss()}catch(t){p||W(r.onError,t)}p||(V="retry",e.textContent=a?"\u672A\u80FD\u786E\u8BA4\u5173\u95ED\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not confirm closure. Try again.",b.textContent=a?"\u91CD\u8BD5\u5173\u95ED":"Retry closing",b.removeAttribute("aria-label"),b.removeAttribute("aria-disabled"))}b.onclick=()=>{ke()},w.addEventListener("cancel",e=>{e.preventDefault(),ke()}),y.onclick=()=>{l&&q(l)};function Ie(e){C.finish("error",e),X()}function Ae(){if(!(!Ve||j||p||ae||g&&!R()))try{let e=t=>{be?.(),g&&(w.showModal(),g.responsive&&w.focus({preventScroll:!0}),!t&&r.loading!=="host"&&Ze(w,g.type,g.responsive)),j=!0};D?D.present(()=>C.present(()=>e(!0))):C.present(e)}catch(e){Ie(e),Q(e)}}try{if(J.type==="inline")b.hidden=Object.values(h.document.buttons).some(t=>t.type==="close"),Me(),be=rt(I,T),T.append(I);else{let t={sm:420,md:640,lg:900};w.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in J?t[J.size]+"px":"100vw"}`,w.setAttribute("aria-label",h.document.name),b.textContent="\xD7",b.setAttribute("aria-label",a?"\u5173\u95ED":"Close"),et(b,h.document.screen.theme),Ke(h.document)?(b.hidden=!0,w.append(I)):w.append(b,I),T.append(w),g=Xe(w,{...h.document.screen,presentation:J},we),g.latch(),g.responsive&&(I.style.display="flex",I.style.flexDirection="column",I.style.maxHeight="100%",Y.style.overflow="clip",Y.style.minHeight="0"),be=nt(w)}F=ut(Y,{mode:"live",rendererUrl:i.webViewUrl,title:h.document.name,hostPresentation:()=>g?.type??J.type,reportContentHeight:g?.responsive,onResize:t=>{if(!g?.responsive)return;let n=Math.min(t,ye);Y.style.height=`${n}px`,g.setContentHeight(n+(H??U).getBoundingClientRect().height)},onAction(t,n={}){if(!j||p||V)return;if(!R()){Ee();return}let s=i.view,o=s?.document.buttons[t];if(!o)return;if(o.type==="close"){q(async()=>{await r.onAction?.(t),X(r.onAction?"action":"dismiss")});return}if(o.type==="action"){l=async()=>{if(o.action.type==="event"){if(!r.onEvent)throw new k("EVENT_HANDLER_REQUIRED","Provide the event handler");await r.onEvent(o.action.event)}else r.onOpenUrl?await r.onOpenUrl(o.action.url):d.defaultView?.location.assign(o.action.url);await r.onAction?.(t),l=null},q(l);return}if($&&i.canReselect===!1){u.textContent=a?"\u8BF7\u5148\u786E\u8BA4\u6216\u53D6\u6D88\u5F53\u524D\u8D2D\u4E70\u3002":"Confirm or cancel the current purchase first.",g?.responsive||$.scrollIntoView?.({block:"nearest"}),$.querySelector("button")?.focus({preventScroll:!0});return}if((i.quote||E)&&i.canReselect===!1){let x=!!s&&!!i.quote&&ht(i.quote,s,o.product,n);Ce=!!i.quote&&!x,l=i.quote?()=>xe(x):ue,q(l);return}let m=s&&te(o.product,n,s.capabilities);if(!s||!m){Q(new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(r.onPurchaseIntent){l=null,q(async()=>{let x={actionId:t,productVersionId:m,selection:structuredClone(n),featureQuantities:Oe(s.document.screen,m,n,s.capabilities)};ge=!0,await r.onPurchaseIntent(x)});return}if(E&&E.actionId!==t){Q(new k("COMMAND_PENDING","Finish the current purchase"));return}E||(E={requestId:crypto.randomUUID(),actionId:t,selection:n},oe=!1),q(ue)},onEscape:()=>{ke()},onError:t=>{let n=new Error(t);!j&&!p&&Ie(n),Q(n)},onRendered:t=>{t&&w.setAttribute("aria-label",t),Ve=!0,Ae()}}),we(),F.update(h.document.screen,h.document.screen.strings.defaultLocale,{capabilities:h.capabilities,unavailableActions:De(h),serverInput:{bindings:[],answers:{}}}),Ue=i.subscribe?.(he),he(i.view??h),await C.wait(F.ready);let e=i.operation;(i.quote||e&&(e.confirmedAt||e.checkoutUrl||e.status==="complete"))&&(l=()=>xe(),q(l))}catch(e){throw Ie(e),e}return{check:G,host:{get observing(){return me},get recovery(){return ft()},async prepareFallback(){if(K||p||V||ge)return{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null};le(!0);try{let e=await Ye(i);return e.type==="native"&&X(),e}finally{le(!1)}},setSuspended(e){ae=e,I.hidden=e,e&&w.open?w.close():!e&&!j?Ae():!e&&!p&&j&&J.type!=="inline"&&!w.open&&w.showModal()},destroy:X,refresh:async()=>{if(!R()){if(i.view)return i.view;throw new k("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await i.refresh();return he(e),Ae(),e}}}}export{zt as showPaywall};
1
+ import{b as at,c as Ne,e as ot,g as st,h as ct}from"./chunk-UWYL2QCF.js";import{c as Xe,d as Ze,e as et,f as pe,g as tt,h as nt,i as rt,k as it}from"./chunk-RBMOWJGE.js";import{a as Ge,c as Se,d as Ye,g as Je,j as Ke}from"./chunk-B3KFE57L.js";import{b as te}from"./chunk-ACFQLHJR.js";import"./chunk-XZEGVBAI.js";import"./chunk-J4VTKRH7.js";import{c as ee,o as re,oa as ie,qa as Oe}from"./chunk-WRUW2UIJ.js";import{c as Te}from"./chunk-FJGJQGYF.js";import{a as k}from"./chunk-HJLGRW4A.js";import"./chunk-XIP32WI7.js";import"./chunk-FVGUBIVT.js";import"./chunk-ZY4XAKNQ.js";import{a as W}from"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";async function lt(T,r,D){if(r.status!=="complete")throw new k("INVALID_RESPONSE","A verified completed purchase is required");let O=T?re.parse(T):null;if(await D.onComplete?.(r),!O||!D.check)return;let S=re.parse(await D.check());if(S.internal_feature_id!==O.internal_feature_id||S.quantity!==O.quantity||O.observation!==void 0&&(S.observation===void 0||S.observation.requirementDigest!==O.observation.requirementDigest||S.observation.authority!==O.observation.authority||Te(S.observation.subject)!==Te(O.observation.subject)))throw new k("INVALID_RESPONSE","The access requirement changed");S.allowed&&await D.onAccessGranted?.(S)}function De(T){return Object.entries(T.document.buttons).filter(([,r])=>r.type==="checkout"&&r.product.type==="fixed"&&!te(r.product,{},T.capabilities)).map(([r])=>r)}async function zt(T,r,D){let O=it(T.ownerDocument),S=()=>{C.finish("dismissed"),O()},B=()=>S(),C=tt(T,r,"paywall",()=>{S(),W(r.onDismiss)});r.signal?.throwIfAborted(),r.signal?.addEventListener("abort",B,{once:!0});let G=null,_,h,Le;try{if(C.start(!0),C.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(G=r.check?re.parse(await C.wait(r.check(),pe)):null,G?.allowed)return C.finish("skipped"),r.signal?.removeEventListener("abort",B),O(),await r.onAccessGranted?.(G),{check:G,host:null};let[e,t]=await Promise.allSettled([C.wait(import("./screen-renderer-W5MP4KVG.js")),C.wait(r.start().then(s=>(C.cancelled&&s.destroy(),s)),pe)]);if(e.status==="rejected")throw t.status==="fulfilled"&&t.value.destroy(),e.reason;if(t.status==="rejected")throw t.reason;Le=e.value,_=t.value,r.signal?.throwIfAborted(),_.signal?.throwIfAborted(),_.signal?.addEventListener("abort",B,{once:!0});let n=_.view??await C.wait(_.refresh(),pe);if(!n)throw new k("INVALID_RESPONSE","Paywall presentation is missing");_.signal?.throwIfAborted(),h=n}catch(e){throw C.finish("error",e),r.signal?.removeEventListener("abort",B),_?.signal?.removeEventListener("abort",B),_?.destroy(),O(),e}let i=_,{mountScreenPreview:ut}=Le,d=T.ownerDocument,fe=new AbortController,I=d.createElement("section"),Y=d.createElement("div"),U=d.createElement("div"),u=d.createElement("p"),y=d.createElement("button"),b=d.createElement("button"),w=d.createElement("dialog"),a=h.document.screen.strings.defaultLocale.startsWith("zh"),dt=a?"\u6B63\u5728\u5904\u7406\u2026":"Processing\u2026",pt=a?"\u6B63\u5728\u51C6\u5907\u62A5\u4EF7\u2026":"Preparing your price\u2026",P=at(h.document.screen.theme);I.dataset.indianaPaywall="",I.setAttribute("aria-label",h.document.name),I.style.cssText=P.root,U.style.cssText=P.controls,u.style.cssText=P.message,u.setAttribute("role","status"),b.style.cssText=P.link,b.textContent=a?"\u5173\u95ED":"Close",y.style.cssText=P.secondary,y.textContent=a?"\u91CD\u8BD5":"Retry",y.hidden=!0,U.append(u,y,b),I.append(Y,U);let Me=()=>{let e=H??U,t=[...e.children].every(s=>s===u?!u.textContent:s.hidden),n=[...e.children].some(s=>s===b?!1:s===u?!!u.textContent:!s.hidden);e.style.cssText=t?P.controls.replace(/padding:[^;]+/,"padding:0"):n?`${P.controls};${P.pinned}`:P.controls,we()},_e=typeof MutationObserver>"u"?void 0:new MutationObserver(Me);_e?.observe(I,{attributes:!0,attributeFilter:["hidden"],characterData:!0,childList:!0,subtree:!0});let J=h.document.presentation,F,Ue,me=!1,$e=JSON.stringify(h.capabilities),qe=e=>K?Object.entries(e.document.buttons).filter(([,t])=>t.type==="checkout").map(([t])=>t):De(e);function he(e){if(p)return;h=e;let t=JSON.stringify(e.capabilities);t!==$e&&(F?.updateCapabilities(e.capabilities,qe(e)),$e=t),mt(e)}let g,ye=0;function we(){let e=d.defaultView;if(!g?.responsive||!e)return;let t=H??U,n=e.innerHeight-(g.type==="modal"?32:0);t.style.maxHeight=`${Math.max(1,n)}px`,t.style.overflowY="auto",t.style.flexShrink="0",ye=Math.max(1,n-t.getBoundingClientRect().height),F?.resizeViewport?.(ye,e.innerWidth)}let p=!1,K=!1,E=null,ae=!1,Ve=!1,j=!1,be,ge=!1,V,H;function ft(){return K||p||V||ge?{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null}:Se(i)}let R=()=>!p&&!ae&&!V&&r.canInteract?.()!==!1,oe=!1,l=null,$=null;function mt(e){K||E||i.quote||i.operation||(u.textContent=Object.values(e.capabilities.plans).some(t=>t.available)?"":a?"\u5F53\u524D\u8D26\u53F7\u6682\u65E0\u53EF\u8D2D\u4E70\u7684\u65B9\u6848\u3002":"No plans are currently available for this account.")}let ve=new Map,Ce=!1;function ht(e,t,n,s){let o=e.lines.length===1?e.lines[0]:void 0,m=te(n,s,t.capabilities);if(!o||!m||o.productVersionId!==m)return!1;let x;try{x=Oe(t.document.screen,m,s,t.capabilities)}catch{return!1}let A=Object.fromEntries((o.prepaid??[]).map(z=>[z.internal_feature_id,z.quantity]));return[...new Set([...Object.keys(x),...Object.keys(A)])].every(z=>(x[z]??0)===(A[z]??0))}let se=e=>Ge({quote:i.quote,operation:e,requestId:null,pending:!1,destroyed:p,canReselect:i.canReselect});async function Pe(e){let t=e.merchantExecution;if(!(!R()||!e.checkoutUrl||r.checkoutNavigation==="after_confirmation"&&se(e).type!=="checkout"||t?.type==="purchase"&&!["not_started","pending"].includes(t.paymentStatus)||ve.get(e.operationId)===e.checkoutUrl)){ve.set(e.operationId,e.checkoutUrl);try{r.onCheckoutUrl?await r.onCheckoutUrl(e.checkoutUrl):d.defaultView?.location.assign(e.checkoutUrl)}catch(n){throw ve.delete(e.operationId),n}}}let Q=(e,t=!1)=>{if(t){let n=e instanceof k?e.code:void 0;n==="CAPABILITY_UNAVAILABLE"||n==="NOT_CONFIGURED"?(l=null,u.textContent=a?"\u6682\u65F6\u65E0\u6CD5\u4E3A\u6B64\u5957\u9910\u62A5\u4EF7\uFF0C\u4ED8\u6B3E\u5C1A\u672A\u5F00\u59CB\u3002":"Pricing for this plan is unavailable. Payment hasn\u2019t started."):i.canReselect===!0&&!E?u.textContent=a?"\u672A\u80FD\u53D6\u5F97\u62A5\u4EF7\uFF0C\u4ED8\u6B3E\u5C1A\u672A\u5F00\u59CB\u3002\u8BF7\u91CD\u65B0\u9009\u62E9\u5957\u9910\u3002":"We couldn\u2019t prepare your price. Payment hasn\u2019t started. Choose a plan again.":n==="COMMAND_PENDING"?u.textContent=a?"\u4ECD\u5728\u51C6\u5907\u62A5\u4EF7\uFF0C\u8BF7\u91CD\u8BD5\u4EE5\u67E5\u770B\u7ED3\u679C\u3002":"Your price is still being prepared. Retry to check the result.":u.textContent=a?"\u672A\u80FD\u53D6\u5F97\u62A5\u4EF7\uFF0C\u4ED8\u6B3E\u5C1A\u672A\u5F00\u59CB\u3002\u8BF7\u91CD\u8BD5\u3002":"We couldn\u2019t prepare your price. Payment hasn\u2019t started. Try again."}else u.textContent=e instanceof k&&(e.code==="NETWORK_ERROR"||e.code==="TIMEOUT")?ot(e,a):e instanceof k?e.message:a?"\u64CD\u4F5C\u672A\u5B8C\u6210\uFF0C\u8BF7\u91CD\u8BD5\u3002":"This action couldn\u2019t be completed. Try again.";y.hidden=l===null,t&&!g?.responsive&&u.scrollIntoView?.({block:"nearest"}),W(t&&D?.quoteError?D.quoteError:r.onError,e)},ce=new WeakMap;function le(e){K=e,F?.updateCapabilities?.(h.capabilities,qe(h));for(let t of $?.querySelectorAll("button")??[])e?(ce.set(t,t.disabled),t.disabled=!0):ce.has(t)&&(t.disabled=ce.get(t),ce.delete(t)),Ne(t)}function Ee(){u.textContent=a?"\u6682\u65F6\u65E0\u6CD5\u64CD\u4F5C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"This action is unavailable right now. Try again in a moment."}async function yt(e){if(r.beforeAction)try{await r.beforeAction()}catch(t){throw l=e,t}}async function q(e){if(K||p)return;if(!R()){Ee();return}let t=e===ue,n=t?pt:dt;le(!0),y.hidden=!0,u.textContent=n;try{if(await yt(e),p)return;if(!R()){l=e,y.hidden=!1,Ee();return}await e()}catch(s){p||Q(s,t)}finally{le(!1),u.textContent===n&&(u.textContent="")}}async function wt(e){await lt(G,e,r)}function He(e){return Se(i).type==="recording"||se(e).type==="recording"}function Be(e){let t=e.merchantTerms,n=t?.subscriptionTerms?.items??[],s=t?t.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),o=t?n.length===1&&n[0]?.amountMinor===s&&n[0]:e.lines.length===1&&e.lines[0]?.catalogAmountMinor===s&&e.lines[0],m=s===null?ee(t.subtotalMinor-t.discountMinor,e.currency)+(a?" + \u5F85\u786E\u8BA4\u7A0E\u8D39":" + tax confirmed at checkout"):ee(s,e.currency)+(o?ie(o.interval,a?"zh-CN":"en",o.intervalCount??1):""),x=e.lines.map(A=>A.productName).join(", ");return{label:x?`${x} \xB7 ${m}`:m,recurring:o}}async function N(e,t=r.checkoutNavigation!=="after_confirmation"){if(p)return;if(!R()){l=async()=>N(await i.read()),y.hidden=!1;return}if(u.textContent=ct(e.status,a),He(e)){let o=e.merchantExecution?.type==="purchase"&&e.merchantExecution.recordingStatus==="failed";u.textContent=o?a?"\u4ED8\u6B3E\u548C\u5546\u6237\u5904\u7406\u5DF2\u5B8C\u6210\uFF0C\u4F46\u4EA4\u6613\u8BB0\u5F55\u5931\u8D25\u3002\u8BF7\u8054\u7CFB\u5546\u6237\u4FEE\u590D\uFF0C\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":a?"\u4ED8\u6B3E\u548C\u5546\u6237\u5904\u7406\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u786E\u8BA4\u4EA4\u6613\u8BB0\u5F55\u3002\u8BF7\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",y.textContent=a?"\u67E5\u8BE2\u8BB0\u5F55":"Check recording",l=async()=>N(await i.read()),y.hidden=!1;return}if(e.problem){let o=e.problem;l=ne,y.textContent=a?"\u68C0\u67E5\u5E76\u6062\u590D\u539F\u64CD\u4F5C":"Check and recover original purchase",Q(new k(o.code,o.reason==="RESULT_UNKNOWN"?a?"\u4ED8\u6B3E\u7ED3\u679C\u5C1A\u672A\u786E\u5B9A\uFF0C\u8BF7\u6062\u590D\u539F\u64CD\u4F5C\uFF0C\u6682\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"The payment result is unknown. Recover the original purchase before buying again.":o.phase==="fulfillment"?a?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u5546\u6237\u6743\u76CA\u5904\u7406\u9700\u8981\u6838\u5BF9\u3002":"Payment was recorded. Access fulfillment needs attention.":o.code==="CAPABILITY_UNAVAILABLE"?a?"\u5546\u6237\u5C1A\u4E0D\u652F\u6301\u672C\u6B21\u8D2D\u4E70\u6240\u9700\u7684\u5B8C\u6574\u80FD\u529B\uFF0C\u8BF7\u5904\u7406\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":o.code==="NOT_CONFIGURED"?a?"\u4ED8\u6B3E\u670D\u52A1\u8FDE\u63A5\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u8054\u7CFB\u5546\u6237\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":a?"\u539F\u8D2D\u4E70\u64CD\u4F5C\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u67E5\u8BE2\u6216\u6062\u590D\u6B64\u64CD\u4F5C\u3002":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,o));return}if(e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(u.textContent=a?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u6B63\u5728\u7B49\u5F85\u5546\u6237\u5B8C\u6210\u5904\u7406\u3002":"Payment was recorded. Waiting for merchant fulfillment."),e.status==="complete"){l=null,await wt(e);return}if(e.status!=="pending"){if(i.canReselect===!1){u.textContent=a?"\u6B63\u5728\u6838\u5BF9\u539F\u8D2D\u4E70\u7ED3\u679C":"Checking the original purchase result",y.textContent=a?"\u67E5\u8BE2\u7ED3\u679C":"Check result",l=async()=>N(await i.read()),y.hidden=!1;return}e.status==="cancelled"?u.textContent=a?"\u8FD9\u7B14\u8D2D\u4E70\u5DF2\u53D6\u6D88\uFF0C\u53EF\u4EE5\u91CD\u65B0\u9009\u62E9\u65B9\u6848\u3002":"This purchase was cancelled. Choose a plan to start again.":e.status==="failed"&&(u.textContent=a?"\u8FD9\u7B14\u8D2D\u4E70\u672A\u80FD\u5B8C\u6210\uFF0C\u53EF\u4EE5\u91CD\u65B0\u9009\u62E9\u65B9\u6848\u3002":"This purchase didn\u2019t go through. Choose a plan to try again."),y.textContent=a?"\u91CD\u8BD5":"Retry",l=null,E=null;return}if(!t&&se(e).type==="checkout"){let o=i.quote,m=o?.operationId===e.operationId?Be(o).label:"";u.textContent=Ce?m?a?`${m} \u5C1A\u672A\u4ED8\u6B3E\u3002\u518D\u6B21\u9009\u62E9\u8BE5\u65B9\u6848\u5373\u53EF\u7EE7\u7EED\u4ED8\u6B3E\u3002`:`${m} is still unpaid. Choose it again to continue paying.`:a?"\u4E4B\u524D\u7684\u8D2D\u4E70\u5C1A\u672A\u4ED8\u6B3E\u3002\u518D\u6B21\u9009\u62E9\u8BE5\u65B9\u6848\u5373\u53EF\u7EE7\u7EED\u4ED8\u6B3E\u3002":"Your earlier purchase is still unpaid. Choose that plan again to continue paying.":"",Ce=!1,l=null;return}await Pe(e);let n=Date.now()+6e5,s=2e3;me=!0,W(r.onObservationChange,!0);try{for(;!p&&Date.now()<n;){if(await st(s,d,fe.signal),p)return;if(!R()){l=async()=>N(await i.read()),y.hidden=!1;return}let o=await i.read();if(!t&&se(o).type==="checkout"){await N(o,!1);return}if(!o.problem&&o.status==="pending"&&await Pe(o),o.status!=="pending"||o.problem||He(o)){await N(o);return}s=Math.min(s*1.5,3e4)}}finally{me=!1,W(r.onObservationChange,!1)}l=async()=>N(await i.read()),y.hidden=!1}async function xe(e=!1){let t=await i.read();if(p)return;if(!R()){l=()=>xe(e),y.hidden=!1;return}let n=i.quote;if(n&&Je(t,{operationId:n.operationId,currency:n.currency},"The original purchase operation changed"),n&&t.status==="pending"&&t.quoteFinalized===!1&&!t.confirmedAt&&!t.checkoutUrl&&!t.nativePurchase&&!t.merchantExecution&&!t.problem&&!i.pendingCancellation){Fe(n);return}await N(t,e||void 0)}async function ne(){$?.remove(),$=null,l=ne;let e=await i.confirm();if(!R()){l=ne,y.hidden=!1;return}if(e.problem){await N(e);return}if(e.status==="pending"){if(e.checkoutUrl)await Pe(e);else if(e.execution&&e.execution.provider!=="merchant"||e.nativePurchase){if(!r.onPurchase)throw new k("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await r.onPurchase({operation:e,signal:fe.signal})}}l=async()=>N(await i.read()),await N(e,!0)}function Fe(e){$?.remove();let t=!(Date.parse(e.expiresAt)>Date.now());u.textContent=t?a?"\u6B64\u62A5\u4EF7\u5DF2\u8FC7\u671F\u3002\u8BF7\u5148\u53D6\u6D88\uFF0C\u518D\u91CD\u65B0\u9009\u62E9\u3002":"This quote has expired. Cancel it, then choose again.":"";let n=d.createElement("div"),s=d.createElement("button"),o=d.createElement("button"),m=d.createElement("div"),x=d.createElement("p"),A=e.merchantTerms,de=a?"zh-CN":"en",z=A?.subscriptionTerms?.items??[],Re=A?A.subscriptionTerms?.trial?.days:e.lines.find(c=>c.trial)?.trial?.days,Z=Re===void 0?null:A?A.totalMinor:e.charge?e.charge.totalMinor:e.lines.every(c=>c.trial)?0:null,je=(c,f)=>a?`${f} \u5929\u8BD5\u7528\u7ED3\u675F\u540E ${c}`:`Then ${c} after the ${f}-day trial`,{label:bt,recurring:Qe}=Be(e),gt=e.lines.map(c=>c.productName).join(", "),ze=Z===null?"":`${a?"\u4ECA\u5929\u5E94\u4ED8":"Due today"} ${ee(Z,e.currency)}`;x.textContent=ze?[gt,ze].filter(Boolean).join(" \xB7 "):bt,s.textContent=a?"\u786E\u8BA4\u8D2D\u4E70":"Confirm purchase",s.disabled=t,o.textContent=a?"\u53D6\u6D88":"Cancel",n.style.cssText=P.panel,x.style.cssText=P.summary,m.style.cssText=P.actions,s.style.cssText=P.primary,o.style.cssText=P.secondary,Ne(s),s.onclick=()=>{q(ne)};let We=async()=>{let c=await i.cancel();p||(n.remove(),$=null,await N(c))};o.onclick=()=>{l=We,q(We)};let L=d.createElement("div");if(L.style.cssText=P.terms,A){for(let f of z){if(Z===null&&f===Qe)continue;let v=d.createElement("p"),M=ee(f.amountMinor,e.currency)+ie(f.interval,de,f.intervalCount);v.textContent=Z!==null&&Re!==void 0?je(M,Re):M,L.append(v)}let c=A.subscriptionTerms?.trial;if(c){let f=d.createElement("p");f.textContent=a?`\u8BD5\u7528 ${c.days} \u5929\uFF1B${c.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${c.days}; ${c.cardRequired?"a payment method is required":"no payment method is required"}`,L.append(f)}for(let f of[...A.expectedEffects.map(v=>v.description),...A.requiredConsents.map(v=>v.summary)]){let v=d.createElement("p");v.textContent=f,L.append(v)}}else{for(let c of e.lines){if(Z!==null||c!==Qe){let f=d.createElement("p"),v=`${ee(c.catalogAmountMinor,e.currency)}${ie(c.interval,de,c.intervalCount??1)}`;f.textContent=Z!==null&&c.trial?(e.lines.length>1?`${c.productName} \xB7 `:"")+je(v,c.trial.days):`${c.productName} \xB7 ${v}`,L.append(f)}for(let f of c.prepaid??[]){let v=d.createElement("p"),M=i.view?.capabilities.plans[c.productVersionId]?.prepaid?.find(vt=>vt.internalFeatureId===f.internal_feature_id);v.textContent=`${M?.name??f.internal_feature_id} \xB7 ${f.quantity} ${a?"\u4EFD":"packs"} \xD7 ${f.terms.units}`,M&&(v.textContent+=ie(M.reset==="week"||M.reset==="month"||M.reset==="year"?M.reset:"one_time",de,M.resetCount)),L.append(v)}if(c.trial){let f=d.createElement("p");f.textContent=a?`\u8BD5\u7528 ${c.trial.days} \u5929\uFF1B${c.trial.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${c.trial.days}; ${c.trial.cardRequired?"a payment method is required":"no payment method is required"}`,L.append(f)}}if(!e.charge){let c=d.createElement("p");c.textContent=a?"\u76EE\u5F55\u4EF7\u683C\uFF1B\u6700\u7EC8\u91D1\u989D\u4EE5\u7ED3\u8D26\u65F6\u7A0E\u8D39\u548C\u8BD5\u7528\u89C4\u5219\u4E3A\u51C6\u3002":"Catalog price; the final charge depends on checkout taxes and trial terms.",L.append(c)}}for(let c of L.children)c.style.margin="0";m.append(s,o),n.append(x,...L.childElementCount?[L]:[],m),U.prepend(n),g?.responsive||n.scrollIntoView?.({block:"nearest"}),s.focus({preventScroll:!0}),$=n,l=null}async function ue(){if(!E)return;if(l=ue,!oe){let n=i.view,s=n?.document.buttons[E.actionId],o=n&&s?.type==="checkout"?te(s.product,E.selection,n.capabilities):null;if(!o)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");let m=await r.resolveOfferId?.({actionId:E.actionId,productVersionId:o});if(p)return;m!==void 0&&(E.offerId=m),oe=!0}if(!R()){y.hidden=!1;return}let e;try{e=await i.preview(E)}catch(n){throw i.canReselect===!0&&(E=null,oe=!1,l=null),n}if(p)return;let t=e.merchantTerms;if(r.confirmOnHostedCheckout&&R()&&e.provider==="merchant"&&e.billingSubscriptionId===null&&t?.request.action==="purchase"&&t.request.mode==="subscription"&&t.subscriptionTerms?.trial===null&&t.requiredConsents.length===0&&Date.parse(e.expiresAt)>Date.now()){let n=a?"\u6B63\u5728\u6253\u5F00\u6536\u94F6\u53F0\u2026":"Opening checkout\u2026";u.textContent=n;try{await ne()}catch(s){p||Q(s)}finally{u.textContent===n&&(u.textContent="")}return}Fe(e)}function X(e="destroy"){p||(p=!0,r.signal?.removeEventListener("abort",B),i.signal?.removeEventListener("abort",B),C.finish("dismissed"),Ue?.(),fe.abort(),_e?.disconnect(),g?.destroy(),F?.destroy(),i.destroy(),w.open&&w.close(),w.remove(),I.remove(),O(),e==="dismiss"&&W(r.onDismiss))}S=X;async function ke(){if(!j||p||ae||V==="closing"||!V&&!R())return;if(!D){X("dismiss");return}let e=d.createElement("p");e.setAttribute("role","status"),e.textContent=a?"\u6B63\u5728\u5173\u95ED\u2026":"Closing\u2026",H||(H=d.createElement("div"),H.style.cssText=U.style.cssText,U.replaceWith(H),Y.inert=!0),b.hidden=!1,H.replaceChildren(e,b),V="closing",b.setAttribute("aria-disabled","true"),b.focus({preventScroll:!0});try{await D.dismiss()}catch(t){p||W(r.onError,t)}p||(V="retry",e.textContent=a?"\u672A\u80FD\u786E\u8BA4\u5173\u95ED\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not confirm closure. Try again.",b.textContent=a?"\u91CD\u8BD5\u5173\u95ED":"Retry closing",b.removeAttribute("aria-label"),b.removeAttribute("aria-disabled"))}b.onclick=()=>{ke()},w.addEventListener("cancel",e=>{e.preventDefault(),ke()}),y.onclick=()=>{l&&q(l)};function Ie(e){C.finish("error",e),X()}function Ae(){if(!(!Ve||j||p||ae||g&&!R()))try{let e=t=>{be?.(),g&&(w.showModal(),g.responsive&&w.focus({preventScroll:!0}),!t&&r.loading!=="host"&&Ze(w,g.type,g.responsive)),j=!0};D?D.present(()=>C.present(()=>e(!0))):C.present(e)}catch(e){Ie(e),Q(e)}}try{if(J.type==="inline")b.hidden=Object.values(h.document.buttons).some(t=>t.type==="close"),Me(),be=rt(I,T),T.append(I);else{let t={sm:420,md:640,lg:900};w.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in J?t[J.size]+"px":"100vw"}`,w.setAttribute("aria-label",h.document.name),b.textContent="\xD7",b.setAttribute("aria-label",a?"\u5173\u95ED":"Close"),et(b,h.document.screen.theme),Ke(h.document)?(b.hidden=!0,w.append(I)):w.append(b,I),T.append(w),g=Xe(w,{...h.document.screen,presentation:J},we),g.latch(),g.responsive&&(I.style.display="flex",I.style.flexDirection="column",I.style.maxHeight="100%",Y.style.overflow="clip",Y.style.minHeight="0"),be=nt(w)}F=ut(Y,{mode:"live",rendererUrl:i.webViewUrl,title:h.document.name,hostPresentation:()=>g?.type??J.type,reportContentHeight:g?.responsive,onResize:t=>{if(!g?.responsive)return;let n=Math.min(t,ye);Y.style.height=`${n}px`,g.setContentHeight(n+(H??U).getBoundingClientRect().height)},onAction(t,n={}){if(!j||p||V)return;if(!R()){Ee();return}let s=i.view,o=s?.document.buttons[t];if(!o)return;if(o.type==="close"){q(async()=>{await r.onAction?.(t),X(r.onAction?"action":"dismiss")});return}if(o.type==="action"){l=async()=>{if(o.action.type==="event"){if(!r.onEvent)throw new k("EVENT_HANDLER_REQUIRED","Provide the event handler");await r.onEvent(o.action.event)}else r.onOpenUrl?await r.onOpenUrl(o.action.url):d.defaultView?.location.assign(o.action.url);await r.onAction?.(t),l=null},q(l);return}if($&&i.canReselect===!1){u.textContent=a?"\u8BF7\u5148\u786E\u8BA4\u6216\u53D6\u6D88\u5F53\u524D\u8D2D\u4E70\u3002":"Confirm or cancel the current purchase first.",g?.responsive||$.scrollIntoView?.({block:"nearest"}),$.querySelector("button")?.focus({preventScroll:!0});return}if((i.quote||E)&&i.canReselect===!1){let x=!!s&&!!i.quote&&ht(i.quote,s,o.product,n);Ce=!!i.quote&&!x,l=i.quote?()=>xe(x):ue,q(l);return}let m=s&&te(o.product,n,s.capabilities);if(!s||!m){Q(new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(r.onPurchaseIntent){l=null,q(async()=>{let x={actionId:t,productVersionId:m,selection:structuredClone(n),featureQuantities:Oe(s.document.screen,m,n,s.capabilities)};ge=!0,await r.onPurchaseIntent(x)});return}if(E&&E.actionId!==t){Q(new k("COMMAND_PENDING","Finish the current purchase"));return}E||(E={requestId:crypto.randomUUID(),actionId:t,selection:n},oe=!1),q(ue)},onEscape:()=>{ke()},onError:t=>{let n=new Error(t);!j&&!p&&Ie(n),Q(n)},onRendered:t=>{t&&w.setAttribute("aria-label",t),Ve=!0,Ae()}}),we(),F.update(h.document.screen,h.document.screen.strings.defaultLocale,{capabilities:h.capabilities,unavailableActions:De(h),serverInput:{bindings:[],answers:{}}}),Ue=i.subscribe?.(he),he(i.view??h),await C.wait(F.ready);let e=i.operation;(i.quote||e&&(e.confirmedAt||e.checkoutUrl||e.status==="complete"))&&(l=()=>xe(),q(l))}catch(e){throw Ie(e),e}return{check:G,host:{get observing(){return me},get recovery(){return ft()},async prepareFallback(){if(K||p||V||ge)return{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null};le(!0);try{let e=await Ye(i);return e.type==="native"&&X(),e}finally{le(!1)}},setSuspended(e){ae=e,I.hidden=e,e&&w.open?w.close():!e&&!j?Ae():!e&&!p&&j&&J.type!=="inline"&&!w.open&&w.showModal()},destroy:X,refresh:async()=>{if(!R()){if(i.view)return i.view;throw new k("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await i.refresh();return he(e),Ae(),e}}}}export{zt as showPaywall};
@@ -1 +1 @@
1
- import{a}from"./chunk-XORU3PYW.js";import"./chunk-EZ5RCVVY.js";import"./chunk-YXCEZAQL.js";import"./chunk-23WNEOK4.js";import"./chunk-JNSU2AP2.js";import"./chunk-STPMMA64.js";import"./chunk-QPHT6QHE.js";import"./chunk-4ZVVG5LM.js";import"./chunk-LZV4QJ5E.js";import"./chunk-ITVSLSRM.js";import"./chunk-SJSCROSL.js";import"./chunk-B3KFE57L.js";import"./chunk-ACFQLHJR.js";import"./chunk-BQLT2LDP.js";import"./chunk-CLAZ7NVN.js";import"./chunk-J4VTKRH7.js";import"./chunk-WRUW2UIJ.js";import"./chunk-FJGJQGYF.js";import"./chunk-HJLGRW4A.js";import"./chunk-XIP32WI7.js";import"./chunk-3VUPVXAV.js";import"./chunk-OHOROFWN.js";import"./chunk-ZY4XAKNQ.js";import"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";export{a as createPaywallSession};
1
+ import{a}from"./chunk-S57HRPT2.js";import"./chunk-EZ5RCVVY.js";import"./chunk-YXCEZAQL.js";import"./chunk-23WNEOK4.js";import"./chunk-JNSU2AP2.js";import"./chunk-WK4WQZHK.js";import"./chunk-QPHT6QHE.js";import"./chunk-4ZVVG5LM.js";import"./chunk-LZV4QJ5E.js";import"./chunk-ITVSLSRM.js";import"./chunk-SJSCROSL.js";import"./chunk-B3KFE57L.js";import"./chunk-ACFQLHJR.js";import"./chunk-BQLT2LDP.js";import"./chunk-XZEGVBAI.js";import"./chunk-J4VTKRH7.js";import"./chunk-WRUW2UIJ.js";import"./chunk-FJGJQGYF.js";import"./chunk-HJLGRW4A.js";import"./chunk-XIP32WI7.js";import"./chunk-3VUPVXAV.js";import"./chunk-FVGUBIVT.js";import"./chunk-ZY4XAKNQ.js";import"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";export{a as createPaywallSession};
@@ -1 +1 @@
1
- import{b as S,c as E,d as T}from"./chunk-3TXBNPEP.js";import"./chunk-JWPTJLAN.js";import{a as A}from"./chunk-XORU3PYW.js";import{e as P}from"./chunk-EZ5RCVVY.js";import"./chunk-YXCEZAQL.js";import{h as b,i as x,k as L}from"./chunk-DIMBCG2C.js";import"./chunk-23WNEOK4.js";import"./chunk-JNSU2AP2.js";import{F as C}from"./chunk-XHQBABH6.js";import"./chunk-STPMMA64.js";import"./chunk-QPHT6QHE.js";import"./chunk-4ZVVG5LM.js";import"./chunk-LZV4QJ5E.js";import"./chunk-ITVSLSRM.js";import"./chunk-SJSCROSL.js";import"./chunk-B3KFE57L.js";import"./chunk-ACFQLHJR.js";import"./chunk-BQLT2LDP.js";import"./chunk-CLAZ7NVN.js";import"./chunk-J4VTKRH7.js";import"./chunk-WRUW2UIJ.js";import"./chunk-FJGJQGYF.js";import{a as r}from"./chunk-HJLGRW4A.js";import{h as R}from"./chunk-XIP32WI7.js";import"./chunk-3VUPVXAV.js";import"./chunk-OHOROFWN.js";import"./chunk-ZY4XAKNQ.js";import"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";function k(t,d){let n,a=0,m=-1,l,i=!1,y=()=>{if(i)throw new r("CLOSED","Native host was destroyed");if(!t.nativeModule)throw new r("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return t.nativeModule},o=()=>new r("IDENTITY_CHANGED","Customer identity changed during the native operation"),h=d.subscribeIdentity(()=>{a++,m=-1;let e=a;n&&t.nativeModule&&n.then(c=>t.nativeModule.reset(c,e)).catch(()=>{})}),I=t.nativeEvents?.(e=>{!n||!t.nativeModule||typeof e?.requestId!="string"||(async()=>{let c=await n;if(e.instanceId!==c)return;if(e.kind==="credential"){let w=a,f=null;try{if(!i&&e.revision===w){let N=await d.access();!i&&a===w&&(f=N)}}finally{await t.nativeModule.provideCredential(c,e.requestId,f)}return}let s=!1,u=a;try{if(i||e.revision!==u||!t.onNativeAction)throw o();await t.onNativeAction(e.action),s=!i&&a===u}finally{await t.nativeModule.acknowledge(c,e.requestId,s)}})().catch(()=>{})});async function p(e,c={}){let s=y();if(d.snapshot()&&!t.nativeEvents)throw new r("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let u=a,w=await d.access();if(i||a!==u)throw o();if(!n){let v=s.create(JSON.stringify({baseUrl:t.baseUrl??"https://api.longplayai.com",scope:t.scope,timeout:(t.timeoutMs??15e3)/1e3,credentialEvents:!!t.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let f=await n;if(i||a!==u)throw o();if(m!==u){if(!l||l.epoch!==u){let O=(async()=>{if(await s.identify(f,JSON.stringify({revision:u,credentials:w})),i||a!==u)throw await s.reset(f,u),o();m=u})();l={epoch:u,task:O}}let v=l;try{await v.task}finally{l===v&&(l=void 0)}}let N=await s.invoke(f,e,JSON.stringify(c));if(i||a!==u)throw o();try{return JSON.parse(N)}catch{throw new r("INVALID_RESPONSE","Native host returned invalid JSON")}}async function g(e,c){let s=await p(e,c);if(!s||typeof s!="object"||Array.isArray(s)||s.status!=="complete"&&s.status!=="dismissed")throw new r("INVALID_RESPONSE","Native presentation returned an invalid result");return s}return{showFunnel(e){return g("showFunnel",{runToken:e})},showPaywall(e){return g("showPaywall",e)},showContent(e){return g("showContent",e)},purchaseSubscription(e,c){return p("purchaseSubscription",{operationId:e,accepted:c})},switchSubscription(e,c){return p("switchSubscription",{operationId:e,accepted:c})},restorePurchases(){return p("restorePurchases")},manageSubscriptions(e){return p("manageSubscriptions",e?{productId:e}:{})},async dismiss(){a++,m=-1,n&&await y().reset(await n,a)},async destroy(){i||(i=!0,a++,h(),I?.(),n&&t.nativeModule&&await t.nativeModule.destroy(await n))}}}var M=P.trackUsage.request.shape.command,U=P.trackUsage.response;function F(t){let d=R.parse(t.scope),n=S({...t,scope:d}),a={...t,scope:d,session:n.session},m=k(t,n.session),l=0,i=!1;n.subscribeIdentity(()=>{l++});let y=()=>{if(i)throw new r("CLOSED","SDK client was destroyed");let o=n.session.peek();if(!o)throw new r("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:m,async destroy(){i||(i=!0,l++,n.destroy(),await m.destroy())},funnel(){return E({...a,customerToken:y()})},resumeFunnel(o){return y(),C({...a,runToken:o})},paywall(o){return A(a,{...o,customerToken:y()})},async trackUsage(o){if(y(),!t.usageReporter)throw new r("INVALID_REQUEST","Configure your authenticated backend usageReporter");let h=M.parse(o),I=l,p;try{p=await t.usageReporter(h)}catch(e){throw I!==l?new r("IDENTITY_CHANGED","Customer identity changed during usage reporting"):e}if(I!==l)throw new r("IDENTITY_CHANGED","Customer identity changed during usage reporting");let g=U.parse(p);if(g.scope.projectId!==d.projectId||g.scope.environment!==d.environment)throw new r("INVALID_RESPONSE","Usage response scope differs");return g}}}export{r as LongplayError,x as createConfigurationSync,b as createFeatureClient,T as createFunnelProcess,L as createLocalFunnelClient,F as createLongplayReactNative};
1
+ import{b as S,c as E,d as T}from"./chunk-D3UU546S.js";import"./chunk-2TPPGW7V.js";import{a as A}from"./chunk-S57HRPT2.js";import{e as P}from"./chunk-EZ5RCVVY.js";import"./chunk-YXCEZAQL.js";import{h as b,i as x,k as L}from"./chunk-2QQZSMTB.js";import"./chunk-23WNEOK4.js";import"./chunk-JNSU2AP2.js";import{F as C}from"./chunk-7Z7JT4HE.js";import"./chunk-WK4WQZHK.js";import"./chunk-QPHT6QHE.js";import"./chunk-4ZVVG5LM.js";import"./chunk-LZV4QJ5E.js";import"./chunk-ITVSLSRM.js";import"./chunk-SJSCROSL.js";import"./chunk-B3KFE57L.js";import"./chunk-ACFQLHJR.js";import"./chunk-BQLT2LDP.js";import"./chunk-XZEGVBAI.js";import"./chunk-J4VTKRH7.js";import"./chunk-WRUW2UIJ.js";import"./chunk-FJGJQGYF.js";import{a as r}from"./chunk-HJLGRW4A.js";import{h as R}from"./chunk-XIP32WI7.js";import"./chunk-3VUPVXAV.js";import"./chunk-FVGUBIVT.js";import"./chunk-ZY4XAKNQ.js";import"./chunk-DSPLGTQI.js";import"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";function k(t,d){let n,a=0,m=-1,l,i=!1,y=()=>{if(i)throw new r("CLOSED","Native host was destroyed");if(!t.nativeModule)throw new r("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return t.nativeModule},o=()=>new r("IDENTITY_CHANGED","Customer identity changed during the native operation"),h=d.subscribeIdentity(()=>{a++,m=-1;let e=a;n&&t.nativeModule&&n.then(c=>t.nativeModule.reset(c,e)).catch(()=>{})}),I=t.nativeEvents?.(e=>{!n||!t.nativeModule||typeof e?.requestId!="string"||(async()=>{let c=await n;if(e.instanceId!==c)return;if(e.kind==="credential"){let w=a,f=null;try{if(!i&&e.revision===w){let N=await d.access();!i&&a===w&&(f=N)}}finally{await t.nativeModule.provideCredential(c,e.requestId,f)}return}let s=!1,u=a;try{if(i||e.revision!==u||!t.onNativeAction)throw o();await t.onNativeAction(e.action),s=!i&&a===u}finally{await t.nativeModule.acknowledge(c,e.requestId,s)}})().catch(()=>{})});async function p(e,c={}){let s=y();if(d.snapshot()&&!t.nativeEvents)throw new r("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let u=a,w=await d.access();if(i||a!==u)throw o();if(!n){let v=s.create(JSON.stringify({baseUrl:t.baseUrl??"https://api.longplayai.com",scope:t.scope,timeout:(t.timeoutMs??15e3)/1e3,credentialEvents:!!t.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let f=await n;if(i||a!==u)throw o();if(m!==u){if(!l||l.epoch!==u){let O=(async()=>{if(await s.identify(f,JSON.stringify({revision:u,credentials:w})),i||a!==u)throw await s.reset(f,u),o();m=u})();l={epoch:u,task:O}}let v=l;try{await v.task}finally{l===v&&(l=void 0)}}let N=await s.invoke(f,e,JSON.stringify(c));if(i||a!==u)throw o();try{return JSON.parse(N)}catch{throw new r("INVALID_RESPONSE","Native host returned invalid JSON")}}async function g(e,c){let s=await p(e,c);if(!s||typeof s!="object"||Array.isArray(s)||s.status!=="complete"&&s.status!=="dismissed")throw new r("INVALID_RESPONSE","Native presentation returned an invalid result");return s}return{showFunnel(e){return g("showFunnel",{runToken:e})},showPaywall(e){return g("showPaywall",e)},showContent(e){return g("showContent",e)},purchaseSubscription(e,c){return p("purchaseSubscription",{operationId:e,accepted:c})},switchSubscription(e,c){return p("switchSubscription",{operationId:e,accepted:c})},restorePurchases(){return p("restorePurchases")},manageSubscriptions(e){return p("manageSubscriptions",e?{productId:e}:{})},async dismiss(){a++,m=-1,n&&await y().reset(await n,a)},async destroy(){i||(i=!0,a++,h(),I?.(),n&&t.nativeModule&&await t.nativeModule.destroy(await n))}}}var M=P.trackUsage.request.shape.command,U=P.trackUsage.response;function F(t){let d=R.parse(t.scope),n=S({...t,scope:d}),a={...t,scope:d,session:n.session},m=k(t,n.session),l=0,i=!1;n.subscribeIdentity(()=>{l++});let y=()=>{if(i)throw new r("CLOSED","SDK client was destroyed");let o=n.session.peek();if(!o)throw new r("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:m,async destroy(){i||(i=!0,l++,n.destroy(),await m.destroy())},funnel(){return E({...a,customerToken:y()})},resumeFunnel(o){return y(),C({...a,runToken:o})},paywall(o){return A(a,{...o,customerToken:y()})},async trackUsage(o){if(y(),!t.usageReporter)throw new r("INVALID_REQUEST","Configure your authenticated backend usageReporter");let h=M.parse(o),I=l,p;try{p=await t.usageReporter(h)}catch(e){throw I!==l?new r("IDENTITY_CHANGED","Customer identity changed during usage reporting"):e}if(I!==l)throw new r("IDENTITY_CHANGED","Customer identity changed during usage reporting");let g=U.parse(p);if(g.scope.projectId!==d.projectId||g.scope.environment!==d.environment)throw new r("INVALID_RESPONSE","Usage response scope differs");return g}}}export{r as LongplayError,x as createConfigurationSync,b as createFeatureClient,T as createFunnelProcess,L as createLocalFunnelClient,F as createLongplayReactNative};
package/dist/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as pn}from"./chunk-U6BYOYEE.js";import{a as I}from"./chunk-TMZGZAWM.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-5N7QFF5M.js";import{a as xt}from"./chunk-XORU3PYW.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-EZ5RCVVY.js";import"./chunk-YXCEZAQL.js";import{a as Te,b as oe,c as yt,d as It,e as wt,f as xe,g as vt,h as _e,i as dn,j as ln,k as mn}from"./chunk-DIMBCG2C.js";import{a as Et,b as Me}from"./chunk-23WNEOK4.js";import"./chunk-JNSU2AP2.js";import{A as Tt,C as V,D as N,a as Oe,e as ft,f as ht,l as gt,m as j,n as St,q as Ct,r as Rt,s as bt,t as At,u as Ot,z as pe}from"./chunk-XHQBABH6.js";import{c as f}from"./chunk-STPMMA64.js";import"./chunk-QPHT6QHE.js";import{e as at}from"./chunk-4ZVVG5LM.js";import{A as tt,B as Se,C as ae,E as ie,F as Ce,K as se,M as ce,N as nt,P as Ee,Q as rt,R as ot,d as Ge,e as je,h as we,p as ze,q as Ke,s as an,t as sn,w as cn,x as Q,y as J,z as re}from"./chunk-LZV4QJ5E.js";import{A as Re,B as st,C as ct,H as ut,I as dt,J as be,K as Ae,S as pt,T as de,U as Y,V as lt,_ as mt,d as ve,f as Ze,g as et,u as q,z as it}from"./chunk-ITVSLSRM.js";import"./chunk-SJSCROSL.js";import"./chunk-B3KFE57L.js";import"./chunk-ACFQLHJR.js";import"./chunk-BQLT2LDP.js";import"./chunk-CLAZ7NVN.js";import{a as Ne,b as Le}from"./chunk-J4VTKRH7.js";import{V as Xe,Y as We,la as ue,n as un,p as $e,q as Qe,r as Je}from"./chunk-WRUW2UIJ.js";import{c as Ie}from"./chunk-FJGJQGYF.js";import{a as c}from"./chunk-HJLGRW4A.js";import{h as $}from"./chunk-XIP32WI7.js";import"./chunk-3VUPVXAV.js";import"./chunk-OHOROFWN.js";import{b as u}from"./chunk-ZY4XAKNQ.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";var Mt=4,_t=[...tt,"requirement_checks","native_offers","preparations","benefit_claims","authorizations","business_results"],In=u.enum(_t),X=(e,n)=>u.array(e).max(n).refine(t=>new Set(t).size===t.length,"Declarations must be unique"),ke=u.strictObject({...ie.shape,bridgeVersion:u.literal(Mt),capabilities:X(In,_t.length),checkKinds:X(u.enum(["access","metered","credit"]),3),preparationActions:X(u.enum(["purchase","subscription_change","refund"]),3),authorizationKinds:X(u.enum(["auto_topup"]),1),nextActionTypes:X(u.enum(["redirect","authenticate"]),2),resultEvents:X(u.enum(["benefit.claimed","authorization.updated"]),2)}).superRefine((e,n)=>{e.capabilities.includes("catalog")!==(e.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(e.capabilities.includes("billing_records")!==e.billingEvents.length>0||new Set(e.billingEvents).size!==e.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare unique supported billing events"});let t=r=>e.capabilities.includes(r),o=(r,a)=>n.addIssue({code:"custom",path:[r],message:a});t("requirement_checks")!==e.checkKinds.length>0&&o("checkKinds","Declare the supported Check kinds"),t("preparations")!==e.preparationActions.length>0&&o("preparationActions","Declare the supported preparation actions"),t("authorizations")!==e.authorizationKinds.length>0&&o("authorizationKinds","Declare the supported authorization kinds"),t("business_results")!==e.resultEvents.length>0&&o("resultEvents","Declare the supported non-financial results");for(let[r,a,s]of[["purchases","purchase","purchase.completed"],["subscription_changes","subscription_change","subscription.change.completed"],["refunds","refund","refund.updated"]])t(r)&&(!t("operation_status")||!t("billing_records")||!t("preparations")||!e.preparationActions.includes(a)||!e.billingEvents.includes(s))&&o("capabilities",`${r} requires preparation, original lookup and its billing result`);t("purchases")&&!e.billingEvents.includes("purchase.closed")&&o("billingEvents","Purchase execution requires its terminal closure result"),t("subscription_changes")&&!e.billingEvents.includes("subscription.change.closed")&&o("billingEvents","Subscription change execution requires its terminal closure result");for(let[r,a]of[["benefit_claims","benefit.claimed"],["authorizations","authorization.updated"]])t(r)&&(!t("operation_status")||!t("business_results")||!e.resultEvents.includes(a))&&o("capabilities",`${r} requires original lookup and its non-financial result`)}),W={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":u.strictObject({}),"requirement.check":$e,"operation.prepare":ze,"benefit.claim":Ue,"operation.read":qe},wn={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":ke,"requirement.check":Qe,"operation.prepare":Ke,"benefit.claim":Ve,"operation.read":He},Hn=u.enum(["bridge.ping","bridge.describe","requirement.check","operation.prepare","benefit.claim","operation.read"]);function Z(e,n){return u.strictObject({bridgeVersion:u.literal(Mt),requestId:u.uuid(),scope:Ce,command:u.literal(e),data:n})}var kt=u.discriminatedUnion("command",[Z("bridge.ping",W["bridge.ping"]),Z("bridge.describe",W["bridge.describe"]),Z("requirement.check",W["requirement.check"]),Z("operation.prepare",W["operation.prepare"]),Z("benefit.claim",W["benefit.claim"]),Z("operation.read",W["operation.read"])]),Be=u.strictObject({code:u.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:u.string().min(1).max(500),retryable:u.boolean(),recovery:u.string().min(1).max(80),effect:u.enum(["none","unknown"])}).refine(e=>e.effect!=="unknown"||!e.retryable&&e.recovery==="recover_operation","Unknown effects require original-operation recovery");function Bt(e){let n={bridgeVersion:u.literal(4),requestId:u.uuid(),scope:Ce,command:u.literal(e)};return u.union([u.strictObject({...n,data:wn[e]}),u.strictObject({...n,error:Be})])}var Pt="X-Indiana-Bridge-Signature",z="X-Indiana-Bridge-Key-Id";function vn(e){return new TextEncoder().encode(e)}function Dt(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),n=>n.charCodeAt(0))}function Ft(e,n,t,o){return vn(`indiana-merchant-bridge:${o}
1
+ import{a as pn}from"./chunk-NH5ML5SB.js";import{a as I}from"./chunk-TMZGZAWM.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-5N7QFF5M.js";import{a as xt}from"./chunk-S57HRPT2.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-EZ5RCVVY.js";import"./chunk-YXCEZAQL.js";import{a as Te,b as oe,c as yt,d as It,e as wt,f as xe,g as vt,h as _e,i as dn,j as ln,k as mn}from"./chunk-2QQZSMTB.js";import{a as Et,b as Me}from"./chunk-23WNEOK4.js";import"./chunk-JNSU2AP2.js";import{A as Tt,C as V,D as N,a as Oe,e as ft,f as ht,l as gt,m as j,n as St,q as Ct,r as Rt,s as bt,t as At,u as Ot,z as pe}from"./chunk-7Z7JT4HE.js";import{c as f}from"./chunk-WK4WQZHK.js";import"./chunk-QPHT6QHE.js";import{e as at}from"./chunk-4ZVVG5LM.js";import{A as tt,B as Se,C as ae,E as ie,F as Ce,K as se,M as ce,N as nt,P as Ee,Q as rt,R as ot,d as Ge,e as je,h as we,p as ze,q as Ke,s as an,t as sn,w as cn,x as Q,y as J,z as re}from"./chunk-LZV4QJ5E.js";import{A as Re,B as st,C as ct,H as ut,I as dt,J as be,K as Ae,S as pt,T as de,U as Y,V as lt,_ as mt,d as ve,f as Ze,g as et,u as q,z as it}from"./chunk-ITVSLSRM.js";import"./chunk-SJSCROSL.js";import"./chunk-B3KFE57L.js";import"./chunk-ACFQLHJR.js";import"./chunk-BQLT2LDP.js";import"./chunk-XZEGVBAI.js";import{a as Ne,b as Le}from"./chunk-J4VTKRH7.js";import{V as Xe,Y as We,la as ue,n as un,p as $e,q as Qe,r as Je}from"./chunk-WRUW2UIJ.js";import{c as Ie}from"./chunk-FJGJQGYF.js";import{a as c}from"./chunk-HJLGRW4A.js";import{h as $}from"./chunk-XIP32WI7.js";import"./chunk-3VUPVXAV.js";import"./chunk-FVGUBIVT.js";import{b as u}from"./chunk-ZY4XAKNQ.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";var Mt=4,_t=[...tt,"requirement_checks","native_offers","preparations","benefit_claims","authorizations","business_results"],In=u.enum(_t),X=(e,n)=>u.array(e).max(n).refine(t=>new Set(t).size===t.length,"Declarations must be unique"),ke=u.strictObject({...ie.shape,bridgeVersion:u.literal(Mt),capabilities:X(In,_t.length),checkKinds:X(u.enum(["access","metered","credit"]),3),preparationActions:X(u.enum(["purchase","subscription_change","refund"]),3),authorizationKinds:X(u.enum(["auto_topup"]),1),nextActionTypes:X(u.enum(["redirect","authenticate"]),2),resultEvents:X(u.enum(["benefit.claimed","authorization.updated"]),2)}).superRefine((e,n)=>{e.capabilities.includes("catalog")!==(e.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(e.capabilities.includes("billing_records")!==e.billingEvents.length>0||new Set(e.billingEvents).size!==e.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare unique supported billing events"});let t=r=>e.capabilities.includes(r),o=(r,a)=>n.addIssue({code:"custom",path:[r],message:a});t("requirement_checks")!==e.checkKinds.length>0&&o("checkKinds","Declare the supported Check kinds"),t("preparations")!==e.preparationActions.length>0&&o("preparationActions","Declare the supported preparation actions"),t("authorizations")!==e.authorizationKinds.length>0&&o("authorizationKinds","Declare the supported authorization kinds"),t("business_results")!==e.resultEvents.length>0&&o("resultEvents","Declare the supported non-financial results");for(let[r,a,s]of[["purchases","purchase","purchase.completed"],["subscription_changes","subscription_change","subscription.change.completed"],["refunds","refund","refund.updated"]])t(r)&&(!t("operation_status")||!t("billing_records")||!t("preparations")||!e.preparationActions.includes(a)||!e.billingEvents.includes(s))&&o("capabilities",`${r} requires preparation, original lookup and its billing result`);t("purchases")&&!e.billingEvents.includes("purchase.closed")&&o("billingEvents","Purchase execution requires its terminal closure result"),t("subscription_changes")&&!e.billingEvents.includes("subscription.change.closed")&&o("billingEvents","Subscription change execution requires its terminal closure result");for(let[r,a]of[["benefit_claims","benefit.claimed"],["authorizations","authorization.updated"]])t(r)&&(!t("operation_status")||!t("business_results")||!e.resultEvents.includes(a))&&o("capabilities",`${r} requires original lookup and its non-financial result`)}),W={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":u.strictObject({}),"requirement.check":$e,"operation.prepare":ze,"benefit.claim":Ue,"operation.read":qe},wn={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":ke,"requirement.check":Qe,"operation.prepare":Ke,"benefit.claim":Ve,"operation.read":He},Hn=u.enum(["bridge.ping","bridge.describe","requirement.check","operation.prepare","benefit.claim","operation.read"]);function Z(e,n){return u.strictObject({bridgeVersion:u.literal(Mt),requestId:u.uuid(),scope:Ce,command:u.literal(e),data:n})}var kt=u.discriminatedUnion("command",[Z("bridge.ping",W["bridge.ping"]),Z("bridge.describe",W["bridge.describe"]),Z("requirement.check",W["requirement.check"]),Z("operation.prepare",W["operation.prepare"]),Z("benefit.claim",W["benefit.claim"]),Z("operation.read",W["operation.read"])]),Be=u.strictObject({code:u.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:u.string().min(1).max(500),retryable:u.boolean(),recovery:u.string().min(1).max(80),effect:u.enum(["none","unknown"])}).refine(e=>e.effect!=="unknown"||!e.retryable&&e.recovery==="recover_operation","Unknown effects require original-operation recovery");function Bt(e){let n={bridgeVersion:u.literal(4),requestId:u.uuid(),scope:Ce,command:u.literal(e)};return u.union([u.strictObject({...n,data:wn[e]}),u.strictObject({...n,error:Be})])}var Pt="X-Indiana-Bridge-Signature",z="X-Indiana-Bridge-Key-Id";function vn(e){return new TextEncoder().encode(e)}function Dt(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),n=>n.charCodeAt(0))}function Ft(e,n,t,o){return vn(`indiana-merchant-bridge:${o}
2
2
  ${n}
3
3
  POST
4
4
  ${J}
package/dist/visual.js CHANGED
@@ -1 +1 @@
1
- import{a as pe,c as fe}from"./chunk-RFUXSC52.js";import{b as ue}from"./chunk-J6KIN4RH.js";import{a as Ve,b as re,c as ce,d as de}from"./chunk-SLUA7ABW.js";import{a as J,b as F,c as ge,e as me}from"./chunk-U6ULFK7M.js";import{a as ae,b as se,c as oe,d as le}from"./chunk-XRR5X74T.js";import"./chunk-3VUPVXAV.js";import"./chunk-OHOROFWN.js";import{b as o}from"./chunk-ZY4XAKNQ.js";import"./chunk-DSPLGTQI.js";import{c as te,e as ie,g as M}from"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";var K="indiana-visual-diagnostics-v1",Ae=o.strictObject({environmentId:o.string().uuid(),release:o.string().regex(/^[a-f0-9]{64}$/).nullable(),generation:o.string().regex(/^[a-f0-9]{64}$/).nullable(),publishedGeneration:o.string().regex(/^[a-f0-9]{64}$/).nullable(),checkedAt:o.string().datetime(),origin:o.string().url(),pathname:o.string().max(2048),urlMatches:o.boolean(),stopped:o.boolean(),rows:o.array(o.strictObject({changeId:o.string().regex(/^[a-f0-9]{64}$/),experimentKey:o.string().max(256),variationKey:o.string().max(256),inExperiment:o.boolean(),fingerprint:o.string().regex(/^[a-f0-9]{64}$/),status:o.enum(["inactive","waiting","partial","applied","mismatch","no_changes","unavailable","error"]),total:o.number().int().min(0).max(600),applied:o.number().int().min(0).max(600)})).max(100)});function ye(e){let l=n=>Array.isArray(n)?"["+n.map(l).join(",")+"]":n&&typeof n=="object"?"{"+Object.entries(n).filter(([,c])=>c!==void 0).sort(([c],[y])=>c.localeCompare(y)).map(([c,y])=>JSON.stringify(c)+":"+l(y)).join(",")+"}":JSON.stringify(n);return l({css:e.css,js:e.js,domMutations:e.domMutations,...e.renderGuard?{renderGuard:e.renderGuard}:{}})}function he(e){let l=new URL(e.baseUrl),n=l.origin==="https://api.longplayai.com"||l.origin==="https://api.dev.longplayai.com"?l.hostname.slice(4):void 0,c=e.origins??(n?[`https://console.${n}`]:[]),y=new Set(c.filter(t=>{try{let i=new URL(t);return i.origin===t&&(i.protocol==="https:"||i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname))}catch{return!1}})),v=!1,I=!1,k=0,T=async t=>{if(v||I||!t.source||!y.has(t.origin)||!t.data||typeof t.data!="object")return;let i=t.data;if(!(i.channel!==K||i.type!=="inspect"||i.environmentId!==e.environmentId||typeof i.nonce!="string"||!/^[a-f0-9-]{36}$/i.test(i.nonce)||typeof i.changeId!="string"||!/^[a-f0-9]{64}$/.test(i.changeId)||typeof i.url!="string"||i.url.length>2048||Date.now()-k<250)){try{if(new URL(i.url).origin!==location.origin)return}catch{return}I=!0,k=Date.now();try{let x=await e.inspect(i.changeId,i.url);!v&&x.rows.some(S=>S.changeId===i.changeId)&&t.source.postMessage({channel:K,type:"result",nonce:i.nonce,snapshot:x},t.origin)}finally{I=!1}}},u=t=>{T(t).catch(()=>{})};return window.addEventListener("message",u),()=>{v=!0,window.removeEventListener("message",u)}}var R=e=>!!e&&typeof e=="object"&&!Array.isArray(e),E=(e,l)=>typeof e=="string"&&e.length<=l,Ee=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function ke(e){if(!R(e)||!E(e.css??"",1e5)||!E(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let l=e.domMutations??[];for(let n of l)if(!R(n)||!E(n.selector,2048)||!n.selector||!Ee(n.attribute)||!["set","append","remove"].includes(String(n.action))||n.value!==void 0&&!E(n.value,5e4)||n.parentSelector!==void 0&&!E(n.parentSelector,2048)||n.insertBeforeSelector!==void 0&&!E(n.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:l,...e.renderGuard===void 0?{}:{renderGuard:ue(e.renderGuard)}}}function q(e){if(!R(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!R(e.savedGroups))throw new Error("Invalid visual experiment payload");let l=e.experiments.map(n=>{if(!R(n)||!["key","changeId"].every(c=>typeof n[c]=="string"&&n[c])||!/^[a-f0-9]{64}$/.test(String(n.changeId))||["namespace","status","groups","url"].some(c=>Object.hasOwn(n,c))||n.hashVersion!==void 0&&n.hashVersion!==2||!Array.isArray(n.variations)||n.variations.length<2||n.variations.length>20||n.urlPatterns!==void 0&&!Array.isArray(n.urlPatterns))throw new Error("Invalid visual experiment");return{...n,variations:n.variations.map(ke)}});return{...e,experiments:l}}var ve=6e4;function qe(e){let l=oe(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),c=F(n),y=F(n),v=`${l}/api/v1/visual-experiments/${e.environmentId}`,I=e.appManifestRelease?`${v}?iam=${e.appManifestRelease}`:v,k=ae(e.deviceIdCookie??"indiana_did"),T=se(),u=null,t=!1,i=!1,x="",S={...e.attributes??{}},G,B,D=0,H=-1/0,$,m=new Map,O=new Map,C=new Set,z=ge({endpoint:`${v}/events`,fetch:n,log:e.log,label:"Visual exposure"}),P=z.flush,W,b;function j(){clearTimeout(W),b?.remove(),b=void 0}function Y(s,d){let f=M(s,d);C.has(f)||e.trackExposures===!1||u?.trackExposures===!1||t||(C.add(f),z.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:k,...T?{sessionId:T}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:s.key,variationKey:d.key}))}function we(s){if(!u||t)return;let d=new Set,f={onExperimentViewed:(r,p)=>{d.add(M(r,p))},url:location.href,attributes:{...me(k,location),...S,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:te(u.savedGroups),log:e.log},h=new Set;for(let r of u.experiments){if(ce(`${e.environmentId}:${r.key}`))continue;let p=r;try{let a=ie(p,f);if(O.set(r.changeId,a),!a.inExperiment)continue;h.add(r.changeId);let w=JSON.stringify([a.key,a.value]),U=m.get(r.changeId);if(U?.signature===w){d.has(M(p,a))&&s.push(()=>{U.applied()&&Y(p,a)});continue}m.get(r.changeId)?.revert(),m.delete(r.changeId);let A=fe(a.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(r.condition?.$and)&&r.condition.$and.some(g=>g!==null&&typeof g=="object"&&!Array.isArray(g)&&g.indianaAppManifestRelease===e.appManifestRelease),boundVariations:r.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{d.has(M(p,a))&&Y(p,a)},onError:g=>e.log?.("Visual experiment stopped",{experiment:r.key,changeId:r.changeId,variation:a.key,error:String(g)}),onTargetStatus:e.log?g=>e.log?.("Visual target status changed",{experiment:r.key,changeId:r.changeId,variation:a.key,...g}):void 0});m.set(r.changeId,{signature:w,revert:A.revert,applied:()=>A.applied,inspect:()=>A.inspect()})}catch(a){e.log?.("Skipping visual experiment",{experiment:r.key,error:String(a)})}}for(let[r,p]of m)h.has(r)||(p.revert(),m.delete(r));j()}let V=()=>{let s=[];pe(()=>we(s));for(let d of s)d()};async function _(){let s=++D,d;try{d=await c.read(I,J)}catch(h){if(t||s!==D)return!1;throw h}let f=q(d);if(f.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return t||s!==D?!1:(u=f,H=performance.now(),!0)}async function Q(){!await _()||t||(N(),V())}function L(){clearTimeout($),$=setTimeout(()=>{if(document.visibilityState==="hidden")return L();Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()})},ve)}let X=()=>{t||document.visibilityState==="hidden"||performance.now()-H<ve||(clearTimeout($),Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()}))},Ie=()=>{x!==location.href&&(x=location.href,V())},Z=()=>{P(!0)},N=()=>{G||t||(G=le(Ie),addEventListener("pagehide",Z),x=location.href)};async function ee(s,d){let f=location.href,h=u,r=[],p=null;if(!t)try{let a=q(await y.read(I,J));a.environmentId===e.environmentId&&(p=a.generation)}catch{}for(let a of h?.experiments??[]){if(s&&a.changeId!==s)continue;let w=O.get(a.changeId);if(!w)continue;let U=new TextEncoder().encode(ye(w.value)),A=[...new Uint8Array(await crypto.subtle.digest("SHA-256",U))].map(be=>be.toString(16).padStart(2,"0")).join(""),g=m.get(a.changeId)?.inspect()??{status:"inactive",total:0,applied:0};r.push({changeId:a.changeId,experimentKey:a.key,variationKey:w.key,inExperiment:w.inExperiment,fingerprint:A,...g})}return{environmentId:e.environmentId,release:e.appManifestRelease??null,generation:h?.generation??null,publishedGeneration:p,checkedAt:new Date().toISOString(),origin:location.origin,pathname:location.pathname,urlMatches:location.href===f&&(!d||d===f)&&h===u,stopped:t,rows:r}}let ne,xe=de(()=>{i&&!t&&V()});return{async start(){if(!(i||t)){i=!0,e.appManifestRelease&&(B=re(e.appManifestRelease)),e.antiFlicker&&(b=document.createElement("style"),e.nonce&&(b.nonce=e.nonce),b.textContent="body { visibility: hidden !important }",document.head.append(b),W=setTimeout(j,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await _()||t)return;N(),V()}finally{j(),t||(L(),document.addEventListener("visibilitychange",X),ne=he({environmentId:e.environmentId,baseUrl:l,origins:e.diagnosticsOrigins,inspect:ee}))}}},async refresh(){t||await _()&&(i&&N(),V())},setAttributes(s){S={...s},V()},flush:()=>P(),getDiagnostics:ee,getResults(){return new Map(O)},get generation(){return u?.generation??null},destroy(){t=!0,clearTimeout($),document.removeEventListener("visibilitychange",X),xe(),ne?.(),D++,c.destroy(),y.destroy(),G?.(),B?.destroy(),removeEventListener("pagehide",Z),j();for(let s of m.values())s.revert();m.clear(),P(!0),u=null,O.clear(),C.clear(),S={}}}}export{qe as createVisualExperiments,Ve as loadAppManifestRelease};
1
+ import{a as pe,c as fe}from"./chunk-RFUXSC52.js";import{b as ue}from"./chunk-J6KIN4RH.js";import{a as Ve,b as re,c as ce,d as de}from"./chunk-SLUA7ABW.js";import{a as J,b as F,c as ge,e as me}from"./chunk-S5H3WJVQ.js";import{a as ae,b as se,c as oe,d as le}from"./chunk-ZYTT7ZAB.js";import"./chunk-3VUPVXAV.js";import"./chunk-FVGUBIVT.js";import{b as o}from"./chunk-ZY4XAKNQ.js";import"./chunk-DSPLGTQI.js";import{c as te,e as ie,g as M}from"./chunk-6BTJNSQQ.js";import"./chunk-PWXN3W4Q.js";import"./chunk-WOT6VMZA.js";var K="indiana-visual-diagnostics-v1",Ae=o.strictObject({environmentId:o.string().uuid(),release:o.string().regex(/^[a-f0-9]{64}$/).nullable(),generation:o.string().regex(/^[a-f0-9]{64}$/).nullable(),publishedGeneration:o.string().regex(/^[a-f0-9]{64}$/).nullable(),checkedAt:o.string().datetime(),origin:o.string().url(),pathname:o.string().max(2048),urlMatches:o.boolean(),stopped:o.boolean(),rows:o.array(o.strictObject({changeId:o.string().regex(/^[a-f0-9]{64}$/),experimentKey:o.string().max(256),variationKey:o.string().max(256),inExperiment:o.boolean(),fingerprint:o.string().regex(/^[a-f0-9]{64}$/),status:o.enum(["inactive","waiting","partial","applied","mismatch","no_changes","unavailable","error"]),total:o.number().int().min(0).max(600),applied:o.number().int().min(0).max(600)})).max(100)});function ye(e){let l=n=>Array.isArray(n)?"["+n.map(l).join(",")+"]":n&&typeof n=="object"?"{"+Object.entries(n).filter(([,c])=>c!==void 0).sort(([c],[y])=>c.localeCompare(y)).map(([c,y])=>JSON.stringify(c)+":"+l(y)).join(",")+"}":JSON.stringify(n);return l({css:e.css,js:e.js,domMutations:e.domMutations,...e.renderGuard?{renderGuard:e.renderGuard}:{}})}function he(e){let l=new URL(e.baseUrl),n=l.origin==="https://api.longplayai.com"||l.origin==="https://api.dev.longplayai.com"?l.hostname.slice(4):void 0,c=e.origins??(n?[`https://console.${n}`]:[]),y=new Set(c.filter(t=>{try{let i=new URL(t);return i.origin===t&&(i.protocol==="https:"||i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname))}catch{return!1}})),v=!1,I=!1,k=0,T=async t=>{if(v||I||!t.source||!y.has(t.origin)||!t.data||typeof t.data!="object")return;let i=t.data;if(!(i.channel!==K||i.type!=="inspect"||i.environmentId!==e.environmentId||typeof i.nonce!="string"||!/^[a-f0-9-]{36}$/i.test(i.nonce)||typeof i.changeId!="string"||!/^[a-f0-9]{64}$/.test(i.changeId)||typeof i.url!="string"||i.url.length>2048||Date.now()-k<250)){try{if(new URL(i.url).origin!==location.origin)return}catch{return}I=!0,k=Date.now();try{let x=await e.inspect(i.changeId,i.url);!v&&x.rows.some(S=>S.changeId===i.changeId)&&t.source.postMessage({channel:K,type:"result",nonce:i.nonce,snapshot:x},t.origin)}finally{I=!1}}},u=t=>{T(t).catch(()=>{})};return window.addEventListener("message",u),()=>{v=!0,window.removeEventListener("message",u)}}var R=e=>!!e&&typeof e=="object"&&!Array.isArray(e),E=(e,l)=>typeof e=="string"&&e.length<=l,Ee=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function ke(e){if(!R(e)||!E(e.css??"",1e5)||!E(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let l=e.domMutations??[];for(let n of l)if(!R(n)||!E(n.selector,2048)||!n.selector||!Ee(n.attribute)||!["set","append","remove"].includes(String(n.action))||n.value!==void 0&&!E(n.value,5e4)||n.parentSelector!==void 0&&!E(n.parentSelector,2048)||n.insertBeforeSelector!==void 0&&!E(n.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:l,...e.renderGuard===void 0?{}:{renderGuard:ue(e.renderGuard)}}}function q(e){if(!R(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!R(e.savedGroups))throw new Error("Invalid visual experiment payload");let l=e.experiments.map(n=>{if(!R(n)||!["key","changeId"].every(c=>typeof n[c]=="string"&&n[c])||!/^[a-f0-9]{64}$/.test(String(n.changeId))||["namespace","status","groups","url"].some(c=>Object.hasOwn(n,c))||n.hashVersion!==void 0&&n.hashVersion!==2||!Array.isArray(n.variations)||n.variations.length<2||n.variations.length>20||n.urlPatterns!==void 0&&!Array.isArray(n.urlPatterns))throw new Error("Invalid visual experiment");return{...n,variations:n.variations.map(ke)}});return{...e,experiments:l}}var ve=6e4;function qe(e){let l=oe(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),c=F(n),y=F(n),v=`${l}/api/v1/visual-experiments/${e.environmentId}`,I=e.appManifestRelease?`${v}?iam=${e.appManifestRelease}`:v,k=ae(e.deviceIdCookie??"indiana_did"),T=se(),u=null,t=!1,i=!1,x="",S={...e.attributes??{}},G,B,D=0,H=-1/0,$,m=new Map,O=new Map,C=new Set,z=ge({endpoint:`${v}/events`,fetch:n,log:e.log,label:"Visual exposure"}),P=z.flush,W,b;function j(){clearTimeout(W),b?.remove(),b=void 0}function Y(s,d){let f=M(s,d);C.has(f)||e.trackExposures===!1||u?.trackExposures===!1||t||(C.add(f),z.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:k,...T?{sessionId:T}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:s.key,variationKey:d.key}))}function we(s){if(!u||t)return;let d=new Set,f={onExperimentViewed:(r,p)=>{d.add(M(r,p))},url:location.href,attributes:{...me(k,location),...S,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:te(u.savedGroups),log:e.log},h=new Set;for(let r of u.experiments){if(ce(`${e.environmentId}:${r.key}`))continue;let p=r;try{let a=ie(p,f);if(O.set(r.changeId,a),!a.inExperiment)continue;h.add(r.changeId);let w=JSON.stringify([a.key,a.value]),U=m.get(r.changeId);if(U?.signature===w){d.has(M(p,a))&&s.push(()=>{U.applied()&&Y(p,a)});continue}m.get(r.changeId)?.revert(),m.delete(r.changeId);let A=fe(a.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(r.condition?.$and)&&r.condition.$and.some(g=>g!==null&&typeof g=="object"&&!Array.isArray(g)&&g.indianaAppManifestRelease===e.appManifestRelease),boundVariations:r.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{d.has(M(p,a))&&Y(p,a)},onError:g=>e.log?.("Visual experiment stopped",{experiment:r.key,changeId:r.changeId,variation:a.key,error:String(g)}),onTargetStatus:e.log?g=>e.log?.("Visual target status changed",{experiment:r.key,changeId:r.changeId,variation:a.key,...g}):void 0});m.set(r.changeId,{signature:w,revert:A.revert,applied:()=>A.applied,inspect:()=>A.inspect()})}catch(a){e.log?.("Skipping visual experiment",{experiment:r.key,error:String(a)})}}for(let[r,p]of m)h.has(r)||(p.revert(),m.delete(r));j()}let V=()=>{let s=[];pe(()=>we(s));for(let d of s)d()};async function _(){let s=++D,d;try{d=await c.read(I,J)}catch(h){if(t||s!==D)return!1;throw h}let f=q(d);if(f.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return t||s!==D?!1:(u=f,H=performance.now(),!0)}async function Q(){!await _()||t||(N(),V())}function L(){clearTimeout($),$=setTimeout(()=>{if(document.visibilityState==="hidden")return L();Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()})},ve)}let X=()=>{t||document.visibilityState==="hidden"||performance.now()-H<ve||(clearTimeout($),Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()}))},Ie=()=>{x!==location.href&&(x=location.href,V())},Z=()=>{P(!0)},N=()=>{G||t||(G=le(Ie),addEventListener("pagehide",Z),x=location.href)};async function ee(s,d){let f=location.href,h=u,r=[],p=null;if(!t)try{let a=q(await y.read(I,J));a.environmentId===e.environmentId&&(p=a.generation)}catch{}for(let a of h?.experiments??[]){if(s&&a.changeId!==s)continue;let w=O.get(a.changeId);if(!w)continue;let U=new TextEncoder().encode(ye(w.value)),A=[...new Uint8Array(await crypto.subtle.digest("SHA-256",U))].map(be=>be.toString(16).padStart(2,"0")).join(""),g=m.get(a.changeId)?.inspect()??{status:"inactive",total:0,applied:0};r.push({changeId:a.changeId,experimentKey:a.key,variationKey:w.key,inExperiment:w.inExperiment,fingerprint:A,...g})}return{environmentId:e.environmentId,release:e.appManifestRelease??null,generation:h?.generation??null,publishedGeneration:p,checkedAt:new Date().toISOString(),origin:location.origin,pathname:location.pathname,urlMatches:location.href===f&&(!d||d===f)&&h===u,stopped:t,rows:r}}let ne,xe=de(()=>{i&&!t&&V()});return{async start(){if(!(i||t)){i=!0,e.appManifestRelease&&(B=re(e.appManifestRelease)),e.antiFlicker&&(b=document.createElement("style"),e.nonce&&(b.nonce=e.nonce),b.textContent="body { visibility: hidden !important }",document.head.append(b),W=setTimeout(j,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await _()||t)return;N(),V()}finally{j(),t||(L(),document.addEventListener("visibilitychange",X),ne=he({environmentId:e.environmentId,baseUrl:l,origins:e.diagnosticsOrigins,inspect:ee}))}}},async refresh(){t||await _()&&(i&&N(),V())},setAttributes(s){S={...s},V()},flush:()=>P(),getDiagnostics:ee,getResults(){return new Map(O)},get generation(){return u?.generation??null},destroy(){t=!0,clearTimeout($),document.removeEventListener("visibilitychange",X),xe(),ne?.(),D++,c.destroy(),y.destroy(),G?.(),B?.destroy(),removeEventListener("pagehide",Z),j();for(let s of m.values())s.revert();m.clear(),P(!0),u=null,O.clear(),C.clear(),S={}}}}export{qe as createVisualExperiments,Ve as loadAppManifestRelease};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tinkerlandai/longplay-sdk",
3
- "version": "0.10.30",
3
+ "version": "0.10.31",
4
4
  "description": "Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- import{b as Ie}from"./chunk-JWPTJLAN.js";import{a as Q}from"./chunk-TMZGZAWM.js";import{A as Se,E as z,G as Pe,d as pe,f as k,k as me,v as we,w as ge,y as ye}from"./chunk-XHQBABH6.js";import{$ as N}from"./chunk-ITVSLSRM.js";import{a as B,i as J}from"./chunk-B3KFE57L.js";import{b as he}from"./chunk-CLAZ7NVN.js";import{a as c}from"./chunk-HJLGRW4A.js";import{h as G}from"./chunk-XIP32WI7.js";import{b as fe}from"./chunk-OHOROFWN.js";import{b as r}from"./chunk-ZY4XAKNQ.js";import{a as oe}from"./chunk-DSPLGTQI.js";var g=N.options,Ae=r.discriminatedUnion("operation",[g[1].omit({customerToken:!0}),g[2].omit({customerToken:!0}),g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0}),g[8].omit({customerToken:!0}),me.omit({customerToken:!0})]),je=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),Me=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume"]),start:r.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:je}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0})]).optional()}).refine(o=>!o.command||o.requestId===o.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:Ae})]),ae=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:k.shape.run.shape.status}),K={scope:G,customerId:r.uuid()},Ce=r.discriminatedUnion("outcome",[r.strictObject({...K,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...K,outcome:r.literal("resolved"),target:ae,view:k.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((o,d)=>{o.outcome==="resolved"&&(o.access.type==="customer"!=(o.view!==null)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Re=r.strictObject({...K,target:ae,view:k.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:k.shape.purchase.unwrap().nullable()}).superRefine((o,d)=>{let p=o.settlement;(p.acceptance==="accepted"!=(p.receiptPhase!==null)||p.acceptance==="accepted"&&p.basis!=="receipt"||p.acceptance==="unknown"&&(p.state!=="unknown"||p.basis!=="none")||p.acceptance!=="accepted"&&(p.operationId!==null||p.receiptId!==null)||p.acceptance==="not_accepted"&&(p.state!=="settled"||!["run_terminal","position_advanced"].includes(p.basis))||o.purchase&&(o.purchase.receiptId!==p.receiptId||o.purchase.operation&&o.purchase.operation.operationId!==p.operationId||o.purchase.quote&&o.purchase.quote.operationId!==p.operationId)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ee=r.strictObject({...K,target:ae,purchase:k.shape.purchase.unwrap()}).superRefine((o,d)=>{(!o.purchase.operation||typeof o.purchase.canReselect!="boolean"||o.purchase.quote&&o.purchase.quote.operationId!==o.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})});var Ne=N.options[0].refine(o=>!o.customer&&!o.customerData),ke=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),ve=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:G,customerId:r.uuid(),sessionId:r.uuid(),start:Ne,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:pe.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ke).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:we.nullable()})});function be(o){return ye({...o,namespace:"purchases",identity:[o.scope.projectId,o.scope.environment,o.customerId]})}function Oe(o){let d=new URL(o.baseUrl??fe).href,p=()=>new c("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function E(){o.assertCurrent();try{let y=await o.storage.read();if(o.assertCurrent(),!Number.isSafeInteger(y.revision)||y.revision<0)throw p();let a=y.entry===null?null:ve.parse(y.entry);if(a&&(a.baseUrl!==d||a.customerId!==o.customerId||a.scope.projectId!==o.scope.projectId||a.scope.environment!==o.scope.environment))throw new c("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(a?.journal.entry&&(a.journal.entry.scope.projectId!==a.scope.projectId||a.journal.entry.scope.environment!==a.scope.environment||a.journal.entry.funnelId!==a.start.funnelId||a.journal.entry.runId!==a.run?.id||a.journal.entry.versionId!==a.run?.versionId)||a?.operationCommand&&!a.purchases.some(R=>R.operationId===a.operationCommand?.operationId))throw p();return{revision:y.revision,entry:a}}catch(y){throw y instanceof c?y:p()}}async function Y(y){for(let a=0;a<8;a++){let R=await E(),b=y(structuredClone(R.entry));if(JSON.stringify(b)===JSON.stringify(R.entry))return b;b&&ve.parse(b),o.assertCurrent();let v;try{v=await o.storage.write(R.revision,b)}catch{throw p()}if(o.assertCurrent(),v!==null){if(!Number.isSafeInteger(v)||v<=R.revision)throw p();return b}}throw new c("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:E,update:Y,baseUrl:d}}function Te(o){let d=o.purchases.find(p=>p.type==="checkout");if(!o.actions.includes("continue_checkout")||d?.type!=="checkout")throw new c("PURCHASE_PENDING","No single resumable Checkout is confirmed");return d.checkoutUrl}function pn(o){let d={...o,scope:{...o.scope},executionPolicy:structuredClone(o.executionPolicy)},p=d.session.snapshot();if(!p)throw new c("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:E,sessionId:Y}=p,y=!1,a=null,R,b=null,v=!1,q,U,D,O={mode:"idle",status:"idle",actions:["start"],purchases:[]},I=new Map,j=new Map,ie=new AbortController,H=new Set,W=he(d),se=Ie(W.request);function L(e){return{code:e instanceof c?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof c&&e.status!==void 0?{status:e.status}:{}}}function P(){if(y||d.session.snapshot()?.customerId!==E)throw new c("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Oe({...d,customerId:E,assertCurrent:P,storage:d.storage??be({baseUrl:d.baseUrl,scope:d.scope,customerId:E})}),Fe=d.session.subscribeIdentity(ue);function ue(){y||(y=!0,clearTimeout(D),ie.abort(new c("IDENTITY_CHANGED","Purchase consumer was destroyed")),Fe(),a?.reset(),a=null,b=null,W.dispose(),H.clear(),I.clear(),j.clear())}function C(e){P();let n=JSON.stringify(e)!==JSON.stringify(O);O=e,clearTimeout(D),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(D=setTimeout(()=>{T().catch(()=>{})},5e3)),n&&oe(d.onRecovery,structuredClone(e));for(let t of n?H:[]){if(y)break;oe(t,structuredClone(e))}return structuredClone(e)}function h(e){if(P(),!e||e.start.requestId!==R)throw new c("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function F(e){let n=[...e.purchases],t=e.journal.entry?.purchase;return t&&!n.some(u=>u.operationId===t.operationId)&&n.push({receiptId:t.receiptId,operationId:t.operationId,terminal:null}),n}function M(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&F(e).every(n=>n.terminal!==null)}function _(e,n){let t=e.journal.entry?.command??e.journal.entry?.closeCommand,u=F(e).map(S=>{let re=I.get(S.operationId);return S.terminal&&!re?{type:S.terminal,operationId:S.operationId}:B({quote:re?.quote??null,operation:re??null,requestId:t?.requestId??null,pending:!1,destroyed:!1,canReselect:j.get(S.operationId)===!0})}),l=u.filter(S=>!["complete","native"].includes(S.type)),i=l[0],s=l.length===1&&i?.operationId?I.get(i.operationId):void 0;if(s&&(i?.type==="checkout"||i?.type==="cancel"))try{z({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote)}catch(S){return{mode:n,status:"blocked",actions:["refresh",...n==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:u,error:L(S)}}let m;if(n==="operation"&&!t&&i?.type==="cancel"&&s?.quote&&!s.problem&&!s.confirmedAt)try{z({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote),Date.parse(s.quote.expiresAt)>Date.now()&&(m={operationId:s.operationId,quote:s.quote})}catch{}let f=u.length>0&&l.length===0,x=M(e)||n==="operation"&&f&&!t&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":t||e.operationCommand||i&&i.type!=="cancel"||n==="operation"&&!m?"waiting_result":"ready";return{mode:n,status:x,purchases:u,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...M(e)?["start"]:[],...n==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...l.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function $(e){let n=B({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&j.get(e.operationId)===!0});return n.type==="complete"||n.type==="native"?n.type:null}function X(e){if(!e.operation)return;let n={...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}};if(n.merchantExecution&&n.merchantExecution.customerId!==E)throw new c("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let t=J(I.get(n.operationId)??null,n);I.set(n.operationId,t),t===n&&j.set(n.operationId,e.canReselect===!0)}async function qe(e){P();for(let t of[e.purchase,e.run.paywall])t&&X(t);let n=await w.update(t=>{if(h(t),t.run&&(t.run.id!==e.run.id||t.run.versionId!==e.run.source.versionId))throw new c("SCOPE_MISMATCH","The original purchase Run changed");let u=F(t);for(let l of[e.purchase,e.run.paywall]){let i=l?.operation?.operationId??l?.quote?.operationId;if(!l||!i)continue;let s=u.find(f=>f.operationId===i);if(s&&s.receiptId!==l.receiptId)throw new c("INVALID_RESPONSE","The original purchase Receipt changed");let m=$(I.get(i));s?s.terminal??=m:u.push({receiptId:l.receiptId,operationId:i,terminal:m})}return{...t,purchases:u,run:t.run&&(t.run.revision>e.run.revision||!["running","waiting"].includes(t.run.status)&&["running","waiting"].includes(e.run.status))?t.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});h(n),n.run&&!["running","waiting"].includes(n.run.status)&&F(n).some(t=>!t.terminal)&&(n=await Z(n,!n.journal.entry?.command&&!n.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(t=>!!t)))),h(n),C(_(n,"run"))}function _e(){return{async read(){let{entry:e}=await w.read();return h(e),structuredClone(e.journal)},async write(e,n){let t=null;return await w.update(u=>{if(h(u),u.operationCommand&&n?.command&&n.command.operation!=="close")throw new c("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return t=null,u.journal.revision!==e?u:(t=e+1,{...u,journal:{revision:t,entry:n}})}),t}}}async function Z(e,n=!1,t=new Set){h(e);let u=F(e);for(let i of u){if(i.terminal)continue;let s=t.has(i.operationId)?I.get(i.operationId):void 0;if(s??=await ce(e,i),P(),s.operationId!==i.operationId)throw new c("INVALID_RESPONSE","Original Operation changed");if(s.merchantExecution&&s.merchantExecution.customerId!==E)throw new c("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(n&&!e.operationCommand&&B({quote:s.quote??null,operation:s,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){if({operation:s}=await se.attach({operationId:i.operationId,intent:"cancel"}),P(),s.operationId!==i.operationId)throw new c("INVALID_RESPONSE","Original cancellation Operation changed");s=await ce(e,i)}I.set(i.operationId,J(I.get(i.operationId)??null,s))}let l=await w.update(i=>{h(i);let s=i.operationCommand&&I.get(i.operationCommand.operationId);return{...i,...s&&(s.confirmedAt||s.merchantExecution||s.status!=="pending")?{operationCommand:void 0}:{},purchases:F(i).map(m=>({...m,terminal:m.terminal??$(I.get(m.operationId))}))}});return h(l),l}async function ee(e){P();let n=await W.request("funnels",e);return P(),n}async function ce(e,n){let t=Q(Ee,await ee({operation:"recover_purchase",runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:n.receiptId,operationId:n.operationId}}));if(ne(e,t),t.purchase.receiptId!==n.receiptId||t.purchase.operation?.operationId!==n.operationId)throw new c("INVALID_RESPONSE","Original purchase reference changed");return X(t.purchase),I.get(n.operationId)}async function le(e){for(let n of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!n)continue;let t=Q(Re,await ee({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:n.requestId,...n.operation==="resume"?{}:{command:n}}));if(ne(e,t),t.settlement.requestId!==n.requestId)throw new c("INVALID_RESPONSE","Original command settlement changed");t.purchase&&X(t.purchase);let u=await w.update(l=>{h(l);let i=F(l),{receiptId:s,operationId:m}=t.settlement;if(s&&m){let x=i.find(S=>S.operationId===m);if(x&&x.receiptId!==s)throw new c("INVALID_RESPONSE","Original Receipt changed");x||i.push({receiptId:s,operationId:m,terminal:$(I.get(m))})}let f=t.settlement.state==="settled"?ge(l.journal.entry,n.requestId):l.journal.entry;return{...l,purchases:i,journal:f===l.journal.entry?l.journal:{revision:l.journal.revision+1,entry:f}}});h(u),e=u}return e}function ne(e,n){if(n.customerId!==E||n.scope.projectId!==d.scope.projectId||n.scope.environment!==d.scope.environment||n.target.funnelId!==e.start.funnelId||n.target.startRequestId!==e.start.requestId||e.run&&(n.target.runId!==e.run.id||n.target.versionId!==e.run.versionId))throw new c("SCOPE_MISMATCH","The original recovery binding changed")}async function te(e,n){if(h(e),e.run&&(e=await le(e)),!F(e).length&&M(e))return C(_(e,"operation"));if(!F(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(n)});v=!0;let t=await Z(e);return C(_(t,"operation"))}async function V(e,n=!1,t=!0){if(R=e.start.requestId,b=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!a){let u=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:n?"resume":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},l;try{l=await ee(u)}catch(f){if(!e.run&&f instanceof c&&(f.status===void 0||f.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:O.purchases,error:L(f)});throw f}let i=Q(Ce,l);if(i.customerId!==E||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new c("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:O.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});ne(e,i);let s=await w.update(f=>(h(f),{...f,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??f.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(h(s),e=s,i.access.type==="operation_only")return te(e,new c("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await le(e);let m=i.view;if(m.locale!==e.start.locale||!Se(m.parameters,e.start.parameters))throw new c("INVALID_RESPONSE","The original Start input changed");a=Pe({...d,customerRun:{runId:i.target.runId,customerId:E,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(f=>d.executionPolicy.allowed.includes(f))},funnelCommandStorage:_e(),onAcceptedResponse:qe},{scope:i.scope,run:m})}try{await a.get(),a.view?.pendingRequest?.requestId===e.start.requestId&&!a.pendingCommands?.length&&await a.resume(a.view.pendingRequest.requestId);for(let l of a.pendingCommands??[])l.operation!=="close"&&await a.settle?.(l.requestId);a.pendingCommands?.length&&await a.retry(),P();let u=(await w.read()).entry;return h(u),C(_(u,"run"))}catch(u){if(P(),t&&u instanceof c&&(u.status===401||u.status===409&&u.reason==="STATE_CHANGED")){a.reset(),a=null;let l=(await w.read()).entry;return h(l),V(l,!1,!1)}throw u}}function A(e,n="read"){if(P(),q)return n==="read"||n===U?q:q.then(()=>A(e,n),()=>A(e,n));clearTimeout(D);let t=e().catch(u=>{throw y||C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:O.purchases,error:L(u)}),u});return q=t,U=n,t.then(()=>{q===t&&(q=void 0,U=void 0)},()=>{q===t&&(q=void 0,U=void 0)}),t}function T(){return A(async()=>{let{entry:e}=await w.read();return e?(R&&e.start.requestId!==R&&(a?.reset(),a=null,I.clear(),j.clear()),v&&R===e.start.requestId?te(e,O.error):V(e)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}async function de(){let e=await T();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:A(async()=>{let n=(await w.read()).entry;if(h(n),!v){if(!a?.view?.paywall?.quote)throw new c("PURCHASE_PENDING","Read the original quote before confirming");let s=a.view.paywall.operation;if(s?.confirmedAt||s?.merchantExecution||s&&s.status!=="pending")return C(_(n,"run"));if(a.pendingCommands?.length)await a.retry();else{let f=a.view;await a.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:f.nodeId,visit:f.visit,revision:f.revision,input:{type:"paywall_confirm",operationId:f.paywall.quote.operationId}})}let m=(await w.read()).entry;return h(m),C(_(m,"run"))}let t=n.operationCommand?.operationId??O.confirmation?.operationId,u=t&&I.get(t);if(!t||!u||n.journal.entry?.command||n.journal.entry?.closeCommand)throw new c("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");z({allowed:n.allowed.filter(s=>d.executionPolicy.allowed.includes(s))},u.quote),await w.update(s=>{if(h(s),s.journal.entry?.command||s.journal.entry?.closeCommand||s.operationCommand&&s.operationCommand.operationId!==t)throw new c("PURCHASE_PENDING","Another original command is pending");return{...s,operationCommand:{operationId:t,intent:"confirm"}}});let l=await se.attach({operationId:t,intent:"confirm"});if(P(),l.operation.operationId!==t)throw new c("INVALID_RESPONSE","Original confirmation Operation changed");I.set(t,J(u,l.operation));let i=(await w.read()).entry;return h(i),C(_(await Z(i,!1,new Set([t])),"operation"))},"confirm")}return{get controller(){return a},get recovery(){return structuredClone(O)},get attempt(){return P(),structuredClone(b)},get identitySignal(){return ie.signal},start(e){let n=N.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(n.operation!=="start"||n.customer||n.customerData)throw new c("INVALID_REQUEST","A Customer-owned Funnel start is required");return A(async()=>{let t=await w.update(u=>{if(u&&!M(u)){if(u.start.funnelId!==n.funnelId)throw new c("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return u}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:E,sessionId:Y,start:n,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!t)throw new c("PURCHASE_STORAGE_INVALID","Original start was not retained");return R!==t.start.requestId&&(a?.reset(),a=null,I.clear(),j.clear(),v=!1),v?te(t,O.error):V(t,!0)},`start:${n.funnelId}`)},refresh:T,confirm:de,retry:()=>v?de():A(async()=>{let{entry:e}=await w.read();return e?V(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return a?.view?A(async()=>{if(!a?.view)throw new c("PURCHASE_PENDING","Recover the original Run before closing");if(a.pendingCommands?.find(t=>t.operation==="close"))await a.retry();else if(["running","waiting"].includes(a.view.status)){let t=a.view;await a.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision})}let n=(await w.read()).entry;return h(n),C(_(n,"run"))},"close"):T()},async continueCheckout(e){let n=await T();P(),await e(Te(n))},subscribe(e){return H.add(e),()=>{H.delete(e)}},destroy:ue}}export{be as a,Te as b,pn as c};
@@ -1 +0,0 @@
1
- import{p as n,s as t}from"./chunk-XHQBABH6.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};